Skip to content

Global Search PR 1 Review

Ed Mozley edited this page Dec 6, 2026 · 1 revision

Global Search PR 1 - review (#537)

PR #537 by @cloudcogsio, "Global Search PR 1 of 2", tracking issue #536. Merged 6 December 2026 (merge commit 749612fb1). Verdict: Merge + fix.

The design was agreed first, on Global Search - design (decisions D1-D13, agreed 5 December 2026). This page says what the PR did, what I changed on top and why, and what a later change must not undo.

What it set out to do

The first of two PRs (D10), carrying the search service as well (D13): the index, the permissions and GlobalSearchService, with no screen and no endpoint. Nothing reads the new index rows yet except the service and its tests. PR 2 brings the results page, the switches, the home page box, Ctrl-K's See all results row, previews, REST and MCP.

  • Five new kinds of record in the search index: tasks, changes, problems, contracts and projects, one row each (title plus text fields), named in one registry, searchRecordTypes() (includes/search/records.php).
  • Permissions inside the query, judged on each record's own table at search time: company, members-only projects, Knowledge access lists, the created-date range.
  • Ctrl-K follows Knowledge access lists (D9) on every install, whatever Global Search's switch will say.
  • Documents across companies (D12): an optional per-entry companies rule in the documents registry, so a search across several companies judges each document by its parent records in those companies.
  • A staged rebuild in System β†’ Search, which records index version 2 at the end.
  • GlobalSearchService::search() with the keywords in:, after:, before: and company:.
  • Six test files and shared fixtures.

The PR said openly where it followed D13 rather than the design page's section 12 Delivery, which still listed the service and keywords under PR 2. That section is now corrected.

Verdict: Merge + fix

The design was followed, the permission model is sound, and the tests are good. An independent permission review of the PR's own code found no leaks: every value is bound, company: can only narrow, empty company lists fail closed, NULL (Default company) rows are in only when the Default company is reachable, the ticket department rule is identical, and members-only projects, Knowledge access lists, contracts and the module filter apply in both the list and the count queries. Each type fails closed on its own, and visibility is judged on the live tables.

The fixes on top are hardening for the next front doors (REST and MCP in PR 2), a stale-row prune, and test fixtures that had been failing on main for reasons outside this PR.

What was good - copy this

  • Design agreed first, then followed - and where the PR departed from the design page (D13 over section 12), it said so in the PR body rather than leaving a reviewer to find it.
  • Permission is judged on each record's live table, inside the query. The index holds a copy of the text, never the answer to "who may see this". A record moved to another company drops out of results at once, re-indexed or not, so a stale index row can never show something to the wrong person.
  • One registry. searchRecordTypes() is read by the indexer, the rebuild, the permission clause and the service, so the four cannot drift apart. Adding a type later is one entry plus its hooks.
  • Index hooks after the commit that log and never throw (searchIndexRecordSafe()), including in the writes that bypass the services: workflow task creation, task clones and their subtasks, repeat occurrences, the starters task text refresh, tasks following a ticket's company move, tasks moved with a change, template clean-up. A failed index never fails a save.
  • A resumable, staged rebuild, with a fallback for a copy of System β†’ Search left open from before the upgrade (it still sends the old since_ticket_id and gets the old protocol, so it cannot loop).
  • The service takes a scope and never reads the session, so every front door (page, REST, MCP) gives the same answer for the same reach.
  • Every denial in the tests is paired with a positive control - the same record, found by someone who may see it - so a test cannot pass because nothing matched.
  • Pre-existing failing tests listed honestly in the PR, with the error each one stopped on, instead of being hidden or skipped.

What was fixed on top, and why

1. A company list can narrow, never widen (97cb3279c)

The PR's own callers only ever pass companies the analyst can reach. But searchScopeForAnalyst() accepted whatever tenant_ids an override handed it, and PR 2 adds REST and MCP, where the list comes from an API key. So the cut is now made where every scope is built, not left to each caller:

// TRAP: a caller's company list NARROWS, never widens (hardening from the
// PR #537 review). ...
if (function_exists('isMultiTenant') && isMultiTenant($conn)) {
    $reach   = array_map('intval', getAccessibleTenantIds($conn, (int)$analystId));
    $default = getDefaultTenantId($conn);
    if (isset($scope['tenant_ids']) && is_array($scope['tenant_ids'])) {
        $scope['tenant_ids'] = array_values(array_intersect(array_map('intval', $scope['tenant_ids']), $reach));
        $scope['include_default'] = !empty($scope['include_default']) && in_array($default, $scope['tenant_ids'], true);
    } elseif (empty($scope['tenant_id'])) {
        // tenant_id null with no list would render as "no company filter at all".
        $scope['tenant_ids'] = $reach;
        $scope['include_default'] = !empty($scope['include_default']) && in_array($default, $reach, true);
    } elseif ((int)$scope['tenant_id'] !== -1 && !in_array((int)$scope['tenant_id'], $reach, true)) {
        $scope['tenant_id'] = -1;
        $scope['include_default'] = false;
    }
}

In plain words: a list is cut down to the companies the analyst can reach; "no company filter" on a multi-company install becomes "the companies you can reach"; include_default survives only when the Default company is actually in the list; and a single named company the analyst cannot reach becomes -1, which matches nothing.

ticketScopeFilterForCompanies() (includes/ticket_department_scope.php) does the same intersection, so the documents registry's ticket entries are safe even when called from somewhere other than search:

if (isMultiTenant($conn)) {
    $companyIds = array_values(array_intersect(array_map('intval', $companyIds),
                                               array_map('intval', getAccessibleTenantIds($conn, $analystId))));
}

documentVisibilityClause() already intersected its list this way in the PR.

A scope built by hand judges no records. searchScopeToSql() now carries a TRAP: that a scope without record_clause (a test, a script) judges no task, change, problem, contract or project at all, members-only projects included. Never search on behalf of a person with a hand-built scope; always use searchScopeForAnalyst() or searchScopeForAnalystAllCompanies().

One test check changed its expected answer. tests/global-search-permissions.php had a check that an analyst with only company A found a company B document after its parent task moved to A, by naming both companies in the scope. That passed only because naming B widened the scope. With the cut in place the document (still company B's own row) stays out, which is the safe answer; a new positive control checks that an analyst with both companies still finds it through the moved parent.

isMultiTenant() is cached per run. The same test asked isMultiTenant() before its fixtures had added their two companies. On a single-company install that answer stayed "single company" for the whole run, so the cross-company checks failed falsely. It now asks after the fixtures.

2. The rebuild also prunes Knowledge rows whose article is gone (67c9b9add)

searchBackfillPrune() removed rows of the five new record types whose record no longer exists, but not Knowledge articles deleted without being taken out of the index (a direct delete, an old test fixture). On the test install, 198 such rows made System β†’ Search read "202 indexed of 2". They were never shown to anyone, because visibility is judged on the live table, but the count was wrong. The final stage now sweeps them too:

$st = $conn->prepare("DELETE sd FROM search_documents sd
                       WHERE sd.source_type = ?
                         AND NOT EXISTS (SELECT 1 FROM knowledge_articles x WHERE x.id = sd.source_id)");
$st->execute([SEARCH_SOURCE_KB_ARTICLE]);

3. Test fixtures for MySQL strict mode and for any install (8aebd62cc)

The PR listed tests that already failed on main. Two causes, both fixed:

  • Required columns left out. Under strict mode (STRICT_TRANS_TABLES) an INSERT that skips a NOT NULL column with no default fails with error 1364. document-permissions.php and document-search-permissions.php inserted contracts without contract_number; ticket-department-scope.php a watcher without created_datetime; task-recurrence-spawn.php tasks without created_by_id. A lenient server fills in a blank; a strict one stops. They now fill every required column:

    $conn->prepare("INSERT INTO contracts (contract_number, title) VALUES ('ZZ-DOCTEST', 'ZZ doc-test contract')")->execute();
  • Companies looked up by name. The tests/knowledge-visibility/* harnesses looked two companies up by the names they have on one developer's own install. Anywhere else the lookup found nothing, id 0 went into foreign keys, and they died before their first check. They now make their own two ZZ companies with kvCompanies() in tests/knowledge-visibility/_bootstrap.php, removed when the run ends:

    function kvCompanies(PDO $c): array
    {
        $tag = 'ZZ KV ' . bin2hex(random_bytes(3));
        $ids = [];
        foreach (['One', 'Two'] as $n) {
            $c->prepare("INSERT INTO tenants (name, slug) VALUES (?, ?)")
              ->execute(["$tag Company $n", strtolower(str_replace(' ', '-', "$tag-company-$n"))]);
            $ids[] = (int)$c->lastInsertId();
        }
        // ... removed in a shutdown function, only if still named 'ZZ KV %'
        return $ids;
    }

    Never look a company up by name in a test - make your own.

4. Talk endpoints in the module-access coverage test (4379caef1)

tests/module-access-coverage.php had failed since 6.0.0 because api/talk/ask.php and api/talk/live.php have no module guard and no listed reason. @cloudcogsio spotted it. Talk is not a module: talkAllowed() lets in only analysts an administrator ticked, and every tool it answers with checks module access and company itself. Both are now listed with that reason.

5. Translations (c584e74d6)

The 11 new System β†’ Search strings in all 22 other languages.

How it was tested

On the test install:

  • His six new test files all pass - indexing 41, permissions 42, query 21, keywords 20, rebuild 16, service 33 - on a single-company install and again with a second company.
  • Existing related tests pass: search/run.php 27, tenant-support.php 27, document-permissions.php 22, document-search-permissions.php 9, ticket-department-scope.php 24, project-documents-api.php 45, knowledge-documents-api.php 76, knowledge-search-ranked.php 9, every knowledge-visibility file, task-clone, task-recurrence-*, the change and project company-move tests, contract-assets, workflow-task-actions, starters, access-scope-5-1, module-access-coverage.php 14.
  • The strict-mode failures were reproduced by running the test install's connections in strict mode, then fixed.
  • The staged rebuild through the real endpoint: 7 calls, one per stage, under a second in all; 186 of 186 records indexed.
  • The guards pass, and GitHub Actions was green on the push.

Files

File Change
πŸ”΄ includes/search/search.php New scope keys, record_clause, the module/type map, searchCorpusWhere(), searchCorpusModuleCounts(), group_by => 'record'; on top: the company list cut in searchScopeForAnalyst(), the hand-built-scope TRAP
πŸ”΄ includes/search/records.php New: searchRecordTypes(), the indexer and searchRecordVisibilityClause()
πŸ”΄ includes/documents.php, includes/search/documents_index.php The optional companies rule; documentVisibilityClause() / documentSearchVisibilityClause() take a company list
πŸ”΄ includes/tenancy.php tenantIdsFilter(); allAccessibleTenantsFilter() uses it; ticketsFollowCompanyMove() re-indexes moved tasks
πŸ”΄ includes/ticket_department_scope.php ticketScopeFilterForCompanies(); on top: the company list cut
🟑 includes/contract_party.php contractVisibilitySqlForScope() uses tenantIdsFilter()
🟑 includes/search/backfill.php Record types, searchRebuildSlice(), the prune; on top: the Knowledge prune
🟑 includes/search/global.php, includes/search/keywords.php, includes/services/search.php New: index version, every-company scope, keywords, GlobalSearchService
🟑 includes/services/{changes,contracts,problems,projects,project_templates,tasks,task_recurrence}.php, includes/starters/service.php, workflow/includes/engine.php Index hooks after commit
🟑 api/system/search_rebuild.php, api/system/search_status.php, system/search/index.php, scripts/search_backfill.php Staged rebuild, records indexed figure
🟑 api/system/global_search.php Ctrl-K's content block asks only for ticket rows and articles
🟒 lang/*/system.php 11 strings, in every language
🟒 tests/global-search-*.php, tests/support/global-search-fixtures.php New tests
🟒 tests/global-search-permissions.php On top: isMultiTenant() asked after fixtures; one check corrected
🟒 tests/document-permissions.php, tests/document-search-permissions.php, tests/ticket-department-scope.php, tests/task-recurrence-spawn.php, tests/knowledge-visibility/*, tests/module-access-coverage.php On top: strict-mode and any-install fixtures; Talk endpoints listed

What this means for users

  • Ctrl-K no longer lists Knowledge articles restricted to other analysts or teams, or archived ones (D9). This is stricter than before, on every install.
  • System β†’ Search rebuilds in stages (tickets, then tasks, changes, problems, contracts and projects, then articles) and shows how many tasks, changes, problems, contracts and projects are indexed, next to tickets and articles. After upgrading, one rebuild fills in the new rows.
  • Nothing else is visible yet. The results page, the home page box and the REST/MCP search come with PR 2.

Related

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally