diff --git a/CHANGELOG.md b/CHANGELOG.md index 8eb5299c1..fc562afb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.3 -Update from Maintenance > Update as usual - this release has three database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, and 4.2.4 lets a ticket keep its pictures as files. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. +Update from Maintenance > Update as usual - this release has four database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, and 4.2.5 adds identity providers. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. ### New Features & Updates @@ -29,6 +29,11 @@ Update from Maintenance > Update as usual - this release has three database chan - Pictures already inside tickets move to files in the background - the new Ticket Pictures job in Maintenance > Cron does a batch every minute until every ticket is done, then keeps an eye on new ones. - Taking a picture out of a reply or the ticket's details when editing it, or redacting it, deletes it - it no longer opens from an old link. Redact now takes a picture selected on its own, as well as text. - A picture from an internal note put in a reply the client sees, or from a ticket merged into another, is copied, so it shows for the client and stays when the other is deleted. +- Identity providers: agents and client contacts can sign in with their Microsoft 365, Google Workspace or Nextcloud account, each a button on the sign-in page, or with their mail password through an IMAP server. Set them up in the new Admin > Identity Providers, under Integrations: each is for agents, client contacts or both, and for the email domains you list. Only people already in ITFlow sign in - an agent, or a contact with portal access, with the same email address - and no one new is added. +- Microsoft 365, Google Workspace and Nextcloud do their own sign-in checks, so ITFlow doesn't ask for its two-step code after them, and they meet a role's or the client portal's requirement for it. A mail password (IMAP) is still asked for the code. +- An identity provider can be required: the accounts on its email domains then can't sign in with a password, and the sign-in page says which button to use. Passkeys still work, and an agent with an administrator role keeps their password, to get back in if the provider is down. +- An agent who signs in with an identity provider or their mail password finds their credentials locked, as after some passkeys: the first username or password they open asks for their ITFlow password, once, until they sign out. +- Admin > Settings > Single Sign-on is gone: the client portal's Microsoft 365 sign-in is now a Microsoft 365 identity provider. A contact's Login of Only with an identity provider (once called With their Microsoft account) signs in only that way, with no password, and is offered when a provider is on for client contacts. ### Bug Fixes @@ -59,6 +64,10 @@ Update from Maintenance > Update as usual - this release has three database chan - A list table with .itflow-list-stack (css/itflow_custom.css) stacks below 768px: each row a grid card with the tick box, first cell and last (the menu) across the top and every other cell under them labelled from its data-label, and the head a wrapping row of its sort links. Used on agent/ticket_list.php, agent/credentials.php, agent/assets.php and agent/contacts.php (contacts and invites); the ticket row's phone-only line of status, priority and client is gone, as the card shows them. - agent/modals/document/document_view.php uses .itflow-prose and linkGroupsHtml()'s compact mode, which takes $open_up_to (5 by default, 0 for the quick view: always closed). Its Edit goes to agent/document_edit.php, so agent/modals/document/document_edit.php, which only it opened, is gone. - A document's editor is .tinymce-document (agent/modals/document/document_form.php; .tinymce-page on agent/document_edit.php): js/app.js itflowDocumentWriter, the document editor with its own toolbar and itflowProseContentStyle() - .itflow-prose as literal CSS, as the editor is an iframe. The page's editor saves on Ctrl+S (addShortcut), the fields and Markdown box through a keydown on the page; the Markdown Preview has .itflow-prose; Markdown pasted into the editor (js/document_markdown.js) takes .tinymce-document too. Other editors (.tinymce) are as they were. +- Database 4.2.5: identity_providers (kind microsoft, google, nextcloud or imap; name, on, agents, contacts, domains, required, client id and secret, tenant, url, port, security, username, redirect_path, used_at). settings.config_azure_client_id and config_azure_client_secret are copied to a microsoft provider for contacts with redirect_path /client/login_microsoft.php, then dropped; users.user_auth_method azure now means only through an identity provider. +- functions/identity_provider.php: the kinds, who a provider covers (identityProviderCovers(), identityProviderFor(), identityProviderRequiredFor(), identityProviderImapFor()), the OpenID Connect code flow with PKCE S256 (identityProviderEndpoints() - Microsoft and Google fixed, Nextcloud from its discovery document; identityProviderAuthorizeUrl(), identityProviderIdentity()) and the IMAP check (identityProviderImapCheck(), DirectoryTree ImapEngine, certificate checked). Microsoft's address is Graph /me userPrincipalName (guests refused), Google's needs email_verified. +- login_provider.php starts a sign-in (?provider=N, a single-use state in the session, ten minutes) and takes the code back, then hands the account to login.php as ?provider_login= with $_SESSION['pending_provider_login'], which signs in through its usual success path - role choice included - with $_SESSION['signed_in_with'] = 'provider' (left out of MFA enforcement as a passkey is) and signed_in_via the provider's name. client/login_microsoft.php serves it for the migrated app's redirect address. IMAP is checked in login.php's password step ('imap'); an administrator's own password still works there. +- Admin: admin/identity_providers.php (list), admin/modals/identity_provider/identity_provider_edit.php (Add and Edit), admin/post/identity_provider.php (save_identity_provider, turn_identity_provider_on / off, delete_identity_provider - locked in the demo). The identity settings page and edit_identity_provider are gone. portalSignInMethods() and identityProviderContactsWording() take an email, to offer only the providers that sign it in; vaultLockedReason() says why the vault is locked. ## [26.12.2] diff --git a/admin/database_updates/4.2.5.php b/admin/database_updates/4.2.5.php new file mode 100644 index 000000000..65674690c --- /dev/null +++ b/admin/database_updates/4.2.5.php @@ -0,0 +1,62 @@ + Identity Providers): agents and + * client contacts signing in with Microsoft 365, Google Workspace, Nextcloud or their mail + * password (IMAP). identity_providers - each one's kind and name, whether it is on, who it signs + * in (agents, contacts) and on which email domains, whether it is required, its app's ID and + * secret, its tenant (Microsoft), address (Nextcloud, or the IMAP server with its port, security + * and username style), the path it sends people back to, and when it was last used. + * + * The Microsoft Entra app the client portal signed in with (settings.config_azure_client_id and + * config_azure_client_secret) becomes the first provider, for client contacts on any domain, still + * sending them back to /client/login_microsoft.php - the address registered with it - and the two + * settings go. Contacts set to sign in with Microsoft keep that (users.user_auth_method azure), + * now meaning through an identity provider, without a password. Re-runnable. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `identity_providers` ( + `identity_provider_id` int(11) NOT NULL AUTO_INCREMENT, + `identity_provider_kind` varchar(20) NOT NULL, + `identity_provider_name` varchar(100) NOT NULL, + `identity_provider_enabled` tinyint(1) NOT NULL DEFAULT 1, + `identity_provider_agents` tinyint(1) NOT NULL DEFAULT 0, + `identity_provider_contacts` tinyint(1) NOT NULL DEFAULT 0, + `identity_provider_domains` varchar(1000) NOT NULL DEFAULT '', + `identity_provider_required` tinyint(1) NOT NULL DEFAULT 0, + `identity_provider_client_id` varchar(255) NOT NULL DEFAULT '', + `identity_provider_client_secret` varchar(1000) NOT NULL DEFAULT '', + `identity_provider_tenant` varchar(100) NOT NULL DEFAULT '', + `identity_provider_url` varchar(500) NOT NULL DEFAULT '', + `identity_provider_port` int(11) NOT NULL DEFAULT 0, + `identity_provider_security` varchar(10) NOT NULL DEFAULT '', + `identity_provider_username` varchar(10) NOT NULL DEFAULT '', + `identity_provider_redirect_path` varchar(100) NOT NULL DEFAULT '/login_provider.php', + `identity_provider_used_at` datetime DEFAULT NULL, + `identity_provider_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `identity_provider_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + PRIMARY KEY (`identity_provider_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + // The client portal's Microsoft Entra app, as the first provider - once + $itflow_azure_column = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'config_azure_client_id' LIMIT 1"); + if ($itflow_azure_column && mysqli_num_rows($itflow_azure_column) > 0) { + $itflow_azure = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_azure_client_id, config_azure_client_secret FROM settings WHERE company_id = 1")); + $itflow_azure_id = trim((string) ($itflow_azure['config_azure_client_id'] ?? '')); + $itflow_azure_secret = trim((string) ($itflow_azure['config_azure_client_secret'] ?? '')); + $itflow_providers = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM identity_providers"))[0] ?? 0); + if ($itflow_azure_id !== '' && $itflow_providers === 0) { + mysqli_query($mysqli, "INSERT INTO identity_providers SET identity_provider_kind = 'microsoft', identity_provider_name = 'Microsoft 365', + identity_provider_enabled = 1, identity_provider_agents = 0, identity_provider_contacts = 1, + identity_provider_client_id = '" . mysqli_real_escape_string($mysqli, $itflow_azure_id) . "', + identity_provider_client_secret = '" . mysqli_real_escape_string($mysqli, $itflow_azure_secret) . "', + identity_provider_redirect_path = '/client/login_microsoft.php'"); + } + mysqli_query($mysqli, "ALTER TABLE `settings` DROP COLUMN `config_azure_client_id`, DROP COLUMN `config_azure_client_secret`"); + } diff --git a/admin/identity_providers.php b/admin/identity_providers.php index 6f2ad488e..3a251743b 100644 --- a/admin/identity_providers.php +++ b/admin/identity_providers.php @@ -1,56 +1,205 @@ Settings > Single sign-on - client contacts signing in to the - * portal with their Microsoft 365 account (client/login_microsoft.php), - * through an app registered in Microsoft Entra. The secret is never put back - * into the page: left empty it stays as saved. Saved by - * edit_identity_provider (admin/post/identity_provider.php). + * Admin > Identity Providers - the ways agents and client contacts sign in besides their ITFlow + * password (functions/identity_provider.php): Microsoft 365, Google Workspace and Nextcloud, each + * a button on the sign-in page, and IMAP, which checks the password typed there with a mail + * server. Each row says what it is, who it signs in and on which email domains, whether it is + * required, and when it was last used. New is a menu of the kinds; Add and Edit are one window + * (modals/identity_provider/identity_provider_edit.php); the rest are + * admin/post/identity_provider.php. */ +// Default Column Sortby Filter +$sort = "identity_provider_name"; +$order = "ASC"; + require_once "includes/inc_all_admin.php"; -$redirect_uri = 'https://' . preg_replace('#^https?://#', '', rtrim((string) $config_base_url, '/')) . '/client/login_microsoft.php'; -$secret_saved = trim((string) $config_azure_client_secret) !== ''; +// The table arrives with the 4.2.5 database update +if (!identityProvidersReady()) { ?> +
Identity Providers arrive with a database update - run it in Maintenance > Update first.
+ "identity_provider_name $order", + 'identity_provider_kind' => "identity_provider_kind $order, identity_provider_name ASC", + 'identity_provider_used_at' => "identity_provider_used_at IS NULL, identity_provider_used_at $order, identity_provider_name ASC", +]; +if (!isset($sortable_columns[$sort])) { + $sort = 'identity_provider_name'; +} + +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS * FROM identity_providers + WHERE (identity_provider_name LIKE '%$q%' OR identity_provider_domains LIKE '%$q%' OR identity_provider_kind LIKE '%$q%' OR identity_provider_url LIKE '%$q%') + ORDER BY {$sortable_columns[$sort]}, identity_provider_id ASC + LIMIT $record_from, $record_to"); + +$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); + +$csrf = $_SESSION['csrf_token']; +$add_url = 'modals/identity_provider/identity_provider_edit.php?kind='; ?> -
- - -
-
- -
The client portal is off - turn it on in Modules.
- - - -
- - +
+
+

