diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f6b3c2e90..9dd887c945 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,46 @@ This file documents all notable changes made to ITFlow. +## [26.11.3] + +### Upgrading + +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's one database change (3.5.4 to 3.5.5) in the same pass. Nothing else is required. Everyone is signed out once after the update, agents and client portal contacts alike - see Security. The new Payment Provider Fees job in Maintenance > Cron is set up by itself. + +### Security + +- Setup: the Restore a backup option on the setup page is open to anyone until the first user is created, as it has to be on a new install. A backup built for the purpose could use it to make the web server run code it carried into the uploads folder. This needed Apache with .htaccess overrides switched on - installs on nginx, and Apache servers that ignore .htaccess files, were not affected. A restore no longer brings in the files that decide how the web server treats a folder, it never writes into the folder backups are kept in, and ITFlow's own protections on the uploads folder are put back after every restore. Every release from 26.08 to 26.11.2 is affected. If an install of yours sat at the setup page where others could reach it, look through its uploads folder for .htaccess, .user.ini or .php files that ITFlow didn't put there. +- Passwords: changing a password now signs that account out everywhere else. Before, a browser that was already signed in stayed signed in after the password changed - including after the incident-response reset in Admin > Users, which is meant to lock out someone who has got in. It covers changing your own password, an admin setting someone's, the incident-response reset, and on the client portal a contact changing theirs, a password reset link, and an agent setting a contact's portal password. On the portal, the browser making the change stays signed in. An agent's View as contact ends too when their password changes. +- MFA: an agent whose account requires multi-factor authentication but who hadn't set it up yet could use ITFlow without ever setting it up, by going straight to other pages after signing in. Until it is set up, every page now goes back to setting it up, or signing out - including for an agent who is already signed in when an admin requires MFA, or resets it, for them. View as contact isn't offered to them either. +- Client portal: the two-step sign-in set up that Admin > Client Portal can require could be got past in two ways - by adding a page name to the end of the address, or by sending another action along with setting it up. A contact who still had to set it up could open their tickets and invoices, and raise or resolve tickets. Neither works now. +- MFA: agents are now emailed when multi-factor authentication is turned on for their account, as client portal contacts already were. Setting it up takes only the password, so this is how someone finds out an authenticator they didn't add was put on their account. + +### New Features & Updates + +- API: products can be updated through the API (`products/update`). Only the fields you send are changed, and the key's user needs edit access to Sales, the same as editing a product in ITFlow. +- API keys: agents are notified in ITFlow a week before an API key expires, so an integration doesn't stop without warning. +- Payment Providers: Stripe's fee on a card payment is now recorded as an expense about 15 minutes after the payment, instead of the next morning. A new Payment Provider Fees job in Maintenance > Cron does it, and you can run it more often there. Record fees now still works any time. + +### Bug Fixes + +- Transactions: the list, its Transfers pill, Reconcile and the transactions export load faster again. On a test with eight years of books, the Transfers pill went from about a third of a second in 26.11.2 to under a fifth. +- Expenses: billable expenses waiting to go on an invoice slowed down every page, because the side menu counts them and each one was checked against every expense. With a few hundred waiting, that was about a third of a second on every page. The invoice page, Add Expenses and an expense's quick look had the same delay. All of them are quick again. +- Transactions: on All accounts, Money in and Money out counted every transfer between your own accounts twice - once out of one account and once into the other - so both were far too high. A Stripe payout to the bank, a check deposit or paying off a card all added to both. They now leave transfers between your accounts out, as the dashboard and Income already did. The Transfers pill still lists them, and one account on its own still counts them as money in and out of that account. The Difference was always right. + +### Developer Updates + +- `backupRestoreArchive()` no longer extracts the inner `uploads.zip` wholesale. It builds an allow-list of entries and extracts with `extractTo($dir, $entries)`, leaving out any entry whose basename is `.htaccess`, `.user.ini` or `.htpasswd` and any entry that resolves inside `backupStorageDir()`, which the restore preserves while it empties the rest of `uploads/`. Unsafe paths (`..`, absolute) still fail the restore as before. `scripts/restore_cli.php` gets the same, as it calls the same function. +- `backupHardenStorageDir()` writes its `.htaccess` every time instead of only when there is none, so a guard carried in by an archive can't survive. `backupAssertUploadsGuards()` also rewrites the deny-all guards in `uploads/backups`, `canned_responses`, `expenses` and `tmp`, so a restored `uploads/` has the same guards as a fresh install. Both use the new `BACKUP_UPLOADS_DENY_GUARD` constant. +- `accountLedgerSql()` reads its lines first and joins each to its account with `STRAIGHT_JOIN`. Left to choose, the optimizer started from the accounts and found their lines through an index it built on the lines' temporary table (`derived_with_keys`), which was two to three times slower. +- Database 3.5.5 indexes `expenses.expense_refund_of_id`. `expenseUnbilledCount()` (the side menu, on every agent page), `expenseUnbilled()`, `expenseOnInvoice()` and `expenseRow()` sum each expense's refunds in a correlated subquery, which scanned every expense for each one. Like 3.5.4, it is safe to run again, and `db.sql` has the key. +- `api/v1/products/update.php` takes `product_id` and any of the `product_*` fields mapped in `api/v1/products/product_model.php`, and saves through `productSave()`. At least one field is required and each must be a scalar. `product_track_stock` accepts `1`, `true`, `yes`, `on` or `tracked`, and sending `product_type` without `product_track_stock` turns stock tracking off, as the product form does. `enforce_api_rbac.php` gates it on `module_sales` at write level, and it logs a Product Edit and an API Success. +- `cron/nightly_tasks.php` sends an `appNotify()` "API Key Expiring" notification for each key whose `api_key_expire` is seven days away, once, on that day. +- Sessions carry `$_SESSION['user_session_stamp']`, `userSessionStamp()` in `functions/user.php`: a SHA-256 digest of the user's `user_password` hash, never the hash itself. It is set at the three places a session is made - `login.php` (agent and client portal) and `client/login_microsoft.php` - and checked with `hash_equals()` on every request in `includes/load_user_session.php` and `client/includes/check_login.php`, next to the existing status and archived checks. Any write to `users.user_password`, from any code path, ends every session made before it, with no new column and no migration. A session without the stamp is signed out, which is the one-time sign-out on updating. +- `userSetPassword()` calls `userSessionRestamp()`, which gives the current session a new id (`session_regenerate_id(true)`) and the new stamp when the password changed is its own user's - so only the other sessions end. The client portal's own password change does the same. `portalViewAsAccess()` returns `agent_session_stamp`, checked against the agent's session while viewing as a contact. +- New `requestIsMfaSetup($allowed)` in `functions/auth.php` decides what a session that still has to set up MFA may request: the script really running (`realpath($_SERVER['SCRIPT_FILENAME'])` under the app root, never `PHP_SELF`, which a path added after the script name changes), and every GET and POST key inside one of the shapes allowed for that script. `includes/load_user_session.php` applies it when `user_config_force_mfa` is 1 and `user_token` is empty, allowing `agent/user/mfa_enforcement.php` with no parameters and `agent/user/post.php` with only `csrf_token`, `enable_mfa` and `verify_code`, or `?logout` - everything else redirects to the set up page, modals and AJAX included. The client portal gate in `client/includes/check_login.php` now uses it too (`profile.php?mfa`, and `post.php` with `portal_mfa_enable` or `?logout`), replacing its `basename($_SERVER['PHP_SELF'])` test; the separate gate in `client/post.php`, which let any request through that carried `portal_mfa_enable` or `logout` alongside other actions, is gone. `portalViewAsAccess()` refuses an agent still owing MFA set up. The `enable_mfa` handler sends `userNotifyChange()`. +- `accountLedgerShows($all_accounts)`: across every account, the `in` and `out` cuts leave out `txn_kind` `transfer_in` and `transfer_out`. `agent/transactions.php` does the same for its Money in and Money out totals, except on the Transfers pill, and notes it in the table footer when the listed lines include transfers the totals leave out. The transactions export, which takes its cuts from the same function, follows. +- Stripe fees are recorded by a new job, `cron/payment_provider_fees.php` (`payment_provider_fees` in `includes/cron_jobs.php`, every 15 minutes, interval-safe), instead of `cron/nightly_tasks.php`. The dispatcher seeds its row the first time it sees it. `paymentProviderRecordFees()` now holds `GET_LOCK('itflow_payment_provider_fees', 0)` around the work, which moved to `paymentProviderRecordFeesLocked()`, and returns `'busy' => true` when another run has it - "has no fee yet" is read before the fee is written, so two runs at once would each record it. Record fees now says when a run is in progress. + ## [26.11.2] ### Upgrading diff --git a/README.md b/README.md index 136bc7dc05..70a43f7b3d 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,7 @@ We're incredibly grateful to the organizations and individuals who [sponsor](htt | [Mountaineer IT](https://mountaineerit.com) | Dec 2025 | | [DataBit Solutions](https://databitsolutions.com) | Dec 2025 | | [City of Rathdrum](https://rathdrumpolice.gov) | Dec 2025 | -| [Algolibre](https://algolibre.io) | Aug 2026 | +| [AlgoLibre Inc.](https://algolibre.io) | Aug 2026 | | [Pentagon Networks](https://pentagon.net) | Aug 2026 | | [Hanobox e.K.](https://hanobox.de) | Oct 2026 | | [Innovarro Group Limited](https://innovarro.com) | Oct 2026 | diff --git a/admin/database_updates/3.5.5.php b/admin/database_updates/3.5.5.php new file mode 100644 index 0000000000..aee4cbf981 --- /dev/null +++ b/admin/database_updates/3.5.5.php @@ -0,0 +1,26 @@ + data-provider-fees-switch> -
Each night, its fee on each card payment is recorded as an expense from the account above.
+
Its fee on each card payment is recorded as an expense from the account above, a few minutes after Stripe settles the payment.
diff --git a/admin/payment_providers.php b/admin/payment_providers.php index 226dd7b18f..f93a31bc95 100644 --- a/admin/payment_providers.php +++ b/admin/payment_providers.php @@ -8,7 +8,7 @@ * and how many are still to record), its saved cards and the autopay on * them, and its card payments in the last 30 days. Check connection asks * the provider whose account the key is; Record fees now does what the - * nightly run does. Add and Edit are one window + * Payment Provider Fees job does every few minutes. Add and Edit are one window * (modals/payment_provider/payment_provider_edit.php); the rest are * admin/post/payment_provider.php. */ @@ -155,7 +155,7 @@ to record + title=" Cron should have had them' : 'Recorded a few minutes after Stripe settles them' ?>"> to record Not recorded @@ -187,7 +187,7 @@ Check connection - + Record fees now diff --git a/admin/post/payment_provider.php b/admin/post/payment_provider.php index f2eea40cf2..9be19fc13c 100644 --- a/admin/post/payment_provider.php +++ b/admin/post/payment_provider.php @@ -165,7 +165,7 @@ } -// Record fees now - what the nightly run does, for the payments whose fee is still to record +// Record fees now - what the Payment Provider Fees job does every few minutes, for the payments whose fee is still to record if (isset($_GET['record_payment_provider_fees'])) { validateCSRFToken(); @@ -182,6 +182,10 @@ } $done = paymentProviderRecordFees($row); + if ($done['busy']) { + flashAlert('' . escapeHtml($name) . '\'s fees are being recorded right now by the scheduled run - look again in a minute', 'info'); + redirect(); + } $said = []; if ($done['recorded']) { $said[] = 'Recorded its fee on ' . $done['recorded'] . ' payment' . ($done['recorded'] === 1 ? '' : 's') . ' - ' . paymentProviderMoneyText($done['amount']); diff --git a/agent/transactions.php b/agent/transactions.php index 90f970c9ae..3e340832a7 100644 --- a/agent/transactions.php +++ b/agent/transactions.php @@ -90,8 +90,11 @@ foreach ($shows as $key => $s) { $count_sql[] = $key === '' ? 'COUNT(*)' : "COALESCE(SUM({$s['where']}), 0)"; } -$count_sql[] = "COALESCE(SUM(CASE WHEN 1 $show_query AND ledger.txn_amount > 0 THEN ledger.txn_amount END), 0)"; -$count_sql[] = "COALESCE(SUM(CASE WHEN 1 $show_query AND ledger.txn_amount < 0 THEN -ledger.txn_amount END), 0)"; +// Across every account a transfer is money moved between them, so Money in and Money out +// leave it out (accountLedgerShows()) - except on Transfers, where it is what is listed +$not_transfer = $all && $show !== 'transfers' ? "AND ledger.txn_kind NOT IN ('transfer_in', 'transfer_out')" : ''; +$count_sql[] = "COALESCE(SUM(CASE WHEN 1 $show_query $not_transfer AND ledger.txn_amount > 0 THEN ledger.txn_amount END), 0)"; +$count_sql[] = "COALESCE(SUM(CASE WHEN 1 $show_query $not_transfer AND ledger.txn_amount < 0 THEN -ledger.txn_amount END), 0)"; if ($transfer_cards) { $count_sql[] = "COALESCE(SUM(CASE WHEN 1 $show_query THEN -ledger.txn_amount END), 0)"; $count_sql[] = "COALESCE(SUM(CASE WHEN 1 $show_query AND ledger.other_account_type = 3 THEN -ledger.txn_amount END), 0)"; @@ -186,14 +189,14 @@
Money in
-
+
Money out
-
+
@@ -428,7 +431,7 @@ - line count($rows) ? ' - the totals are for all of them, not just this page' : '' ?> + line count($rows) ? ' - the totals are for all of them, not just this page' : '' ?> diff --git a/agent/user/post/profile.php b/agent/user/post/profile.php index 7c455068cc..3990089d8c 100644 --- a/agent/user/post/profile.php +++ b/agent/user/post/profile.php @@ -157,6 +157,11 @@ function userCurrentPasswordOk($password) { logAudit("User Account", "Edit", "$session_name enabled MFA on their account"); + // Setting MFA up needs only the password, so whoever holds it can do it - the email + // is how the real owner finds out an authenticator was added (the portal sends one too) + $me = userRow($session_user_id); + userNotifyChange($me['user_name'], $me['user_email'], 'multi-factor authentication was turned on'); + flashAlert("Multi-factor authentication is on - you will be asked for a code when you sign in"); // Clear the mfa_token from the session to avoid re-use. diff --git a/api/v1/products/product_model.php b/api/v1/products/product_model.php new file mode 100644 index 0000000000..32344ccb2b --- /dev/null +++ b/api/v1/products/product_model.php @@ -0,0 +1,50 @@ + 'name', + 'product_type' => 'type', + 'product_category_id' => 'category', + 'product_price' => 'price', + 'product_cost' => 'cost', + 'product_tax_id' => 'tax', + 'product_frequency' => 'frequency', + 'product_seat_source' => 'seat_source', + 'product_code' => 'code', + 'product_vendor_id' => 'vendor', + 'product_vendor_part' => 'vendor_part', + 'product_reorder_level' => 'reorder_level', + 'product_reorder_qty' => 'reorder_qty', + 'product_location' => 'location', + 'product_asset_type' => 'asset_type', + 'product_make' => 'make', + 'product_model' => 'model', + 'product_warranty_months' => 'warranty_months', + 'product_description' => 'description', + 'product_notes' => 'notes', + 'product_track_stock' => 'track_stock', +]; + +$product_input = []; +$product_model_error = ''; + +foreach ($field_names as $api_field => $key) { + if (!array_key_exists($api_field, $_POST)) { + continue; + } + if (!is_scalar($_POST[$api_field]) && $_POST[$api_field] !== null) { + $product_model_error = "The $api_field field must be a scalar value."; + break; + } + + $value = (string) ($_POST[$api_field] ?? ''); + if ($key === 'track_stock') { + $value = in_array(strtolower(trim($value)), ['1', 'true', 'yes', 'on', 'tracked'], true); + } + $product_input[$key] = $value; +} + +// The product form posts the stock switch with the type, including when it is off. +if (array_key_exists('type', $product_input) && !array_key_exists('track_stock', $product_input)) { + $product_input['track_stock'] = false; +} diff --git a/api/v1/products/update.php b/api/v1/products/update.php new file mode 100644 index 0000000000..63f8413053 --- /dev/null +++ b/api/v1/products/update.php @@ -0,0 +1,60 @@ + Client Portal) and -// not set up yet: Your account until it is, and nothing else +// not set up yet: Your account until it is, and nothing else. The one gate for the +// pages and for client/post.php, judged on the script really running and every key +// in the request (requestIsMfaSetup()). $portal_mfa_setup_needed = !$portal_view_as && intval($config_client_portal_require_mfa ?? 0) === 1 && $session_auth_method === 'local' && !$session_mfa_on; -if ($portal_mfa_setup_needed && !in_array(basename($_SERVER['PHP_SELF']), ['profile.php', 'post.php'], true)) { +if ($portal_mfa_setup_needed && !requestIsMfaSetup([ + 'client/profile.php' => [[['mfa'], []]], + 'client/post.php' => [[[], ['csrf_token', 'portal_mfa_enable', 'verify_code']], [['logout'], []]], +])) { redirect("/client/profile.php?mfa=setup"); } diff --git a/client/login_microsoft.php b/client/login_microsoft.php index 6728cd09cf..0f5865f58e 100644 --- a/client/login_microsoft.php +++ b/client/login_microsoft.php @@ -126,7 +126,7 @@ $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 FROM users + $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' @@ -156,6 +156,8 @@ $_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 diff --git a/client/post.php b/client/post.php index d3c37616db..7966a3aec6 100644 --- a/client/post.php +++ b/client/post.php @@ -25,10 +25,8 @@ redirect(); } -// Two-step sign-in required and not set up yet: setting it up, or signing out -if ($portal_mfa_setup_needed && !isset($_POST['portal_mfa_enable']) && !isset($_GET['logout'])) { - redirect('profile.php?mfa=setup'); -} +// Two-step sign-in required and not set up yet: client/includes/check_login.php has +// already turned away everything but setting it up, or signing out if (isset($_POST['add_ticket'])) { @@ -562,9 +560,11 @@ redirect('profile.php#security'); } - $hash = escapeSql(password_hash($new_password, PASSWORD_DEFAULT)); - mysqli_query($mysqli, "UPDATE users SET user_password = '$hash' WHERE user_id = $session_user_id AND user_type = 2"); + $new_hash = password_hash($new_password, PASSWORD_DEFAULT); + mysqli_query($mysqli, "UPDATE users SET user_password = '" . escapeSql($new_hash) . "' WHERE user_id = $session_user_id AND user_type = 2"); portalPasswordLinkClear($session_user_id); + // This browser stays signed in, with a new session id - every other session of theirs ends + userSessionRestamp($session_user_id, $new_hash); logAudit("Contact", "Edit", "Client contact $session_contact_name changed their password in the client portal", $session_client_id, $session_contact_id); portalMailAccountChange(stripslashes($session_contact_email), stripslashes($session_contact_name), 'password'); diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index 5c0c5f5912..c5607c3f6b 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -323,6 +323,17 @@ function cronInvoiceHistoryToday(int $invoice_id, string $description_prefix): b // Logging // logAudit("Cron", "Task", "Cron created notifications for certificates expiring"); +// API KEYS EXPIRING +$sql = mysqli_query($mysqli, "SELECT api_key_id, api_key_name, api_key_expire FROM api_keys + WHERE api_key_expire = CURDATE() + INTERVAL 7 DAY"); + +while ($row = mysqli_fetch_assoc($sql)) { + $api_key_id = intval($row['api_key_id']); + $api_key_name = escapeSql($row['api_key_name']); + $api_key_expire = escapeSql($row['api_key_expire']); + appNotify("API Key Expiring", "API key $api_key_name will expire in 7 days on $api_key_expire", "/admin/api_keys.php", 0, $api_key_id); +} + // Asset Warranties Expiring $warranty_alert_array = [1,7,45]; @@ -747,19 +758,7 @@ function cronInvoiceHistoryToday(int $invoice_id, string $description_prefix): b } } -/* - * Stripe fee reconciliation - the fee on each recent card payment that has - * none recorded yet, as Stripe charged it, once it has settled - * (paymentProviderRecordFees(), functions/payment_provider.php - the same - * thing Record fees now on Admin > Payment Providers does). One card payment - * over several invoices has one fee, taken once. A payment can complete - * before Stripe settles it; that one is picked up on a later run. - */ -$stripe_provider = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT payment_provider_name, payment_provider_private_key, payment_provider_account, - payment_provider_expense_vendor, payment_provider_expense_category FROM payment_providers WHERE payment_provider_name = 'Stripe' LIMIT 1")); -if ($stripe_provider) { - paymentProviderRecordFees($stripe_provider); -} +// Stripe fees are recorded by their own job every few minutes - cron/payment_provider_fees.php /* * Recurring expenses - each running one due today, or missed by up to diff --git a/cron/payment_provider_fees.php b/cron/payment_provider_fees.php new file mode 100644 index 0000000000..adac6dd742 --- /dev/null +++ b/cron/payment_provider_fees.php @@ -0,0 +1,54 @@ + Payment Providers does. A card payment usually settles within + * seconds, so running this every few minutes has its fee on the books shortly after the + * payment instead of the next morning. One that hasn't settled yet waits for a later run. + * + * Safe on an interval: a payment whose fee is recorded is never looked at again, and the + * recorder holds a lock so this and Record fees now can't both record the same fee. With + * nothing waiting, a run is one query and no call to Stripe. + */ + +// Set working directory to the directory this cron script lives at. +chdir(dirname(__FILE__)); + +// Ensure we're running from command line +if (php_sapi_name() !== 'cli') { + die("This script must be run from the command line.\n"); +} + +// Prevent overlapping runs of this script +$cron_lock_script = __FILE__; +require_once "includes/cron_lock.php"; + +require_once "../config.php"; + +// Set Timezone +require_once "../includes/inc_set_timezone.php"; +require_once "../functions.php"; + +$payment_provider_fees_settings = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_enable_cron FROM settings WHERE company_id = 1")); + +if (intval($payment_provider_fees_settings['config_enable_cron'] ?? 0) == 0) { + cronJobStop("Cron: is not enabled\n"); +} + +$payment_provider_fees_provider = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT payment_provider_name, payment_provider_private_key, payment_provider_account, + payment_provider_expense_vendor, payment_provider_expense_category FROM payment_providers WHERE payment_provider_name = 'Stripe' LIMIT 1")); + +if (!$payment_provider_fees_provider) { + cronJobStop("No Stripe payment provider\n"); +} + +$payment_provider_fees_done = paymentProviderRecordFees($payment_provider_fees_provider); + +if ($payment_provider_fees_done['busy']) { + echo "Fees are being recorded already - left to that run\n"; +} else { + echo $payment_provider_fees_done['recorded'] . " fee(s) recorded, " . $payment_provider_fees_done['waiting'] . " waiting for Stripe to settle, " . $payment_provider_fees_done['failed'] . " failed\n"; +} diff --git a/db.sql b/db.sql index 739104d565..6258fb94b4 100644 --- a/db.sql +++ b/db.sql @@ -1746,7 +1746,8 @@ CREATE TABLE `expenses` ( KEY `expense_invoice_id` (`expense_invoice_id`), KEY `expense_import_key` (`expense_import_key`), KEY `expense_reimbursement_id` (`expense_reimbursement_id`), - KEY `expense_reconciliation_id` (`expense_reconciliation_id`) + KEY `expense_reconciliation_id` (`expense_reconciliation_id`), + KEY `expense_refund_of_id` (`expense_refund_of_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/functions/accounts.php b/functions/accounts.php index c3c8e3f7aa..8fd10f2bf5 100644 --- a/functions/accounts.php +++ b/functions/accounts.php @@ -363,6 +363,11 @@ function accountLedgerKinds() { * it is only worked out with $with_balance - where it is shown. Without it, * txn_balance is NULL: counts, totals and lists across every account don't * need it. + * + * The lines are read first and each looks its account up (STRAIGHT_JOIN). + * Left to choose, the optimizer starts from the few accounts and finds their + * lines through an index it builds on the lines' temporary table, which is + * two to three times slower. */ function accountLedgerSql($account_id = 0, $with_balance = true) { $account_id = intval($account_id); @@ -416,7 +421,7 @@ function accountLedgerSql($account_id = 0, $with_balance = true) { " . ($with_balance ? "accounts.opening_balance + SUM(ledger_lines.txn_amount) OVER (PARTITION BY ledger_lines.txn_account_id ORDER BY ledger_lines.txn_date ASC, ledger_lines.txn_created_at ASC, ledger_lines.txn_order ASC, ledger_lines.txn_id ASC)" : "NULL") . " AS txn_balance FROM ($rows) AS ledger_lines - JOIN accounts ON accounts.account_id = ledger_lines.txn_account_id + STRAIGHT_JOIN accounts ON accounts.account_id = ledger_lines.txn_account_id LEFT JOIN accounts AS other_account ON ledger_lines.txn_kind IN ('transfer_in', 'transfer_out') AND other_account.account_id = ledger_lines.txn_other_account_id LEFT JOIN account_reconciliations AS cleared ON cleared.reconciliation_id = ledger_lines.txn_reconciliation_id AND cleared.reconciliation_finished_at IS NOT NULL LEFT JOIN categories ON category_id = ledger_lines.txn_category_id @@ -466,14 +471,17 @@ function accountLedgerWhat(array $row) { } /** - * The ways the ledger can be cut - ?show=. Across every account a transfer - * shows once on Transfers, from the account it left. + * The ways the ledger can be cut - ?show=. Across every account a transfer is + * money moved between them, not money in or out: Money in and Money out leave + * both of its lines out, and Transfers shows it once, from the account it left. + * On one account a transfer is money in or out of that account like any other. */ function accountLedgerShows($all_accounts = false) { + $not_transfer = $all_accounts ? " AND ledger.txn_kind NOT IN ('transfer_in', 'transfer_out')" : ''; return [ '' => ['label' => 'All', 'where' => ''], - 'in' => ['label' => 'Money in', 'icon' => 'fa-arrow-down', 'where' => 'ledger.txn_amount > 0'], - 'out' => ['label' => 'Money out', 'icon' => 'fa-arrow-up', 'where' => 'ledger.txn_amount < 0'], + 'in' => ['label' => 'Money in', 'icon' => 'fa-arrow-down', 'where' => 'ledger.txn_amount > 0' . $not_transfer], + 'out' => ['label' => 'Money out', 'icon' => 'fa-arrow-up', 'where' => 'ledger.txn_amount < 0' . $not_transfer], 'transfers' => ['label' => 'Transfers', 'icon' => 'fa-exchange-alt', 'where' => $all_accounts ? "ledger.txn_kind = 'transfer_out'" : "ledger.txn_kind IN ('transfer_in', 'transfer_out')"], 'uncleared' => ['label' => 'Uncleared', 'icon' => 'fa-hourglass-half', 'where' => 'ledger.txn_cleared_id IS NULL'], ]; diff --git a/functions/auth.php b/functions/auth.php index 5b6670ec7b..9c6308cb6c 100644 --- a/functions/auth.php +++ b/functions/auth.php @@ -5,6 +5,31 @@ // When provided a module name (e.g. module_support), returns the associated permission level (false=none, 1=read, 2=write, 3=full). // The role's levels are read once a request - a page asks dozens of times. +/* + * Is this request one of the few a session may make while it still has to set up MFA? + * + * $allowed maps a script, from the app root, to the request shapes it may take - each a + * [GET keys, POST keys] pair, and every key in the request has to be one of them. The + * script is the file actually running, never PHP_SELF: a path tacked onto the end of a + * URL (client/tickets.php/profile.php) changes PHP_SELF but not what runs. And the keys + * are checked whole, because post handlers run one after another - a request that carries + * the set-up action and another one alongside it must not get the other one through. + */ +function requestIsMfaSetup(array $allowed) { + $root = realpath(dirname(__DIR__)); + $script = realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')); + if ($root === false || $script === false || strpos($script, $root . DIRECTORY_SEPARATOR) !== 0) { + return false; + } + $script = str_replace(DIRECTORY_SEPARATOR, '/', substr($script, strlen($root) + 1)); + foreach ($allowed[$script] ?? [] as [$get_keys, $post_keys]) { + if (!array_diff(array_keys($_GET), $get_keys) && !array_diff(array_keys($_POST), $post_keys)) { + return true; + } + } + return false; +} + function lookupUserPermission($module) { global $mysqli, $session_is_admin, $session_user_role; static $levels = []; diff --git a/functions/backup.php b/functions/backup.php index baa6d2df94..cec6e96345 100644 --- a/functions/backup.php +++ b/functions/backup.php @@ -18,6 +18,10 @@ DEFINE("BACKUP_TYPE_DATABASE", "database"); DEFINE("BACKUP_TYPE_MASTER_KEY", "master_key"); +// The deny-all guard written into upload directories that must never be served. Kept in one +// place so the restore path and the storage-dir hardening agree on what "our guard" is. +DEFINE("BACKUP_UPLOADS_DENY_GUARD", "Require all denied\nOptions -ExecCGI -Indexes\nphp_flag engine off\n"); + /** * The backup types that can be produced without a logged-in user. * master_key needs the session master key, so cron can never make one. @@ -187,6 +191,12 @@ function backupStorageDir(): string * "turn PHP off" rule used elsewhere in uploads/, because nothing in here should ever * be reachable over HTTP by any means. nginx installs get no protection from this file * at all, which is why the archives are encrypted and their names carry a random token. + * + * The guard is written unconditionally. A restore preserves this directory (it holds the + * other archives) while it clears and repopulates the rest of uploads/ from an archive that, + * at the setup restore, is supplied by an unauthenticated requester - so "write it only if + * absent" would let a backup keep whatever .htaccess it carried in. Re-assert means + * re-assert: ours is what ends up on disk. */ function backupHardenStorageDir(string $dir): void { @@ -194,10 +204,7 @@ function backupHardenStorageDir(string $dir): void return; } - $htaccess = $dir . "/.htaccess"; - if (!file_exists($htaccess)) { - @file_put_contents($htaccess, "Require all denied\nOptions -ExecCGI -Indexes\nphp_flag engine off\n"); - } + @file_put_contents($dir . "/.htaccess", BACKUP_UPLOADS_DENY_GUARD); $index = $dir . "/index.php"; if (!file_exists($index)) { @@ -229,6 +236,19 @@ function backupAssertUploadsGuards(): void if (!file_exists($index)) { @file_put_contents($index, ""); } + + // The subdirectories that ship their own deny-all guard. A restore has just cleared and + // repopulated uploads/ from the archive, and the extraction step drops any .htaccess the + // archive carried, so these are rewritten from our own copy rather than trusted from the + // backup - the same reasoning as the root guard above. The root rule covers them by + // inheritance on Apache; keeping their own guard on disk means a restored tree matches a + // fresh install and survives a host that narrows AllowOverride to a subdirectory. + foreach (['backups', 'canned_responses', 'expenses', 'tmp'] as $sub) { + $sub_dir = $uploads . "/" . $sub; + if (is_dir($sub_dir)) { + @file_put_contents($sub_dir . "/.htaccess", BACKUP_UPLOADS_DENY_GUARD); + } + } } /** @@ -1267,6 +1287,10 @@ function backupRestoreArchive(mysqli $mysqli, string $zip_path, string $key, ?st return false; } + $storage_real = realpath(backupStorageDir()); + $uploads_real = realpath($uploads_dir) ?: $uploads_dir; + $safe_entries = []; + for ($i = 0; $i < $uz->numFiles; $i++) { $name = $uz->getNameIndex($i); if ($name === false) { @@ -1279,6 +1303,27 @@ function backupRestoreArchive(mysqli $mysqli, string $zip_path, string $key, ?st $error = "The database was restored but uploads.zip contains an unsafe path: $name"; return false; } + + // An archive may carry uploads, it may not decide what the web server will run. + // A .htaccess / .user.ini that re-enables PHP in a directory our own guards keep + // inert is a code-execution path the moment the archive is attacker-supplied - + // and the setup restore accepts one before the first user exists. Uploads carry + // no such file of their own, and our guards are rewritten from source below + // regardless, so these entries are simply never extracted. + if (in_array(strtolower(basename($name)), ['.htaccess', '.user.ini', '.htpasswd'], true)) { + continue; + } + + // Never let the archive write into the preserved backup storage directory - it + // survives the wipe, so anything landing there would stay without being re-guarded. + if ($storage_real !== false) { + $target = $uploads_real . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, rtrim($name, '/')); + if ($target === $storage_real || strpos($target, $storage_real . DIRECTORY_SEPARATOR) === 0) { + continue; + } + } + + $safe_entries[] = $name; } if (!is_dir($uploads_dir)) { @@ -1290,7 +1335,7 @@ function backupRestoreArchive(mysqli $mysqli, string $zip_path, string $key, ?st backupEmptyDirectory($uploads_dir, [backupStorageDir()]); } - $extracted = $uz->extractTo($uploads_dir); + $extracted = empty($safe_entries) ? true : $uz->extractTo($uploads_dir, $safe_entries); $uz->close(); if (!$extracted) { diff --git a/functions/payment_provider.php b/functions/payment_provider.php index 8c3c82f5b4..1f4f652a2b 100644 --- a/functions/payment_provider.php +++ b/functions/payment_provider.php @@ -6,8 +6,8 @@ * The services clients pay invoices by card through - Stripe, for now. Each * has its keys (live or test, as the keys say), whether it is on, the account * its payments go into, the invoices it is too small for (the card limit), and - * whether its fees are recorded as expenses - each night, by - * cron/nightly_tasks.php. Paying through one is functions/billing_pay.php. + * whether its fees are recorded as expenses - every few minutes, by + * cron/payment_provider_fees.php. Paying through one is functions/billing_pay.php. * * A provider is saved only once it is right: its keys look like that * provider's, come from the same mode, and - when they are new or changed - @@ -411,16 +411,19 @@ function paymentProviderUnrecordedSql() { /* * Record the provider's fee on its recent card payments that have none yet, - * from what it actually charged - each night (cron/nightly_tasks.php), or - * now from Payment Providers. A payment it hasn't settled yet waits for the + * from what it actually charged - every few minutes (cron/payment_provider_fees.php), + * or now from Payment Providers. A payment it hasn't settled yet waits for the * next run. Only while its fees are recorded, under a vendor and a category. * ['recorded' => how many, 'amount' => their fees by currency, 'waiting' => * how many not settled yet, 'failed' => how many it wouldn't say, 'error' => - * the last thing it said]. + * the last thing it said, 'busy' => another run had it in hand, so nothing was done]. + * + * One run at a time: "has no fee yet" is read before the fee is written, so two runs + * at once - the job, and someone pressing Record fees now - would each record it. */ function paymentProviderRecordFees(array $provider, $limit = 50) { global $mysqli; - $result = ['recorded' => 0, 'amount' => [], 'waiting' => 0, 'failed' => 0, 'error' => '']; + $result = ['recorded' => 0, 'amount' => [], 'waiting' => 0, 'failed' => 0, 'error' => '', 'busy' => false]; $private_key = (string) ($provider['payment_provider_private_key'] ?? ''); $vendor_id = intval($provider['payment_provider_expense_vendor'] ?? 0); $category_id = intval($provider['payment_provider_expense_category'] ?? 0); @@ -429,6 +432,26 @@ function paymentProviderRecordFees(array $provider, $limit = 50) { return $result; } + $lock = mysqli_fetch_row(mysqli_query($mysqli, "SELECT GET_LOCK('itflow_payment_provider_fees', 0)")); + if (intval($lock[0] ?? 0) !== 1) { + $result['busy'] = true; + return $result; + } + try { + return paymentProviderRecordFeesLocked($provider, $limit, $result); + } finally { + mysqli_query($mysqli, "SELECT RELEASE_LOCK('itflow_payment_provider_fees')"); + } +} + +/* paymentProviderRecordFees(), with its lock held. */ +function paymentProviderRecordFeesLocked(array $provider, $limit, array $result) { + global $mysqli; + $private_key = (string) $provider['payment_provider_private_key']; + $vendor_id = intval($provider['payment_provider_expense_vendor']); + $category_id = intval($provider['payment_provider_expense_category']); + $account_id = intval($provider['payment_provider_account'] ?? 0); + $sql = mysqli_query($mysqli, "SELECT payment_reference, MIN(payment_date) AS payment_date, SUM(payment_amount) AS payment_amount, GROUP_CONCAT(CONCAT(invoice_prefix, invoice_number) ORDER BY invoice_number SEPARATOR ', ') AS invoice_numbers, MIN(invoice_client_id) AS invoice_client_id @@ -477,8 +500,8 @@ function paymentProviderRecordFees(array $provider, $limit = 50) { * What has gone through a provider in the last 30 days - 'payments' (card * payments, a split one once), 'paid' and 'fees' (by currency), and, while * its fees are recorded, 'waiting' (payments with no fee recorded yet) and - * 'stale' (of those, the ones more than two days old - the nightly run - * should have had them). + * 'stale' (of those, the ones more than two days old - the Payment + * Provider Fees job should have had them). */ function paymentProviderActivity(array $provider) { global $mysqli; @@ -541,7 +564,7 @@ function paymentProviderProblems() { $activity = paymentProviderActivity($provider); if ($activity['stale']) { $problems[] = ['warning', 'fa-receipt', "$name's fees aren't being recorded", - $activity['stale'] . ' card payment' . ($activity['stale'] === 1 ? '' : 's') . ' more than two days old ' . ($activity['stale'] === 1 ? 'has' : 'have') . ' no fee recorded. The nightly run records them - or record them now.', 'payment_providers.php', 'Payment Providers']; + $activity['stale'] . ' card payment' . ($activity['stale'] === 1 ? '' : 's') . ' more than two days old ' . ($activity['stale'] === 1 ? 'has' : 'have') . ' no fee recorded. The Payment Provider Fees job in Maintenance > Cron records them - check it is on, or record them now.', 'payment_providers.php', 'Payment Providers']; } } return $problems; diff --git a/functions/portal.php b/functions/portal.php index e7e4b8760f..36ab0bb886 100644 --- a/functions/portal.php +++ b/functions/portal.php @@ -343,11 +343,17 @@ function portalViewAsAccess($agent_user_id, $contact_id) { if (intval($config_client_portal_enable) !== 1 || !$agent_user_id || !$contact_id) { return null; } - $agent = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_name, user_type, user_status, user_archived_at, user_role_id, role_is_admin - FROM users LEFT JOIN user_roles ON role_id = user_role_id WHERE user_id = $agent_user_id LIMIT 1")); + $agent = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_name, user_password, user_type, user_status, user_archived_at, user_role_id, role_is_admin, + user_token, user_config_force_mfa + FROM users LEFT JOIN user_roles ON role_id = user_role_id LEFT JOIN user_settings ON user_settings.user_id = users.user_id + WHERE users.user_id = $agent_user_id LIMIT 1")); if (!$agent || intval($agent['user_type']) !== 1 || intval($agent['user_status']) !== 1 || $agent['user_archived_at'] !== null) { return null; } + // Still has to set up the MFA their account requires (includes/load_user_session.php) + if (intval($agent['user_config_force_mfa'] ?? 0) === 1 && trim((string) $agent['user_token']) === '') { + return null; + } $admin = intval($agent['role_is_admin'] ?? 0) === 1; $level = function ($module) use ($mysqli, $admin, $agent) { if ($admin) { @@ -391,6 +397,7 @@ function portalViewAsAccess($agent_user_id, $contact_id) { 'user_id' => intval($contact['contact_user_id']), 'agent_user_id' => $agent_user_id, 'agent_name' => (string) $agent['user_name'], + 'agent_session_stamp' => userSessionStamp($agent['user_password'] ?? ''), // client/includes/check_login.php 'billing' => $level('module_sales') >= 1 && $level('module_financial') >= 1, ]; } diff --git a/functions/user.php b/functions/user.php index e17c799fa6..64dbe7a035 100644 --- a/functions/user.php +++ b/functions/user.php @@ -202,9 +202,34 @@ function userPasswordProblem($password) { */ function userSetPassword($user_id, $password) { global $mysqli; - $hash = escapeSql(password_hash((string) $password, PASSWORD_DEFAULT)); + $hash = password_hash((string) $password, PASSWORD_DEFAULT); $ciphertext = escapeSql(encryptUserSpecificKey((string) $password)); - mysqli_query($mysqli, "UPDATE users SET user_password = '$hash', user_specific_encryption_ciphertext = '$ciphertext' WHERE user_id = " . intval($user_id)); + mysqli_query($mysqli, "UPDATE users SET user_password = '" . escapeSql($hash) . "', user_specific_encryption_ciphertext = '$ciphertext' WHERE user_id = " . intval($user_id)); + userSessionRestamp($user_id, $hash); +} + +/** + * What a session keeps of the password it was signed in with - a digest of the hash, + * never the hash. A new password makes every session signed in before it stop + * matching, and the next page each one loads signs it out: includes/load_user_session.php + * for agents, client/includes/check_login.php for the portal. That covers every way a + * password is set - by its owner, by an admin, the incident-response reset, a portal + * reset link - with nothing to call, the same way disabling a user already ends their + * sessions. + */ +function userSessionStamp($password_hash) { + return hash('sha256', 'itflow-session|' . (string) $password_hash); +} + +/** + * Keep this browser signed in when the password just changed is its own user's - a new + * session id, and the stamp of the new hash. Every other session of theirs still ends. + */ +function userSessionRestamp($user_id, $password_hash) { + if (session_status() === PHP_SESSION_ACTIVE && intval($_SESSION['user_id'] ?? 0) === intval($user_id) && !headers_sent()) { + session_regenerate_id(true); + $_SESSION['user_session_stamp'] = userSessionStamp($password_hash); + } } /** Turn an agent's MFA off - and forget the browsers it trusted, which have to sign in afresh. */ diff --git a/includes/app_version.php b/includes/app_version.php index d102eeae48..67aef4b9cb 100644 --- a/includes/app_version.php +++ b/includes/app_version.php @@ -5,4 +5,4 @@ * Update this file each time we merge develop into master. Format is YY.MM (add a .v if there is more than one release a month. */ -DEFINE("APP_VERSION", "26.11.2"); +DEFINE("APP_VERSION", "26.11.3"); diff --git a/includes/cron_jobs.php b/includes/cron_jobs.php index d1a2b662b2..3ec554edec 100644 --- a/includes/cron_jobs.php +++ b/includes/cron_jobs.php @@ -75,6 +75,14 @@ function cronJobRegistry(): array 'schedule' => 'Interval', 'interval_minutes' => 1, ], + [ + 'name' => 'payment_provider_fees', + 'label' => 'Payment Provider Fees', + 'script' => 'payment_provider_fees.php', + 'description' => 'Records what Stripe charged on each card payment as an expense, once Stripe has settled it - while Admin > Payment Providers records its fees.', + 'schedule' => 'Interval', + 'interval_minutes' => 15, + ], [ 'name' => 'domain_refresher', 'label' => 'Domain Refresher', diff --git a/includes/load_user_session.php b/includes/load_user_session.php index 569cebdbab..fe446ff555 100644 --- a/includes/load_user_session.php +++ b/includes/load_user_session.php @@ -8,7 +8,7 @@ $mysqli, "SELECT role_is_admin, role_name, user_archived_at, user_avatar, user_config_force_mfa, user_config_records_per_page, user_config_theme_dark, user_email, user_name, user_role_id, - user_status, user_token, user_type FROM users + user_password, user_status, user_token, user_type FROM users LEFT JOIN user_settings ON users.user_id = user_settings.user_id LEFT JOIN user_roles ON user_role_id = role_id WHERE users.user_id = $session_user_id" @@ -16,6 +16,11 @@ $row = mysqli_fetch_assoc($sql); +$session_stamp_current = userSessionStamp($row['user_password'] ?? ''); +if ($row) { + unset($row['user_password']); +} + $session_name = escapeSql($row['user_name']); $session_email = $row['user_email']; $session_avatar = $row['user_avatar']; @@ -51,6 +56,25 @@ redirect("/login.php"); } +// Check the password hasn't changed since this session signed in - by them elsewhere, +// an admin, or the incident-response reset (userSessionStamp()) +if (!hash_equals($session_stamp_current, (string) ($_SESSION['user_session_stamp'] ?? ''))) { + session_unset(); + session_destroy(); + redirect("/login.php"); +} + +// MFA required on this account and not set up yet: setting it up, or signing out, is all +// this session may do - every other page, modal, AJAX call and POST goes back to the set +// up page. Signing in only sends them there; this is what keeps them there, including when +// an admin requires MFA, or resets it, on an agent who is already signed in. +if ($session_user_config_force_mfa === 1 && trim((string) $session_token) === '' && !requestIsMfaSetup([ + 'agent/user/mfa_enforcement.php' => [[[], []]], + 'agent/user/post.php' => [[[], ['csrf_token', 'enable_mfa', 'verify_code']], [['logout'], []]], +])) { + redirect("/agent/user/mfa_enforcement.php"); +} + // Load user client permissions (allow + deny lists) $user_client_access_sql = "SELECT client_id, permission_type FROM user_client_permissions WHERE user_id = $session_user_id"; $user_client_access_result = mysqli_query($mysqli, $user_client_access_sql); diff --git a/login.php b/login.php index 4f65eb91e1..048ad7f14d 100644 --- a/login.php +++ b/login.php @@ -471,6 +471,8 @@ function pendingExpired($sess, $ttl_seconds = 120) { $_SESSION['user_id'] = $user_id; $_SESSION['csrf_token'] = randomString(32); $_SESSION['logged'] = true; + // A later password change ends this session (userSessionStamp()) + $_SESSION['user_session_stamp'] = userSessionStamp($selectedRow['user_password'] ?? ''); if ($force_mfa == 1 && $token == NULL) { $config_start_page = "user/mfa_enforcement.php"; @@ -710,6 +712,8 @@ class='form-control' placeholder='6-digit code' aria-label='6-digit code' $_SESSION['user_type'] = 2; $_SESSION['contact_id'] = $contact_id; $_SESSION['login_method'] = "local"; + // A later password change ends this session (userSessionStamp()) + $_SESSION['user_session_stamp'] = userSessionStamp($selectedRow['user_password'] ?? ''); // Keep consistent with agent flow (helps any shared session checks) $_SESSION['logged'] = true;