Identity Providers

+
+
+ + -
- -
- - - -
-
Under Authentication in the app registration, as a Web platform.
-
- 'fa-fingerprint', 'maxlength' => 200, 'placeholder' => 'e721e3b6-01d6-50e8-7f22-c84d951a52e7', - 'help' => 'From the app\'s Overview. Empty turns signing in with Microsoft off, and forgets the secret.']) ?> - 'fa-key', 'type' => 'password', 'maxlength' => 200, 'autocomplete' => 'new-password', - 'placeholder' => $secret_saved ? 'Saved - type a new one to replace it' : 'From Certificates & secrets', - 'help' => 'Its Value, not its ID. A secret runs out - put the new one here before it does.']) ?> - - - +
- + +
+ The client portal is off in Modules, so identity providers sign in agents only. +
+ +
+
+
+
+
+ + +
+
+
+
+
+
+ + "> + + + + + + + + + + + + + + + + + + + + + +
Signs inEmail domains
+
+ +
+ + + + + Unknown kind + + + Off + + + Required + +
+
·
+
+
+
+ + No one + + + Agents + + + >Client contacts + + Any email domain' ?> + + + + Not yet + + + +
+
+ 'identity providers', + 'icon' => 'fa-id-badge', + 'text' => 'Let agents and client contacts sign in with their Microsoft 365, Google Workspace or Nextcloud account, or with their mail password through an IMAP server - picked by the domain of their email address. No one new is added: the account has to be in ITFlow already.', + 'actions' => array_map(function ($key, $info) use ($add_url) { + return ['label' => $info['name'], 'icon' => 'fa-plus', 'modal' => $add_url . $key, 'size' => 'lg']; + }, array_keys($kinds), $kinds), + ]; + ?> + +
Phone Systems

+
@@ -62,7 +62,7 @@ if (!$portal_user) { ?>
> -
+
diff --git a/admin/post/identity_provider.php b/admin/post/identity_provider.php index f4d36fe9c..01e4a4633 100644 --- a/admin/post/identity_provider.php +++ b/admin/post/identity_provider.php @@ -1,37 +1,87 @@ Settings > Single sign-on (admin/identity_providers.php): - * edit_identity_provider saves the Microsoft Entra app the client portal - * signs in with. A secret left empty stays as saved; an empty app ID turns - * it off and forgets the secret. An ID that isn't one, or an app with no - * secret, comes back to the page saying so - nothing is saved. + * Admin > Identity Providers (functions/identity_provider.php) - Add and Edit, turning one off and + * on, and Delete. What changed is in the audit log - never the secret. */ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); -if (isset($_POST['edit_identity_provider'])) { +if (isset($_POST['save_identity_provider'])) { validateCSRFToken(); - $before = settingsCurrent(['config_azure_client_id', 'config_azure_client_secret']); - - $client_id = trim((string) ($_POST['config_azure_client_id'] ?? $before['config_azure_client_id'])); - $secret = trim((string) ($_POST['config_azure_client_secret'] ?? '')); - $after = ['config_azure_client_id' => $client_id, 'config_azure_client_secret' => $client_id === '' ? '' : ($secret !== '' ? $secret : (string) $before['config_azure_client_secret'])]; - - $errors = []; - if ($client_id !== '' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $client_id)) { - $errors['config_azure_client_id'] = 'The Application (client) ID - 32 letters and numbers in five groups, as e721e3b6-01d6-50e8-7f22-c84d951a52e7.'; - } elseif ($client_id !== '' && $after['config_azure_client_secret'] === '') { - $errors['config_azure_client_secret'] = 'And a secret for it, from Certificates & secrets.'; + if (!identityProvidersReady()) { + flashAlert('Identity providers arrive with a database update - run it first.', 'error'); + redirect('update.php'); } + + $identity_provider_id = intval($_POST['identity_provider_id'] ?? 0); + $before = $identity_provider_id ? identityProviderRow($identity_provider_id) : null; + if ($identity_provider_id && !$before) { + flashAlert('That identity provider no longer exists.', 'error'); + redirect('identity_providers.php'); + } + + [$after, $errors] = identityProviderCheck($_POST, $before); if ($errors) { - settingsRefuse('identity', $errors); + flashAlert('Not saved - ' . escapeHtml(reset($errors)), 'error'); + redirect(); } - settingsSave('identity', $before, $after); + $name = $after['identity_provider_name']; + $kind = identityProviderKinds()[$after['identity_provider_kind']]; + if ($before) { + $lines = identityProviderChangeLines($before, $after); + if (!$lines) { + flashAlert('Nothing changed on ' . escapeHtml($name) . '', 'info'); + redirect(); + } + identityProviderWrite($after, $identity_provider_id); + logAudit("Identity Provider", "Edit", "$session_name changed identity provider " . escapeSql($before['identity_provider_name'] . ': ' . implode('; ', $lines)), 0, $identity_provider_id); + flashAlert('' . escapeHtml($name) . ' saved'); + redirect(); + } + $identity_provider_id = identityProviderWrite($after); + logAudit("Identity Provider", "Create", "$session_name added identity provider " . escapeSql($name . ($name !== $kind['name'] ? " ({$kind['name']})" : '') . ($after['identity_provider_domains'] !== '' ? ' for ' . $after['identity_provider_domains'] : '')), 0, $identity_provider_id); + flashAlert('' . escapeHtml($name) . ' created' . ($kind['oauth'] ? ' - its button is on the sign-in page' : '')); + redirect('identity_providers.php'); + +} + +// Turn it off - no one signs in with it - or on again +if (isset($_GET['turn_identity_provider_off']) || isset($_GET['turn_identity_provider_on'])) { + + validateCSRFToken(); + + $on = isset($_GET['turn_identity_provider_on']); + $provider = identityProviderRow($on ? $_GET['turn_identity_provider_on'] : $_GET['turn_identity_provider_off']); + if (!$provider) { + flashAlert('That identity provider no longer exists.', 'error'); + redirect('identity_providers.php'); + } + $identity_provider_id = intval($provider['identity_provider_id']); + mysqli_query($mysqli, "UPDATE identity_providers SET identity_provider_enabled = " . ($on ? 1 : 0) . " WHERE identity_provider_id = $identity_provider_id"); + logAudit("Identity Provider", "Edit", "$session_name turned identity provider " . escapeSql($provider['identity_provider_name']) . ($on ? ' on' : ' off'), 0, $identity_provider_id); + flashAlert('' . escapeHtml($provider['identity_provider_name']) . ' turned ' . ($on ? 'on' : 'off - no one signs in with it'), $on ? 'success' : 'error'); redirect(); } + +if (isset($_GET['delete_identity_provider'])) { + + validateCSRFToken(); + + $provider = identityProviderRow($_GET['delete_identity_provider']); + if (!$provider) { + flashAlert('That identity provider no longer exists.', 'error'); + redirect('identity_providers.php'); + } + $identity_provider_id = intval($provider['identity_provider_id']); + mysqli_query($mysqli, "DELETE FROM identity_providers WHERE identity_provider_id = $identity_provider_id"); + logAudit("Identity Provider", "Delete", "$session_name deleted identity provider " . escapeSql($provider['identity_provider_name']), 0, $identity_provider_id); + flashAlert('' . escapeHtml($provider['identity_provider_name']) . ' deleted', 'error'); + redirect('identity_providers.php'); + +} diff --git a/admin/settings.php b/admin/settings.php index 6d73a7ff1..cc856a858 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -54,7 +54,6 @@ $summaries = [ 'notification' => 'Domain alerts ' . $on_off($config_enable_alert_domain_expire) . ' · ticket emails to clients ' . $on_off($config_ticket_client_general_notifications), 'security' => 'Login key ' . $on_off($config_login_key_required) . ' · devices remembered ' . $days($config_login_remember_me_expire), 'client_portal' => 'Two-step sign-in ' . ($config_client_portal_require_mfa ? 'required' : 'optional'), - 'identity' => 'Microsoft Entra ' . ($config_azure_client_id ? 'set up' : 'not set up'), 'module' => $modules_on ? escapeHtml(implode(', ', $modules_on)) : 'None in use', 'telemetry' => $config_telemetry ? 'Nightly report on' : 'Off', ]; diff --git a/admin/settings_client_portal.php b/admin/settings_client_portal.php index 33272aaa5..5bb7e09e0 100644 --- a/admin/settings_client_portal.php +++ b/admin/settings_client_portal.php @@ -39,8 +39,8 @@ $signup_clients = $signup_ready ? portalSignupClients() : []; - Single sign-on is set up' . (empty($config_azure_client_id) ? ' (it isn\'t yet)' : '') . '.') ?> - 'requireMfa', 'help' => 'Contacts who sign in with a password are asked for a code from an authenticator app too. Anyone without it set up is taken to set it up before anything else. Microsoft 365 sign-ins are left to Microsoft.']) ?> + identity provider signs in contacts' . (identityProviderNamesForContacts() || array_filter(identityProvidersOn(), function ($p) { return $p['identity_provider_kind'] === 'imap' && intval($p['identity_provider_contacts']) === 1; }) ? '' : ' (none does yet)') . '.') ?> + 'requireMfa', 'help' => 'Contacts who sign in with a password are asked for a code from an authenticator app too. Anyone without it set up is taken to set it up before anything else. A sign-in through an identity provider is left to it, but a mail password (IMAP) is asked for a code too.']) ?> diff --git a/admin/users.php b/admin/users.php index 990d25d2a..9a98ff9a9 100644 --- a/admin/users.php +++ b/admin/users.php @@ -75,7 +75,7 @@ $portal_never_sql = "NOT EXISTS (SELECT 1 FROM logs WHERE log_user_id = users.us $portal_accesses = [ '' => ['label' => 'Can sign in', 'icon' => 'fas fa-check-circle', 'where' => PORTAL_USER_ON_SQL], 'local' => ['label' => 'Password', 'icon' => 'fas fa-key', 'where' => PORTAL_USER_ON_SQL . " AND user_auth_method = 'local'"], - 'azure' => ['label' => 'Microsoft 365', 'icon' => 'fab fa-microsoft', 'where' => PORTAL_USER_ON_SQL . " AND user_auth_method = 'azure'"], + 'azure' => ['label' => 'Identity provider', 'icon' => 'fas fa-id-badge', 'where' => PORTAL_USER_ON_SQL . " AND user_auth_method = 'azure'"], 'nomfa' => ['label' => 'No two-step', 'icon' => 'fas fa-unlock', 'where' => PORTAL_USER_ON_SQL . " AND user_auth_method = 'local' AND (user_token IS NULL OR user_token = '')"], 'never' => ['label' => 'Never signed in', 'icon' => 'fas fa-user-clock', 'where' => PORTAL_USER_ON_SQL . " AND $portal_never_sql"], 'off' => ['label' => 'Access off', 'icon' => 'fas fa-ban', 'where' => 'NOT (' . PORTAL_USER_ON_SQL . ')'], @@ -446,8 +446,8 @@ $csrf = $_SESSION['csrf_token']; $login = $portal_logins[$user_id] ?? null; $remember_count = $portal_remembered[$user_id] ?? 0; $sign_in_pills = $is_on - ? '' . ($is_local ? 'Password' : 'Microsoft 365') . '' . ($is_local ? ' ' . $portal_two_step($row) : '') + ? '' . ($is_local ? 'Password' : 'Identity provider') . '' . ($is_local ? ' ' . $portal_two_step($row) : '') : 'Access off'; ?> diff --git a/agent/modals/contact/contact_form.php b/agent/modals/contact/contact_form.php index 2a0cd161f..b7c68b8ca 100644 --- a/agent/modals/contact/contact_form.php +++ b/agent/modals/contact/contact_form.php @@ -223,7 +223,7 @@ $contact_roles = [
diff --git a/client/functions.php b/client/functions.php index 03df9c9f9..cdd614d86 100644 --- a/client/functions.php +++ b/client/functions.php @@ -639,7 +639,7 @@ function portalContactRoles(array $row) { /** * Give a contact of this client portal access and email them how to sign in - - * a link to set their password, or for Microsoft a link to the sign-in page. + * a link to set their password, or for an identity provider a link to the sign-in page. * Makes their portal user when they have none, turns it back on when it was * off, and sends the invite again when it is on. $by is the primary contact * doing it. ['ok' => bool, 'error' => why not, 'emailed' => bool]. @@ -654,7 +654,7 @@ function portalContactInvite($contact_id, $method, $by) { if (!$contact) { return ['ok' => false, 'error' => "That person isn't here", 'emailed' => false]; } - if (!isset(portalSignInMethods()[$method])) { + if (!isset(portalSignInMethods($contact['contact_email'])[$method])) { $method = 'local'; } $name = (string) $contact['contact_name']; @@ -675,7 +675,7 @@ function portalContactInvite($contact_id, $method, $by) { mysqli_query($mysqli, "UPDATE contacts SET contact_user_id = $user_id WHERE contact_id = $contact_id AND contact_client_id = $client_id"); } - // The email - a link to set their password, or for Microsoft the sign-in page (functions/portal.php) + // The email - a link to set their password, or for an identity provider the sign-in page (functions/portal.php) $emailed = portalMailInvite($user_id, $by); if (!$emailed && $method !== 'local') { portalPasswordLinkClear($user_id); diff --git a/client/includes/check_login.php b/client/includes/check_login.php index 6907988f9..475c5fc52 100644 --- a/client/includes/check_login.php +++ b/client/includes/check_login.php @@ -123,7 +123,7 @@ if (!$portal_view_as) { // in the request (requestIsMfaSetup()). // A passkey sign-in is two-step sign-in already (functions/passkey.php) $portal_mfa_setup_needed = !$portal_view_as && intval($config_client_portal_require_mfa ?? 0) === 1 && $session_auth_method === 'local' && !$session_mfa_on - && ($_SESSION['signed_in_with'] ?? '') !== 'passkey'; + && !in_array($_SESSION['signed_in_with'] ?? '', ['passkey', 'provider'], true); if ($portal_mfa_setup_needed && !requestIsMfaSetup([ 'client/profile.php' => [[['mfa'], []]], 'client/post.php' => [[[], ['csrf_token', 'portal_mfa_enable', 'verify_code']], [['logout'], []]], diff --git a/client/join.php b/client/join.php index 68880d4ed..f6ddf7a3e 100644 --- a/client/join.php +++ b/client/join.php @@ -3,7 +3,7 @@ * Client Portal * Joining - from an invite (ours, or a colleague's in the portal) or the link * to finish signing up: ?invite=&token=. The person puts in their name, job - * title, phone and a password - or, when Microsoft 365 sign-in is set up, + * title, phone and a password - or, when an identity provider signs in their address, * chooses that instead - and is made a contact who can sign in * (portalInviteAccept(), functions/portal_invite.php). Then they sign in on * the usual page. A link that has run out, been used or cancelled says so, @@ -43,6 +43,8 @@ $error = ''; $in = ['name' => '', 'title' => '', 'phone' => '']; if ($invite && $link['state'] === 'pending') { + // Only an identity provider that signs in their address (functions/identity_provider.php) + $methods = portalSignInMethods($invite['invite_email']); $who = portalInviteWho($invite['invite_email'], $invite['invite_client_id']); $in['name'] = trim((string) $invite['invite_name']) !== '' ? (string) $invite['invite_name'] : (string) ($who['name'] ?? ''); @@ -61,7 +63,7 @@ if ($invite && $link['state'] === 'pending') { if ($contact_id) { $first = strtok(trim(preg_replace('/\s+/', ' ', $in['name'])), ' '); $_SESSION['login_message'] = "Welcome, $first - your account is ready. " . (isset($methods[$method]) && $method === 'azure' - ? 'Sign in with your Microsoft 365 account below.' + ? 'Sign in with your ' . identityProviderContactsWording($invite['invite_email']) . ' account below.' : 'Sign in with ' . $invite['invite_email'] . ' and your new password.'); $_SESSION['login_message_type'] = 'success'; redirect("/login.php"); @@ -169,7 +171,7 @@ $title = $state === 'pending' ? ($signup ? 'Finish signing up' : 'Join ' . $invi
or, with no password here
- + diff --git a/client/login_microsoft.php b/client/login_microsoft.php index 2ca200eeb..3419fc0b9 100644 --- a/client/login_microsoft.php +++ b/client/login_microsoft.php @@ -1,203 +1,10 @@ $client_id, - 'redirect_uri' => $redirect_uri, - 'response_type' => 'code', - // Must come back as a top-level GET - a SameSite=Lax session cookie is - // not sent on the cross-site POST that form_post produces - 'response_mode' => 'query', - 'scope' => 'https://graph.microsoft.com/User.Read', - 'state' => $state); - - redirect($auth_code_url . '?' . http_build_query($params)); - -} - -// Microsoft has redirected back with an authorization code (or an error) -// Request an access token using authorization code (& client secret) (server side) -if (isset($_GET['code']) || isset($_GET['error'])) { - - $state = is_string($_GET['state'] ?? null) ? $_GET['state'] : ''; - $session_state = $_SESSION['azure_oauth_state'] ?? ''; - $session_state_expires = intval($_SESSION['azure_oauth_state_expires_at'] ?? 0); - - // Single use, consumed whether or not it validates - unset($_SESSION['azure_oauth_state'], $_SESSION['azure_oauth_state_expires_at']); - - if (!empty($_GET['error'])) { - $_SESSION['login_message'] = 'Something went wrong with logging you in: Microsoft returned an error. Please try again.'; - redirect("../login.php"); - } - - if (empty($state) || empty($session_state) || !hash_equals($session_state, $state) || time() > $session_state_expires) { - $_SESSION['login_message'] = 'Something went wrong with logging you in: the sign-in request could not be verified. Please try again.'; - redirect("../login.php"); - } - - $params = array ( - 'client_id' =>$client_id, - 'code' => is_string($_GET['code'] ?? null) ? $_GET['code'] : '', - 'redirect_uri' => $redirect_uri, - 'grant_type' => 'authorization_code', - 'client_secret' => $client_secret - ); - - // Send request via CURL (server side) so user cannot see the client secret - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $token_grant_url); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt( - $ch, - CURLOPT_POSTFIELDS, - http_build_query($params) - ); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); - curl_setopt($ch, CURLOPT_TIMEOUT, 30); - #curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP - - $access_token_response = json_decode(curl_exec($ch), 1); - - // Check if we have an access token - // If we do, send a request to Microsoft Graph API to get user info - if (isset($access_token_response['access_token'])) { - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$access_token_response['access_token'], - 'Content-type: application/json')); - curl_setopt($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/"); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); - curl_setopt($ch, CURLOPT_TIMEOUT, 30); - #curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP - - $msgraph_response = json_decode(curl_exec($ch), 1); - - if (isset($msgraph_response['error'])) { - // Something went wrong verifying the token/using the Graph API - quit - error_log("ITFlow: MS Graph API error during client portal Entra login: " . json_encode($msgraph_response['error'])); - $_SESSION['login_message'] = 'Something went wrong with logging you in: could not read your profile from Microsoft. Please try again.'; - redirect("../login.php"); - - } elseif (isset($msgraph_response['id'])) { - - $upn = mysqli_real_escape_string($mysqli, $msgraph_response["userPrincipalName"]); - - $sql = mysqli_query($mysqli, "SELECT contact_client_id, contact_id, user_auth_method, user_email, user_id, user_password FROM users - LEFT JOIN contacts ON user_id = contact_user_id - LEFT JOIN clients ON contact_client_id = client_id - WHERE user_email = '$upn' - AND user_archived_at IS NULL - AND contact_archived_at IS NULL - AND client_archived_at IS NULL - AND user_type = 2 - AND user_status = 1 - LIMIT 1" - ); - $row = mysqli_fetch_assoc($sql); - $client_id = intval($row['contact_client_id']); - $user_id = intval($row['user_id']); - $session_user_id = $user_id; // to pass the user_id to logAction function - $contact_id = intval($row['contact_id']); - $user_email = escapeSql($row['user_email']); - $user_auth_method = escapeSql($row['user_auth_method']); - - if ($user_auth_method == 'azure') { - - // New session ID for the authenticated session (CWE-384) - session_regenerate_id(true); - - $_SESSION['client_logged_in'] = true; - $_SESSION['client_id'] = $client_id; - $_SESSION['user_id'] = $user_id; - $_SESSION['user_type'] = 2; - $_SESSION['contact_id'] = $contact_id; - $_SESSION['csrf_token'] = randomString(32); - $_SESSION['login_method'] = "azure"; - // A later password change ends this session (userSessionStamp()) - $_SESSION['user_session_stamp'] = userSessionStamp($row['user_password'] ?? ''); - unset($_SESSION['portal_view_as']); // an agent's View as contact in this browser ends here - - // Logging - logAudit("Client Login", "Success", "Client contact $upn successfully logged in via Entra", $client_id, $user_id); - - redirect("index.php"); - - } else { - - // Logged with why, against the account when there is one (functions/sign_in.php) - $entra_why = $row ? ['user_id' => $user_id, 'client_id' => $client_id, 'reason' => 'the account signs in with a password, not Microsoft 365'] : signInFailureReason($msgraph_response['userPrincipalName']); - signInLogFailure('Client Login', 'Failed', "Failed client portal sign in via Entra as $upn - " . escapeSql($entra_why['reason']), $entra_why['user_id'], $entra_why['client_id']); - - $_SESSION['login_message'] = 'Something went wrong with logging you in: Your account is not configured for Entra SSO. Please ensure you are setup in ITFlow as a contact and have Entra SSO configured.'; - - redirect("../login.php"); - } - - } - - redirect('index.php'); - - } else { - - error_log("ITFlow: no access_token returned during client portal Entra login"); - $_SESSION['login_message'] = 'Something went wrong with logging you in: Microsoft did not return an access token. Please try again.'; - redirect("../login.php"); - - } - -} - -// If the user is just sat on the page, send them back to log in to try again -redirect("../login.php"); +require __DIR__ . '/../login_provider.php'; diff --git a/client/profile.php b/client/profile.php index 8c38f4355..d4c58130c 100644 --- a/client/profile.php +++ b/client/profile.php @@ -232,7 +232,7 @@ $csrf = escapeHtml($_SESSION['csrf_token']);
-

You sign in with your Microsoft 365 account - Microsoft looks after your password and its own sign-in checks.

+

You sign in with your account - it looks after your password and its own sign-in checks.

diff --git a/db.sql b/db.sql index 681de55b7..1970646eb 100644 --- a/db.sql +++ b/db.sql @@ -1915,6 +1915,37 @@ CREATE TABLE `history` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `identity_providers` +-- + +DROP TABLE IF EXISTS `identity_providers`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `identity_providers` ( + `identity_provider_id` int(11) NOT NULL AUTO_INCREMENT, + `identity_provider_kind` varchar(20) NOT NULL, + `identity_provider_name` varchar(100) NOT NULL, + `identity_provider_enabled` tinyint(1) NOT NULL DEFAULT 1, + `identity_provider_agents` tinyint(1) NOT NULL DEFAULT 0, + `identity_provider_contacts` tinyint(1) NOT NULL DEFAULT 0, + `identity_provider_domains` varchar(1000) NOT NULL DEFAULT '', + `identity_provider_required` tinyint(1) NOT NULL DEFAULT 0, + `identity_provider_client_id` varchar(255) NOT NULL DEFAULT '', + `identity_provider_client_secret` varchar(1000) NOT NULL DEFAULT '', + `identity_provider_tenant` varchar(100) NOT NULL DEFAULT '', + `identity_provider_url` varchar(500) NOT NULL DEFAULT '', + `identity_provider_port` int(11) NOT NULL DEFAULT 0, + `identity_provider_security` varchar(10) NOT NULL DEFAULT '', + `identity_provider_username` varchar(10) NOT NULL DEFAULT '', + `identity_provider_redirect_path` varchar(100) NOT NULL DEFAULT '/login_provider.php', + `identity_provider_used_at` datetime DEFAULT NULL, + `identity_provider_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `identity_provider_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + PRIMARY KEY (`identity_provider_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `income_import_rules` -- @@ -4116,8 +4147,6 @@ CREATE TABLE `settings` ( `config_statement_monthly` tinyint(1) NOT NULL DEFAULT 0, `config_statement_day` tinyint(2) NOT NULL DEFAULT 1, `config_billing_email_attach_pdf` tinyint(1) NOT NULL DEFAULT 1, - `config_azure_client_id` varchar(200) DEFAULT NULL, - `config_azure_client_secret` varchar(200) DEFAULT NULL, `config_module_enable_itdoc` tinyint(1) NOT NULL DEFAULT 1, `config_module_enable_accounting` tinyint(1) NOT NULL DEFAULT 1, `config_client_portal_enable` tinyint(1) NOT NULL DEFAULT 1, diff --git a/functions.php b/functions.php index 0dc2bcbb1..33bab3cef 100644 --- a/functions.php +++ b/functions.php @@ -48,6 +48,7 @@ require_once __DIR__ . '/functions/log_forward.php'; require_once __DIR__ . '/functions/audit_log.php'; require_once __DIR__ . '/functions/sign_in.php'; require_once __DIR__ . '/functions/passkey.php'; +require_once __DIR__ . '/functions/identity_provider.php'; require_once __DIR__ . '/functions/app_log.php'; require_once __DIR__ . '/functions/app.php'; require_once __DIR__ . '/functions/email.php'; diff --git a/functions/contact.php b/functions/contact.php index 80c97a6f2..024c3a410 100644 --- a/functions/contact.php +++ b/functions/contact.php @@ -73,13 +73,13 @@ function contactAvatarData($client_id, $contact_id, $name, $photo) { /** * How they log in to the client portal, or '' with no access: 'Password' - * or 'Microsoft'. + * or 'Identity provider' (only through one, functions/identity_provider.php). */ function contactPortalAccess($contact_user_id, $auth_method) { if (!intval($contact_user_id) || (string) $auth_method === '') { return ''; } - return $auth_method === 'azure' ? 'Microsoft' : 'Password'; + return $auth_method === 'azure' ? 'Identity provider' : 'Password'; } /** diff --git a/functions/credential.php b/functions/credential.php index 336a2354c..388802880 100644 --- a/functions/credential.php +++ b/functions/credential.php @@ -268,7 +268,7 @@ function credentialFormSet($post, $client_id, &$error = '') { $password = encryptCredentialEntry(trim((string) ($post['password'] ?? ''))); $otp = credentialOtpEncrypt($otp); if ($username === false || $password === false || $otp === false) { - $error = vaultLocked() ? 'Your credentials are locked - you signed in with a passkey that can\'t open them. Unlock them with your password (the lock beside a username), then save again.' + $error = vaultLocked() ? 'Your credentials are locked - ' . vaultLockedReason() . '. Unlock them with your password (the lock beside a username), then save again.' : 'Your vault session has expired, so the login could not be encrypted - sign out and back in, then try again.'; return null; } diff --git a/functions/demo.php b/functions/demo.php index 6305568a0..64e89e0dc 100644 --- a/functions/demo.php +++ b/functions/demo.php @@ -62,7 +62,7 @@ const DEMO_MODE_LOCKS = [ ], [ 'message' => "Sign-in security and identity providers can't be changed in the demo.", - 'keys' => ['edit_security_settings', 'edit_identity_provider'], + 'keys' => ['edit_security_settings', 'save_identity_provider', 'turn_identity_provider_on', 'turn_identity_provider_off', 'delete_identity_provider'], ], [ 'message' => "API keys can't be made or changed in the demo.", diff --git a/functions/identity_provider.php b/functions/identity_provider.php new file mode 100644 index 000000000..39b817ab0 --- /dev/null +++ b/functions/identity_provider.php @@ -0,0 +1,679 @@ + Identity Providers, admin/identity_providers.php). + * + * Who a provider signs in goes by email domain: each provider is for agents, client contacts or + * both, and lists the email domains it signs in - any account on them can use it. Microsoft 365 + * and Google can leave the list empty and sign in any account, as both vouch for the address + * (Microsoft's sign-in name is on a domain its directory has proved it owns, and Google says when + * an address is verified); Nextcloud and IMAP need it, as a Nextcloud's users can set their own email + * address, and a mail server only says whether a password is right. + * A provider made required turns off password sign-in for the accounts on its domains - an + * agent with an administrator role keeps theirs, to get back in when it is down. No one is made + * an account by signing in: an agent, or a contact with portal access, has to be there already. + * + * Microsoft 365, Google and Nextcloud sign in by OpenID Connect's code flow (login_provider.php): + * the button on the sign-in page goes to the provider, which sends them back with a code; ITFlow + * swaps it for a token, server to server with the app's secret and PKCE, and asks the provider + * who they are - Microsoft Graph's /me, or the userinfo endpoint. Their own two-step sign-in + * stands in for ITFlow's. IMAP is a password, so it is checked in the password step of + * login.php instead of ITFlow's - against the mail server - and the two-step code is still asked. + * An administrator's ITFlow password still works too, for when the mail server is down. + * + * An agent signed in through a provider has their credentials locked until they type their ITFlow + * password once (vaultUnlock()), as the vault key is opened with it and the provider never sees it. + */ + +/** Whether the database has identity providers yet (4.2.5). */ +function identityProvidersReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '4.2.5', '>='); + } + return $ready; +} + +/** The kinds of identity provider, and what each needs. */ +function identityProviderKinds() { + return [ + 'microsoft' => [ + 'name' => 'Microsoft 365', + 'button' => 'Sign in with Microsoft', + 'icon' => 'fab fa-microsoft', + 'oauth' => true, + 'domains_optional' => true, + 'about' => 'Work accounts in Microsoft 365 - an app registered in Microsoft Entra', + 'fields' => ['client_id', 'client_secret', 'tenant'], + ], + 'google' => [ + 'name' => 'Google Workspace', + 'button' => 'Sign in with Google', + 'icon' => 'fab fa-google', + 'oauth' => true, + 'domains_optional' => true, + 'about' => 'Google Workspace accounts - an OAuth client in Google Cloud', + 'fields' => ['client_id', 'client_secret'], + ], + 'nextcloud' => [ + 'name' => 'Nextcloud', + 'button' => 'Sign in with Nextcloud', + 'icon' => 'fas fa-cloud', + 'oauth' => true, + 'domains_optional' => false, + 'about' => 'Nextcloud accounts - its OIDC Identity Provider app', + 'fields' => ['url', 'client_id', 'client_secret'], + ], + 'imap' => [ + 'name' => 'IMAP', + 'button' => '', + 'icon' => 'fas fa-envelope', + 'oauth' => false, + 'domains_optional' => false, + 'about' => 'A mail server - the password typed on the sign-in page is checked with it', + 'fields' => ['url', 'port', 'security', 'username'], + ], + ]; +} + +/** The kind of an identity_providers row, or null when this ITFlow doesn't know it. */ +function identityProviderKind(array $row) { + return identityProviderKinds()[(string) ($row['identity_provider_kind'] ?? '')] ?? null; +} + +/** An identity provider's row, or null. */ +function identityProviderRow($identity_provider_id) { + global $mysqli; + if (!identityProvidersReady()) { + return null; + } + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM identity_providers WHERE identity_provider_id = " . intval($identity_provider_id))) ?: null; +} + +/** Every provider that is on, of a known kind - once a request. */ +function identityProvidersOn() { + global $mysqli; + static $rows = null; + if ($rows === null) { + $rows = []; + if (identityProvidersReady()) { + $sql = mysqli_query($mysqli, "SELECT * FROM identity_providers WHERE identity_provider_enabled = 1 ORDER BY identity_provider_name ASC, identity_provider_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + if (identityProviderKind($row)) { + $rows[] = $row; + } + } + } + } + return $rows; +} + +/** A list of email domains as they are kept - lowercase, one each, no @ - from what was typed. */ +function identityProviderDomainList($text) { + $domains = []; + foreach (preg_split('/[\s,;]+/', strtolower((string) $text)) as $domain) { + $domain = trim($domain, " \t.@"); + if ($domain !== '') { + $domains[$domain] = true; + } + } + return array_keys($domains); +} + +/** Whether a domain is one - letters, digits and hyphens, in parts. */ +function identityProviderDomainValid($domain) { + return (bool) preg_match('/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/', $domain); +} + +/** The domains a provider signs in - [] for any, where its kind allows that. */ +function identityProviderDomains(array $row) { + return identityProviderDomainList($row['identity_provider_domains'] ?? ''); +} + +/** The part of an email address after the @, lowercase. */ +function identityProviderEmailDomain($email) { + $at = strrpos((string) $email, '@'); + return $at === false ? '' : strtolower(substr((string) $email, $at + 1)); +} + +/** Whether a provider signs in this email address - its domain is on the list, or the list is empty where that means any. */ +function identityProviderCovers(array $row, $email) { + $kind = identityProviderKind($row); + if (!$kind) { + return false; + } + $domains = identityProviderDomains($row); + if (!$domains) { + return !empty($kind['domains_optional']); + } + return in_array(identityProviderEmailDomain($email), $domains, true); +} + +/** Whether a provider is for this kind of account - 1 an agent, 2 a client contact (only while the portal is on). */ +function identityProviderFor(array $row, $user_type) { + global $config_client_portal_enable; + if (intval($user_type) === 1) { + return intval($row['identity_provider_agents']) === 1; + } + return intval($row['identity_provider_contacts']) === 1 && intval($config_client_portal_enable ?? 0) === 1; +} + +/** The IMAP provider that checks this account's password, or null. */ +function identityProviderImapFor($email, $user_type) { + foreach (identityProvidersOn() as $row) { + if ($row['identity_provider_kind'] === 'imap' && identityProviderFor($row, $user_type) && identityProviderCovers($row, $email)) { + return $row; + } + } + return null; +} + +/** + * The provider this account has to sign in with, when one on its domains is required - null when + * its password still works. An agent whose role is an administrator's keeps their password, to + * get back in when the provider is down or set up wrong. + */ +function identityProviderRequiredFor($email, $user_type, $role_id = 0) { + foreach (identityProvidersOn() as $row) { + $kind = identityProviderKind($row); + if (!$kind['oauth'] || intval($row['identity_provider_required']) !== 1 || !identityProviderDomains($row) + || !identityProviderFor($row, $user_type) || !identityProviderCovers($row, $email)) { + continue; + } + if (intval($user_type) === 1 && identityProviderAdminRole($role_id)) { + continue; + } + return $row; + } + return null; +} + +/** Whether an agent's role is an administrator's - who keeps their ITFlow password, to get back in when a provider is down. */ +function identityProviderAdminRole($role_id) { + global $mysqli; + if (intval($role_id) <= 0) { + return false; + } + $admin = mysqli_fetch_row(mysqli_query($mysqli, "SELECT role_is_admin FROM user_roles WHERE role_id = " . intval($role_id))); + return intval($admin[0] ?? 0) === 1; +} + +/** The providers with a button on the sign-in page - Microsoft 365, Google and Nextcloud that sign anyone in here. */ +function identityProviderButtons() { + return array_values(array_filter(identityProvidersOn(), function ($row) { + return identityProviderKind($row)['oauth'] && (identityProviderFor($row, 1) || identityProviderFor($row, 2)); + })); +} + +/** Where a provider sends people back to - the address registered with it. */ +function identityProviderRedirectUri(array $row) { + global $config_base_url; + $path = (string) ($row['identity_provider_redirect_path'] ?? '') ?: '/login_provider.php'; + return 'https://' . preg_replace('#^https?://#', '', rtrim((string) $config_base_url, '/')) . $path; +} + +/** + * The names of the providers on for client contacts, Microsoft 365, Google or Nextcloud - for what + * the portal tells them. With an email address, only the ones that sign that address in. + */ +function identityProviderNamesForContacts($email = null) { + $names = []; + foreach (identityProvidersOn() as $row) { + if (identityProviderKind($row)['oauth'] && identityProviderFor($row, 2) && ($email === null || identityProviderCovers($row, $email))) { + $names[] = (string) $row['identity_provider_name']; + } + } + return array_values(array_unique($names)); +} + +/** What contacts sign in with besides a password, for what they and agents are told - "Microsoft 365 or Google Workspace", or "an identity provider". */ +function identityProviderContactsWording($email = null) { + $names = identityProviderNamesForContacts($email); + return $names ? implode(' or ', $names) : 'an identity provider'; +} + +/** A Nextcloud's address, as typed - https, no trailing slash. */ +function identityProviderNextcloudUrl(array $row) { + return rtrim(trim((string) ($row['identity_provider_url'] ?? '')), '/'); +} + +/** An HTTP request to a provider - [status, decoded JSON or null, raw body]. Never sent anywhere but its own endpoints. */ +function identityProviderHttp($method, $url, $fields = null, $headers = []) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_TIMEOUT, 20); + curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + if ($method === 'POST') { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query((array) $fields)); + } + curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge(['Accept: application/json'], $headers)); + $body = curl_exec($ch); + $status = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE)); + curl_close($ch); + $json = is_string($body) ? json_decode($body, true) : null; + return [$status, is_array($json) ? $json : null, is_string($body) ? $body : '']; +} + +/** + * Where a provider's sign-in happens - authorize, token and userinfo endpoints, and how the token + * endpoint takes the secret. Microsoft and Google are fixed; a Nextcloud says in its OpenID + * configuration. [endpoints, error]. + */ +function identityProviderEndpoints(array $row) { + $kind = (string) $row['identity_provider_kind']; + if ($kind === 'microsoft') { + $tenant = trim((string) ($row['identity_provider_tenant'] ?? '')) ?: 'organizations'; + $tenant = preg_match('/^[a-z0-9.-]{1,100}$/i', $tenant) ? $tenant : 'organizations'; + return [[ + 'authorize' => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/authorize", + 'token' => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token", + 'userinfo' => 'https://graph.microsoft.com/v1.0/me', + 'scope' => 'openid profile email User.Read', + 'auth' => 'post', + ], '']; + } + if ($kind === 'google') { + return [[ + 'authorize' => 'https://accounts.google.com/o/oauth2/v2/auth', + 'token' => 'https://oauth2.googleapis.com/token', + 'userinfo' => 'https://openidconnect.googleapis.com/v1/userinfo', + 'scope' => 'openid email profile', + 'auth' => 'post', + ], '']; + } + if ($kind === 'nextcloud') { + $base = identityProviderNextcloudUrl($row); + if (!preg_match('#^https://[^/\s]+#i', $base)) { + return [null, 'its address is not an https:// one']; + } + $config = null; + foreach (["$base/index.php/.well-known/openid-configuration", "$base/.well-known/openid-configuration"] as $url) { + [$status, $json] = identityProviderHttp('GET', $url); + if ($status === 200 && $json && !empty($json['authorization_endpoint']) && !empty($json['token_endpoint']) && !empty($json['userinfo_endpoint'])) { + $config = $json; + break; + } + } + if (!$config) { + return [null, "it didn't give its OpenID configuration - is its OIDC Identity Provider app installed?"]; + } + foreach (['authorization_endpoint', 'token_endpoint', 'userinfo_endpoint'] as $key) { + if (stripos((string) $config[$key], 'https://') !== 0) { + return [null, 'its OpenID configuration gives an address that is not https://']; + } + } + $methods = (array) ($config['token_endpoint_auth_methods_supported'] ?? ['client_secret_post']); + return [[ + 'authorize' => (string) $config['authorization_endpoint'], + 'token' => (string) $config['token_endpoint'], + 'userinfo' => (string) $config['userinfo_endpoint'], + 'scope' => 'openid profile email', + 'auth' => in_array('client_secret_post', $methods, true) ? 'post' : 'basic', + ], '']; + } + return [null, 'it is not a kind that signs in with a button']; +} + +/** PKCE - a random verifier, and its S256 challenge. */ +function identityProviderPkce() { + $verifier = rtrim(strtr(base64_encode(random_bytes(48)), '+/', '-_'), '='); + $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='); + return [$verifier, $challenge]; +} + +/** The address that starts signing in with a provider. */ +function identityProviderAuthorizeUrl(array $row, array $endpoints, $state, $challenge) { + $params = [ + 'client_id' => (string) $row['identity_provider_client_id'], + 'redirect_uri' => identityProviderRedirectUri($row), + 'response_type' => 'code', + // Back as a top-level GET - the session cookie isn't sent on a cross-site POST + 'response_mode' => 'query', + 'scope' => $endpoints['scope'], + 'state' => $state, + 'code_challenge' => $challenge, + 'code_challenge_method' => 'S256', + 'prompt' => 'select_account', + ]; + $domains = identityProviderDomains($row); + if ($row['identity_provider_kind'] === 'google' && count($domains) === 1) { + $params['hd'] = $domains[0]; // straight to their Workspace's accounts + } + if ($row['identity_provider_kind'] === 'nextcloud') { + unset($params['prompt'], $params['response_mode']); + } + return $endpoints['authorize'] . (str_contains($endpoints['authorize'], '?') ? '&' : '?') . http_build_query($params); +} + +/** + * Who signed in, from the code the provider sent back - ['email' => ..., 'name' => ...], or + * ['error' => why, for the log]. The code is swapped for a token server to server, with the app's + * secret and the PKCE verifier, then the provider is asked who it is for. + */ +function identityProviderIdentity(array $row, array $endpoints, $code, $verifier) { + $fields = [ + 'grant_type' => 'authorization_code', + 'code' => (string) $code, + 'redirect_uri' => identityProviderRedirectUri($row), + 'client_id' => (string) $row['identity_provider_client_id'], + 'code_verifier' => (string) $verifier, + ]; + $headers = []; + if ($endpoints['auth'] === 'basic') { + $headers[] = 'Authorization: Basic ' . base64_encode(rawurlencode((string) $row['identity_provider_client_id']) . ':' . rawurlencode((string) $row['identity_provider_client_secret'])); + } else { + $fields['client_secret'] = (string) $row['identity_provider_client_secret']; + } + [$status, $token] = identityProviderHttp('POST', $endpoints['token'], $fields, $headers); + if (empty($token['access_token']) || !is_string($token['access_token'])) { + $why = is_array($token) && !empty($token['error']) ? (string) $token['error'] . (!empty($token['error_description']) ? ' - ' . mb_substr((string) $token['error_description'], 0, 200) : '') : "HTTP $status"; + return ['error' => "it gave no token for the code ($why)"]; + } + + [$status, $who] = identityProviderHttp('GET', $endpoints['userinfo'], null, ['Authorization: Bearer ' . $token['access_token']]); + if (!$who || $status !== 200) { + return ['error' => "it didn't say who signed in (HTTP $status)"]; + } + + $kind = (string) $row['identity_provider_kind']; + if ($kind === 'microsoft') { + // The sign-in name, on a domain the directory has proved it owns - not mail, which anyone in a directory can be given + $email = (string) ($who['userPrincipalName'] ?? ''); + $name = (string) ($who['displayName'] ?? ''); + if (str_contains($email, '#EXT#')) { + return ['error' => 'it is a guest account in another organization']; + } + } else { + $email = (string) ($who['email'] ?? ''); + $name = (string) ($who['name'] ?? ''); + if ($kind === 'google' && ($who['email_verified'] ?? false) !== true && ($who['email_verified'] ?? '') !== 'true') { + return ['error' => "Google hasn't verified the address $email"]; + } + // A Nextcloud that says the address isn't verified is taken at its word + if ($kind === 'nextcloud' && array_key_exists('email_verified', $who) && $who['email_verified'] !== true && $who['email_verified'] !== 'true') { + return ['error' => "Nextcloud hasn't verified the address $email"]; + } + } + $email = strtolower(trim($email)); + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + return ['error' => 'it gave no email address']; + } + return ['email' => $email, 'name' => $name]; +} + +/** + * The accounts a provider can sign in for this address - ['agent' => user id or 0, 'client' => + * user id or 0]: an agent that is active, and a contact with portal access at a current client. + */ +function identityProviderAccounts(array $row, $email) { + global $mysqli; + $accounts = ['agent' => 0, 'client' => 0]; + if (!identityProviderCovers($row, $email)) { + return $accounts; + } + $email_sql = escapeSql($email); + if (identityProviderFor($row, 1)) { + $agent = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$email_sql' AND user_type = 1 AND user_status = 1 + AND user_archived_at IS NULL" . serviceAccountsOutSql('users.user_service_account') . " ORDER BY user_id LIMIT 1")); + $accounts['agent'] = intval($agent[0] ?? 0); + } + if (identityProviderFor($row, 2)) { + $contact = mysqli_fetch_row(mysqli_query($mysqli, "SELECT users.user_id FROM users + JOIN contacts ON contact_user_id = users.user_id AND contact_archived_at IS NULL + JOIN clients ON client_id = contact_client_id AND client_archived_at IS NULL + WHERE user_email = '$email_sql' AND user_type = 2 AND user_status = 1 AND user_archived_at IS NULL AND user_auth_method IN ('local', 'azure') + ORDER BY users.user_id LIMIT 1")); + $accounts['client'] = intval($contact[0] ?? 0); + } + return $accounts; +} + +/** The name an IMAP server is given for this address - the address, or the part before the @. */ +function identityProviderImapUsername(array $row, $email) { + return ($row['identity_provider_username'] ?? '') === 'local' ? substr((string) $email, 0, strrpos((string) $email, '@')) : (string) $email; +} + +/** + * Whether the mail server takes this password for the address - [ok, why not, for the log]. A + * server that can't be reached is said apart from a wrong password, and goes in the app log. + */ +function identityProviderImapCheck(array $row, $email, #[\SensitiveParameter] $password) { + static $checked = []; + if ((string) $password === '' || strpos((string) $email, '@') === false) { + return [false, 'no password was typed']; + } + $key = intval($row['identity_provider_id']) . '|' . strtolower((string) $email) . '|' . hash('sha256', (string) $password); + if (isset($checked[$key])) { + return $checked[$key]; + } + require_once dirname(__DIR__) . '/libs/vendor/autoload.php'; + $security = (string) ($row['identity_provider_security'] ?? 'ssl'); + $mailbox = new \DirectoryTree\ImapEngine\Mailbox([ + 'host' => (string) $row['identity_provider_url'], + 'port' => intval($row['identity_provider_port']) ?: ($security === 'ssl' ? 993 : 143), + 'encryption' => $security === 'none' ? '' : $security, + 'validate_cert' => true, + 'timeout' => 10, + 'username' => identityProviderImapUsername($row, $email), + 'password' => (string) $password, + ]); + try { + $mailbox->connect(); + try { + $mailbox->disconnect(); + } catch (\Throwable $e) { + // Signed in is all that was asked + } + return $checked[$key] = [true, '']; + } catch (\DirectoryTree\ImapEngine\Exceptions\ImapCommandException $e) { + return $checked[$key] = [false, 'the mail server said the password is wrong']; + } catch (\Throwable $e) { + logApp('Identity Provider', 'warning', 'Could not reach the mail server for ' . $row['identity_provider_name'] . ' (' . $row['identity_provider_url'] . '): ' . mb_substr($e->getMessage(), 0, 300)); + return $checked[$key] = [false, "the mail server couldn't be reached"]; + } +} + +/** A provider was just used to sign in - for its list. */ +function identityProviderUsed($identity_provider_id) { + global $mysqli; + if (identityProvidersReady()) { + mysqli_query($mysqli, "UPDATE identity_providers SET identity_provider_used_at = NOW(), identity_provider_updated_at = identity_provider_updated_at WHERE identity_provider_id = " . intval($identity_provider_id)); + } +} + +/* + * ---------- Admin > Identity Providers ---------- + * + * Add and Edit are one window (admin/modals/identity_provider/identity_provider_edit.php), saved by + * save_identity_provider (admin/post/identity_provider.php). Which kind it is stays once added. + * The secret is never put back into the page - left empty, it stays as saved. + */ + +/** What is typed in an identity provider's window, checked - [the row to save, errors by field]. */ +function identityProviderCheck(array $in, ?array $before): array +{ + $errors = []; + $kind_key = $before ? (string) $before['identity_provider_kind'] : (string) ($in['kind'] ?? ''); + $kind = identityProviderKinds()[$kind_key] ?? null; + if (!$kind) { + return [[], ['kind' => 'Pick the kind of identity provider.']]; + } + $text = function ($key, $max = 255) use ($in) { + return trim((string) ($in[$key] ?? '')); + }; + $fields = $kind['fields']; + + $name = $text('name'); + if ($name === '') { + $errors['name'] = 'Give it a name - its button on the sign-in page says Sign in with it.'; + } elseif (mb_strlen($name) > 100) { + $errors['name'] = 'Its name is 100 characters at most.'; + } + + $agents = intval($in['agents'] ?? 0) === 1 ? 1 : 0; + $contacts = intval($in['contacts'] ?? 0) === 1 ? 1 : 0; + if (!$agents && !$contacts) { + $errors['agents'] = 'Pick who it signs in - agents, client contacts or both.'; + } + + $domains = identityProviderDomainList($text('domains')); + $bad = array_values(array_filter($domains, function ($domain) { + return !identityProviderDomainValid($domain); + })); + if ($bad) { + $errors['domains'] = $bad[0] . ' isn\'t an email domain - type them as example.com, with a comma between.'; + } elseif (!$domains && !$kind['domains_optional']) { + $errors['domains'] = 'List the email domains it signs in - ' . ($kind_key === 'imap' ? 'the ones whose mailboxes are all on this server.' : 'the ones whose people are all on your Nextcloud.'); + } elseif (strlen(implode(', ', $domains)) > 1000) { + $errors['domains'] = 'That many email domains don\'t fit - split them over two providers.'; + } + + $required = $kind['oauth'] && intval($in['required'] ?? 0) === 1 ? 1 : 0; + if ($required && !$domains) { + $errors['required'] = 'List the email domains it is required for.'; + } + + $client_id = $secret = $tenant = $url = ''; + $port = 0; + $security = $username = ''; + if (in_array('client_id', $fields, true)) { + $client_id = $text('client_id'); + if ($client_id === '') { + $errors['client_id'] = $kind_key === 'microsoft' ? 'The Application (client) ID, from the app\'s Overview.' : 'Its client ID.'; + } elseif ($kind_key === 'microsoft' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $client_id)) { + $errors['client_id'] = 'The Application (client) ID - 32 letters and numbers in five groups, as e721e3b6-01d6-50e8-7f22-c84d951a52e7.'; + } elseif ($kind_key === 'google' && !preg_match('/^[A-Za-z0-9-]+\.apps\.googleusercontent\.com$/', $client_id)) { + $errors['client_id'] = 'The Client ID of the OAuth client - it ends in .apps.googleusercontent.com.'; + } elseif (strlen($client_id) > 255 || preg_match('/\s/', $client_id)) { + $errors['client_id'] = 'That isn\'t a client ID - copy it again, with no spaces.'; + } + $secret = (string) ($in['client_secret'] ?? ''); + $secret = trim($secret) !== '' ? trim($secret) : (string) ($before['identity_provider_client_secret'] ?? ''); + if ($secret === '') { + $errors['client_secret'] = $kind_key === 'microsoft' ? 'And a secret for it, from Certificates & secrets - its Value, not its ID.' : 'And its client secret.'; + } elseif (strlen($secret) > 1000) { + $errors['client_secret'] = 'That is too long for a client secret - copy it again.'; + } + } + if (in_array('tenant', $fields, true)) { + $tenant = strtolower($text('tenant')); + if (in_array($tenant, ['common', 'consumers'], true)) { + $errors['tenant'] = 'Personal Microsoft accounts can\'t sign in here - leave it empty for any organization\'s work accounts.'; + } elseif ($tenant === 'organizations') { + $tenant = ''; + } elseif ($tenant !== '' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $tenant) && !identityProviderDomainValid($tenant)) { + $errors['tenant'] = 'The Directory (tenant) ID, or one of its domains as contoso.onmicrosoft.com - or leave it empty.'; + } + } + if ($kind_key === 'nextcloud') { + $url = rtrim($text('url'), '/'); + $parts = parse_url($url); + if ($url === '' || !$parts || strtolower($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) || isset($parts['query']) || isset($parts['fragment']) || isset($parts['user']) || strlen($url) > 500) { + $errors['url'] = 'Your Nextcloud\'s address, starting with https:// - as https://cloud.example.com.'; + } + } + if ($kind_key === 'imap') { + $url = strtolower($text('url')); + if ($url === '' || (!identityProviderDomainValid($url) && !filter_var($url, FILTER_VALIDATE_IP))) { + $errors['url'] = 'The mail server\'s name, as mail.example.com.'; + } + $security = (string) ($in['security'] ?? 'ssl'); + if (!in_array($security, ['ssl', 'starttls', 'none'], true)) { + $security = 'ssl'; + } + $port_text = $text('port'); + $port = $port_text === '' ? ($security === 'ssl' ? 993 : 143) : intval($port_text); + if ($port < 1 || $port > 65535 || ($port_text !== '' && !ctype_digit($port_text))) { + $errors['port'] = 'A port is a number from 1 to 65535 - 993 for SSL/TLS, 143 for STARTTLS.'; + } + $username = ($in['username'] ?? 'email') === 'local' ? 'local' : 'email'; + } + + $after = [ + 'identity_provider_kind' => $kind_key, + 'identity_provider_name' => mb_substr($name, 0, 100), + 'identity_provider_enabled' => intval($in['enabled'] ?? 0) === 1 ? 1 : 0, + 'identity_provider_agents' => $agents, + 'identity_provider_contacts' => $contacts, + 'identity_provider_domains' => implode(', ', $domains), + 'identity_provider_required' => $required, + 'identity_provider_client_id' => $client_id, + 'identity_provider_client_secret' => $secret, + 'identity_provider_tenant' => $tenant, + 'identity_provider_url' => $url, + 'identity_provider_port' => $port, + 'identity_provider_security' => $security, + 'identity_provider_username' => $username, + ]; + + // A Nextcloud has to say where its OpenID Connect is - asked when its address is new + if (!$errors && $kind_key === 'nextcloud' && (!$before || identityProviderNextcloudUrl($before) !== $url)) { + [, $why] = identityProviderEndpoints($after); + if ($why) { + $errors['url'] = 'ITFlow asked your Nextcloud, but ' . $why; + } + } + + return [$after, $errors]; +} + +/** Save an identity provider's row - a new one when $identity_provider_id is 0. Its id. */ +function identityProviderWrite(array $after, int $identity_provider_id = 0): int +{ + global $mysqli; + $set = implode(', ', array_map(function ($column, $value) { + return "`$column` = '" . escapeSql((string) $value) . "'"; + }, array_keys($after), $after)); + if ($identity_provider_id) { + mysqli_query($mysqli, "UPDATE identity_providers SET $set WHERE identity_provider_id = $identity_provider_id"); + return $identity_provider_id; + } + mysqli_query($mysqli, "INSERT INTO identity_providers SET $set"); + return intval(mysqli_insert_id($mysqli)); +} + +/** What changed on an identity provider, for the audit log - its secret is never written down. */ +function identityProviderChangeLines(array $before, array $after): array +{ + $labels = [ + 'identity_provider_name' => 'name', 'identity_provider_enabled' => 'on', 'identity_provider_agents' => 'agents', + 'identity_provider_contacts' => 'client contacts', 'identity_provider_domains' => 'email domains', 'identity_provider_required' => 'required', + 'identity_provider_client_id' => 'client ID', 'identity_provider_client_secret' => 'secret', 'identity_provider_tenant' => 'tenant', + 'identity_provider_url' => 'address', 'identity_provider_port' => 'port', 'identity_provider_security' => 'security', 'identity_provider_username' => 'username', + ]; + $switches = [ + 'identity_provider_enabled' => ['turned it on', 'turned it off'], + 'identity_provider_agents' => ['signs in agents', 'no longer signs in agents'], + 'identity_provider_contacts' => ['signs in client contacts', 'no longer signs in client contacts'], + 'identity_provider_required' => ['made it required', 'made it not required'], + ]; + $lines = []; + foreach ($labels as $column => $label) { + $old = (string) ($before[$column] ?? ''); + $new = (string) ($after[$column] ?? ''); + if ($old === $new) { + continue; + } + if (isset($switches[$column])) { + $lines[] = $switches[$column][$new === '1' ? 0 : 1]; + } elseif ($column === 'identity_provider_client_secret') { + $lines[] = 'a new secret'; + } else { + $lines[] = "$label: " . ($old === '' ? '(none)' : $old) . ' to ' . ($new === '' ? '(none)' : $new); + } + } + return $lines; +} diff --git a/functions/passkey.php b/functions/passkey.php index 9158a6731..9aedb2dbe 100644 --- a/functions/passkey.php +++ b/functions/passkey.php @@ -435,10 +435,22 @@ function vaultUnlock($user_id, #[\SensitiveParameter] $password) { return [true, '']; } +/* + * Why the vault is locked, as it is said to the agent - how they signed in without the password + * that opens it (login.php): a passkey that can't, an identity provider, or their mail password. + */ +function vaultLockedReason() { + $via = trim((string) ($_SESSION['signed_in_via'] ?? '')); + return [ + 'provider' => 'you signed in with ' . ($via !== '' ? $via : 'an identity provider') . ', which can\'t open them', + 'imap' => 'you signed in with your mail password, which can\'t open them', + ][$_SESSION['signed_in_with'] ?? ''] ?? 'you signed in with a passkey that can\'t open them'; +} + /** The note in a credential window while the vault is locked - with the button that unlocks it (js/credentials.js). */ function vaultLockedAlertHtml() { return '
' - . 'Your credentials are locked - you signed in with a passkey that can\'t open them.' + . 'Your credentials are locked - ' . escapeHtml(vaultLockedReason()) . '.' . '
'; } diff --git a/functions/portal.php b/functions/portal.php index 53d4c71d6..0f3947ab9 100644 --- a/functions/portal.php +++ b/functions/portal.php @@ -100,7 +100,8 @@ function portalContactLastSignIn($user_id) { /** * Whether a contact can sign in to the portal, and how: key none (never set - * up), off (turned off), local (a password) or azure (Microsoft) - with a + * up), off (turned off), local (a password) or azure (only through an identity + * provider, functions/identity_provider.php) - with a * label, icon and class for portalStateBadge() in client/functions.php. From * a row with user_id, user_auth_method, user_status and user_archived_at * (LEFT JOIN users). @@ -113,7 +114,7 @@ function portalContactAccess(array $row) { if (!in_array($method, ['local', 'azure'], true) || intval($row['user_status'] ?? 0) !== 1 || !empty($row['user_archived_at'])) { return ['key' => 'off', 'label' => 'Portal access off', 'icon' => 'fa-ban', 'class' => 'itflow-portal-state-closed']; } - return ['key' => $method, 'label' => $method === 'azure' ? 'Signs in with Microsoft' : 'Signs in with a password', 'icon' => 'fa-check', 'class' => 'itflow-portal-state-resolved']; + return ['key' => $method, 'label' => $method === 'azure' ? 'Signs in with ' . identityProviderContactsWording() : 'Signs in with a password', 'icon' => 'fa-check', 'class' => 'itflow-portal-state-resolved']; } /* @@ -202,7 +203,7 @@ function portalUserAccessOn($user_id, $method) { if (!empty($row['client_archived_at']) || !empty($row['contact_archived_at'])) { return ($row['client_archived_at'] ? 'Their client' : 'The contact') . ' is archived - restore it first'; } - if (!isset(portalSignInMethods()[$method])) { + if (!isset(portalSignInMethods($row['user_email'])[$method])) { $method = 'local'; } $error = ''; @@ -213,12 +214,15 @@ function portalUserAccessOn($user_id, $method) { return ''; } -/** The ways a portal user can sign in here - a password, and Microsoft when it is set up. method => label. */ -function portalSignInMethods() { - global $config_azure_client_id; +/* + * The ways a portal user can sign in here - a password (and any identity provider on their email's + * domain), and only through a provider, when one is on for contacts - for this email address, when + * it is given. method => label. + */ +function portalSignInMethods($email = null) { $methods = ['local' => 'With a password']; - if (!empty($config_azure_client_id)) { - $methods['azure'] = 'With their Microsoft 365 account'; + if (identityProviderNamesForContacts($email)) { + $methods['azure'] = 'Only with ' . identityProviderContactsWording($email) . ' - no password'; } return $methods; } @@ -228,7 +232,7 @@ function portalSignInMethods() { * * A portal user's authenticator secret is users.user_token, as an agent's is, * and a browser ticked to be remembered is a remember_tokens row - so sign-in - * (login.php) treats both alike. Microsoft 365 accounts are left to Microsoft. + * (login.php) treats both alike. A sign-in through an identity provider is left to it. */ /** How many browsers this user ticked to be remembered, still in date. */ @@ -331,7 +335,7 @@ function portalMailInvite($user_id, $by = '') { } else { portalPasswordLinkClear($user_id); $button = ['label' => 'Sign in', 'url' => "https://$config_base_url/login.php"]; - $how = 'Sign in with your Microsoft 365 account - choose Login with Microsoft on the sign-in page.'; + $how = 'Sign in with your ' . identityProviderContactsWording($row['user_email']) . ' account - choose its button on the sign-in page.'; $after = 'Questions? Reply to this email.'; } return (bool) emailQueue([['email' => $row['user_email'], 'name' => $row['contact_name'], diff --git a/functions/portal_invite.php b/functions/portal_invite.php index 4ab36f398..c2aa1b940 100644 --- a/functions/portal_invite.php +++ b/functions/portal_invite.php @@ -7,7 +7,7 @@ * it from the client's Contacts (the Invites tab), a primary contact from * Contacts in the portal. Nobody is a contact until they accept: the link * opens client/join.php, where they put in their name, title, phone and a - * password (or choose their Microsoft 365 account), and they are made a + * password (or choose an identity provider's account), and they are made a * contact with portal access - or, when the client already has a contact * with that address, that contact is given access. * @@ -432,7 +432,7 @@ function portalInviteAccept(array $invite, array $in, &$error = '') { $title = trim(mb_substr((string) ($in['title'] ?? ''), 0, 200)); $phone = substr(preg_replace('/[^0-9]/', '', (string) ($in['phone'] ?? '')), 0, 200); $method = (string) ($in['method'] ?? 'local'); - if (!isset(portalSignInMethods()[$method])) { + if (!isset(portalSignInMethods($email)[$method])) { $method = 'local'; } $password = (string) ($in['password'] ?? ''); @@ -501,7 +501,7 @@ function portalInviteAccept(array $invite, array $in, &$error = '') { WHERE contact_id = $contact_id AND contact_client_id = $client_id"); } - // Their portal account - a password, or their Microsoft 365 account + // Their portal account - a password, or only an identity provider (functions/identity_provider.php) $hash = escapeSql(password_hash($method === 'local' ? $password : randomString(32), PASSWORD_DEFAULT)); $user_id = intval($who['user_id'] ?? 0); if ($user_id) { @@ -804,7 +804,7 @@ function portalMailSignupExists($user_id) { 'kind' => 'Client portal', 'tone' => 'primary', 'preview' => 'Sign in with the account you have', 'title' => "You already have a $company_name client portal account", 'intro' => ["Someone - probably you - tried to sign up for the $company_name client portal with this address, but it has an account already.", - $local ? 'Forgot your password? Choose a new one with the button below.' : 'Sign in with your Microsoft 365 account - choose Login with Microsoft on the sign-in page.'], + $local ? 'Forgot your password? Choose a new one with the button below.' : 'Sign in with your ' . identityProviderContactsWording($row['user_email']) . ' account - choose its button on the sign-in page.'], 'summary' => ['Account' => (string) $row['user_email']], 'button' => $local ? ['label' => 'Set a new password', 'url' => portalPasswordLink($user_id, PORTAL_RESET_LINK_MINUTES)] : ['label' => 'Sign in', 'url' => "https://$config_base_url/login.php"], 'after' => [$local ? 'The link works once, for the next ' . PORTAL_RESET_LINK_MINUTES . ' minutes. If you did not ask, ignore this email - your account stays as it is.' : 'If you did not ask, ignore this email - your account stays as it is.'], diff --git a/functions/settings.php b/functions/settings.php index 26855eacf..19ee63f4d 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -65,8 +65,6 @@ function settingsPages() { 'about' => 'The sign-in page, two-step sign-in, passkeys, failed sign-ins, API keys and shared links.'], 'client_portal' => ['group' => 'access', 'title' => 'Client Portal', 'icon' => 'fa-user-shield', 'url' => 'settings_client_portal.php', 'module' => 'portal', 'about' => 'How your clients\' contacts sign in to the portal, and the announcements they see there.'], - 'identity' => ['group' => 'access', 'title' => 'Single Sign-on', 'icon' => 'fa-fingerprint', 'url' => 'identity_providers.php', 'module' => 'portal', - 'about' => 'Contacts signing in to the client portal with their Microsoft 365 account.'], 'module' => ['group' => 'system', 'title' => 'Modules', 'icon' => 'fa-cube', 'url' => 'settings_module.php', 'about' => 'The parts of ITFlow in use - IT documentation, ticketing, invoicing, the calendar, the Knowledge Base and the client portal, and the parts that come with them - and white-labelling.'], 'logs' => ['group' => 'system', 'title' => 'Log Settings', 'icon' => 'fa-scroll', 'url' => 'settings_logs.php', 'under' => 'logs', @@ -421,10 +419,6 @@ function settingsFields() { 'config_client_portal_require_mfa' => ['page' => 'client_portal', 'section' => 'Signing in', 'label' => 'Require two-step sign-in', 'words' => 'portal mfa 2fa two factor contacts'] + $on_off, 'config_client_portal_signup' => ['page' => 'client_portal', 'section' => 'Signing up', 'label' => 'Let people sign up', 'words' => 'portal sign up register registration self create account domain'] + $on_off, - // Single sign-on - 'config_azure_client_id' => ['page' => 'identity', 'section' => 'Microsoft Entra', 'label' => 'Application (client) ID', 'words' => 'sso entra azure microsoft 365 single sign-on portal'], - 'config_azure_client_secret' => ['page' => 'identity', 'section' => 'Microsoft Entra', 'label' => 'Client secret', 'kind' => 'secret', 'words' => 'sso entra azure secret'], - // Modules 'config_module_enable_itdoc' => ['page' => 'module', 'section' => 'Modules', 'label' => 'IT documentation', 'words' => 'module itdoc documentation assets credentials'] + $on_off, 'config_module_enable_ticketing' => ['page' => 'module', 'section' => 'Modules', 'label' => 'Ticketing', 'words' => 'module tickets support'] + $on_off, diff --git a/functions/sign_in.php b/functions/sign_in.php index 0adc9b8a6..e46061d93 100644 --- a/functions/sign_in.php +++ b/functions/sign_in.php @@ -7,7 +7,7 @@ * (signInNewIpIds()); and telling the admins about a run of failures from one * address or against one account (signInWatch()) - how many is Admin > * Settings > Security (config_login_alert_failures, 0 for never). login.php, - * client/login_microsoft.php and api/v1/validate_api_key.php write it; Admin > + * login_provider.php and api/v1/validate_api_key.php write it; Admin > * Sign-ins, the audit log and Your account > Activity read it. */ diff --git a/includes/footer.php b/includes/footer.php index 211dcf511..f13d99416 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -96,7 +96,7 @@ try {