@memberjunction/search-engine 6.2.0-edge.4 → 6.2.0-edge.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/generic/EntitySearchProvider.d.ts +12 -4
- package/dist/generic/EntitySearchProvider.d.ts.map +1 -1
- package/dist/generic/EntitySearchProvider.js +13 -6
- package/dist/generic/EntitySearchProvider.js.map +1 -1
- package/dist/generic/FullTextSearchProvider.d.ts +8 -0
- package/dist/generic/FullTextSearchProvider.d.ts.map +1 -1
- package/dist/generic/FullTextSearchProvider.js +12 -4
- package/dist/generic/FullTextSearchProvider.js.map +1 -1
- package/dist/generic/ISearchProvider.d.ts +67 -2
- package/dist/generic/ISearchProvider.d.ts.map +1 -1
- package/dist/generic/ISearchProvider.js +63 -0
- package/dist/generic/ISearchProvider.js.map +1 -1
- package/dist/generic/ResultFieldProjection.d.ts +35 -0
- package/dist/generic/ResultFieldProjection.d.ts.map +1 -0
- package/dist/generic/ResultFieldProjection.js +97 -0
- package/dist/generic/ResultFieldProjection.js.map +1 -0
- package/dist/generic/ScopeDimensionResolver.d.ts +28 -0
- package/dist/generic/ScopeDimensionResolver.d.ts.map +1 -1
- package/dist/generic/ScopeDimensionResolver.js +55 -3
- package/dist/generic/ScopeDimensionResolver.js.map +1 -1
- package/dist/generic/ScopeExplanation.d.ts +24 -13
- package/dist/generic/ScopeExplanation.d.ts.map +1 -1
- package/dist/generic/ScopeExplanation.js +39 -26
- package/dist/generic/ScopeExplanation.js.map +1 -1
- package/dist/generic/ScopeFilterGuard.d.ts +18 -0
- package/dist/generic/ScopeFilterGuard.d.ts.map +1 -1
- package/dist/generic/ScopeFilterGuard.js +49 -0
- package/dist/generic/ScopeFilterGuard.js.map +1 -1
- package/dist/generic/ScopeTemplateRenderer.d.ts +3 -0
- package/dist/generic/ScopeTemplateRenderer.d.ts.map +1 -1
- package/dist/generic/ScopeTemplateRenderer.js +11 -2
- package/dist/generic/ScopeTemplateRenderer.js.map +1 -1
- package/dist/generic/ScopeValueEscaper.d.ts +10 -3
- package/dist/generic/ScopeValueEscaper.d.ts.map +1 -1
- package/dist/generic/ScopeValueEscaper.js +51 -5
- package/dist/generic/ScopeValueEscaper.js.map +1 -1
- package/dist/generic/SearchEngine.d.ts +532 -50
- package/dist/generic/SearchEngine.d.ts.map +1 -1
- package/dist/generic/SearchEngine.js +1396 -244
- package/dist/generic/SearchEngine.js.map +1 -1
- package/dist/generic/SearchEnricher.d.ts +3 -1
- package/dist/generic/SearchEnricher.d.ts.map +1 -1
- package/dist/generic/SearchEnricher.js +10 -5
- package/dist/generic/SearchEnricher.js.map +1 -1
- package/dist/generic/StorageSearchProvider.d.ts +37 -20
- package/dist/generic/StorageSearchProvider.d.ts.map +1 -1
- package/dist/generic/StorageSearchProvider.js +79 -105
- package/dist/generic/StorageSearchProvider.js.map +1 -1
- package/dist/generic/TagSearchProvider.d.ts +5 -1
- package/dist/generic/TagSearchProvider.d.ts.map +1 -1
- package/dist/generic/TagSearchProvider.js +5 -2
- package/dist/generic/TagSearchProvider.js.map +1 -1
- package/dist/generic/VectorSearchProvider.d.ts +3 -0
- package/dist/generic/VectorSearchProvider.d.ts.map +1 -1
- package/dist/generic/VectorSearchProvider.js +9 -3
- package/dist/generic/VectorSearchProvider.js.map +1 -1
- package/dist/generic/search.types.d.ts +102 -5
- package/dist/generic/search.types.d.ts.map +1 -1
- package/dist/generic/search.types.js +0 -9
- package/dist/generic/search.types.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/permissions/SearchScopePermissionResolver.d.ts +6 -5
- package/dist/permissions/SearchScopePermissionResolver.d.ts.map +1 -1
- package/dist/permissions/SearchScopePermissionResolver.js +15 -13
- package/dist/permissions/SearchScopePermissionResolver.js.map +1 -1
- package/dist/providers/AzureAISearchProvider.d.ts +4 -1
- package/dist/providers/AzureAISearchProvider.d.ts.map +1 -1
- package/dist/providers/AzureAISearchProvider.js +8 -6
- package/dist/providers/AzureAISearchProvider.js.map +1 -1
- package/dist/providers/ElasticsearchSearchProvider.d.ts +3 -0
- package/dist/providers/ElasticsearchSearchProvider.d.ts.map +1 -1
- package/dist/providers/ElasticsearchSearchProvider.js +8 -7
- package/dist/providers/ElasticsearchSearchProvider.js.map +1 -1
- package/dist/providers/OpenSearchSearchProvider.d.ts +5 -1
- package/dist/providers/OpenSearchSearchProvider.d.ts.map +1 -1
- package/dist/providers/OpenSearchSearchProvider.js +9 -5
- package/dist/providers/OpenSearchSearchProvider.js.map +1 -1
- package/dist/providers/TypesenseSearchProvider.d.ts +4 -1
- package/dist/providers/TypesenseSearchProvider.d.ts.map +1 -1
- package/dist/providers/TypesenseSearchProvider.js +8 -7
- package/dist/providers/TypesenseSearchProvider.js.map +1 -1
- package/package.json +10 -10
|
@@ -19,28 +19,66 @@
|
|
|
19
19
|
*
|
|
20
20
|
* @module @memberjunction/search-engine
|
|
21
21
|
*/
|
|
22
|
-
import { CompositeKey, EntityPermissionType, LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
22
|
+
import { CompositeKey, EntityPermissionType, KeyValuePair, LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
23
23
|
import { SearchEngineBase } from '@memberjunction/core-entities';
|
|
24
|
-
import { BaseSingleton, EscapeSQLString, MJGlobal, NormalizeUUID, UUIDsEqual } from '@memberjunction/global';
|
|
24
|
+
import { BaseSingleton, EscapeSQLString, IsValidUUID, MJGlobal, NormalizeUUID, UUIDSet, UUIDsEqual } from '@memberjunction/global';
|
|
25
|
+
import { FileStorageEngine, StorageAccessEvaluator } from '@memberjunction/storage';
|
|
25
26
|
import { BaseSearchProvider } from './ISearchProvider.js';
|
|
26
27
|
import { SearchFusion, ApplySemanticFloor } from './SearchFusion.js';
|
|
27
28
|
import { SearchEnricher } from './SearchEnricher.js';
|
|
29
|
+
import { ProjectSearchResultForReader } from './ResultFieldProjection.js';
|
|
28
30
|
import { FullTextSearchProvider } from './FullTextSearchProvider.js';
|
|
31
|
+
import { StorageSearchProvider } from './StorageSearchProvider.js';
|
|
29
32
|
import { BaseReRanker } from './BaseReRanker.js';
|
|
30
33
|
import { NoopReRanker, LoadNoopReRanker } from './NoopReRanker.js';
|
|
31
34
|
import { RerankerBudgetGuard } from '../rerankers/RerankerBudgetGuard.js';
|
|
32
35
|
import { RenderScopeTemplate, RenderScopeJsonTemplate } from './ScopeTemplateRenderer.js';
|
|
33
36
|
import { LaneKindForIndexType } from './ScopeValueEscaper.js';
|
|
34
|
-
import { CheckRenderedTemplate, CheckRequiredMetadataKeys, ParseRequiredMetadataKeys } from './ScopeFilterGuard.js';
|
|
37
|
+
import { CheckRenderedFolderPath, CheckRenderedTemplate, CheckRequiredMetadataKeys, ParseRequiredMetadataKeys } from './ScopeFilterGuard.js';
|
|
35
38
|
import { ScopeDimensionResolver } from './ScopeDimensionResolver.js';
|
|
36
39
|
import { GetSearchScopePermissionResolver } from '../permissions/SearchScopePermissionResolver.js';
|
|
37
40
|
/**
|
|
38
|
-
* Emitted
|
|
39
|
-
* Shared by the dry run and the search path
|
|
41
|
+
* Emitted when a GLOBAL scope configures no lanes at all — a global scope runs unconstrained, so
|
|
42
|
+
* every provider searches everything available to it. Shared by the dry run and the search path.
|
|
40
43
|
*/
|
|
41
|
-
const UNBOUNDED_SCOPE_DIAGNOSTIC = 'this scope configures NO lanes (no external indexes, entities, or storage accounts). ' +
|
|
42
|
-
'
|
|
43
|
-
|
|
44
|
+
const UNBOUNDED_SCOPE_DIAGNOSTIC = 'this global scope configures NO lanes (no external indexes, entities, or storage accounts). ' +
|
|
45
|
+
'A global scope is UNSCOPED: every provider searches everything available to it with no filter.';
|
|
46
|
+
/**
|
|
47
|
+
* Emitted when a NON-global scope configures no lanes. Each lane list reaches the providers empty,
|
|
48
|
+
* and an empty list means "nothing for this provider", so the scope reaches nothing — never everything.
|
|
49
|
+
*/
|
|
50
|
+
const NO_LANES_DIAGNOSTIC = 'this scope configures NO lanes (no external indexes, entities, or storage accounts), so it reaches nothing: ' +
|
|
51
|
+
'a non-global scope searches only what its lanes name. Add a lane to make it retrieve.';
|
|
52
|
+
/**
|
|
53
|
+
* Emitted when a NON-global scope has no enabled `MJ: Search Scope Providers` row. It runs no provider —
|
|
54
|
+
* a scope with no provider rows used to run every provider, which made disabling the last row widen it.
|
|
55
|
+
*/
|
|
56
|
+
const NO_PROVIDER_ROWS_DIAGNOSTIC = 'this scope has no enabled provider rows (MJ: Search Scope Providers), so it runs no provider and returns nothing: ' +
|
|
57
|
+
'a non-global scope runs only the providers it lists. Add an enabled provider row to make it retrieve.';
|
|
58
|
+
/** Emitted when a NON-global scope's provider rows name no provider this engine can run. */
|
|
59
|
+
function noRunnableProviderDiagnostic(isPreview) {
|
|
60
|
+
const which = isPreview ? 'configured, available provider that supports preview searches' : 'configured, available provider';
|
|
61
|
+
return `this scope's enabled provider rows name no ${which}, so it runs no provider and returns nothing. ` +
|
|
62
|
+
'Check that each provider row names an active MJ: Search Providers row whose provider initialised.';
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Emitted when a NON-global scope's runnable providers read no lane kind the scope configures
|
|
66
|
+
* (`BaseSearchProvider.ConsumesLaneKinds`) — e.g. a Vector provider row over entity lanes only. Each provider
|
|
67
|
+
* would get an empty list for every lane it reads, so none is called and the scope reaches nothing.
|
|
68
|
+
*/
|
|
69
|
+
function noProviderReadsALaneDiagnostic(providers, lanes) {
|
|
70
|
+
const listed = providers.map(p => `${p.DisplayName} (reads ${p.Provider.ConsumesLaneKinds.join(', ') || 'no lane'})`).join('; ');
|
|
71
|
+
const configured = Array.from(new Set(lanes.filter(l => l.Status === 'Active').map(l => l.Kind))).join(', ');
|
|
72
|
+
return `none of this scope's providers reads a lane kind it configures — providers: ${listed}; active lanes: ${configured}. ` +
|
|
73
|
+
'It reaches nothing: add a lane each provider reads (e.g. a Vector external-index row for a vector provider), ' +
|
|
74
|
+
'or a provider row for a provider that reads these lanes.';
|
|
75
|
+
}
|
|
76
|
+
/** Emitted (dry run only) when a lane is skipped: the real search refuses on the first such lane. */
|
|
77
|
+
function refusedLanesDiagnostic(skipped) {
|
|
78
|
+
const named = skipped.map(l => `${l.Kind} "${l.Target}"`).join(', ');
|
|
79
|
+
return `a real search would be refused: ${skipped.length === 1 ? 'a lane is' : `${skipped.length} lanes are`} unusable (${named}). ` +
|
|
80
|
+
'A search refuses a scope with any unusable lane rather than search the others; fix the lane(s) to make it retrieve.';
|
|
81
|
+
}
|
|
44
82
|
// Keep the default re-ranker registration alive under tree-shaking
|
|
45
83
|
LoadNoopReRanker();
|
|
46
84
|
/**
|
|
@@ -105,6 +143,12 @@ export class SearchEngine extends BaseSingleton {
|
|
|
105
143
|
static { this.CACHE_TTL_MS = 30_000; }
|
|
106
144
|
/** Maximum cached entries across all users. LRU-evicted on overflow. */
|
|
107
145
|
static { this.CACHE_MAX_ENTRIES = 500; }
|
|
146
|
+
/**
|
|
147
|
+
* Ceiling on the per-provider over-fetch multiplier, whatever its source (caller, scope metadata or
|
|
148
|
+
* the engine default). Above it a single metadata edit would multiply every provider call for every
|
|
149
|
+
* caller of the scope, and vector providers bill per candidate.
|
|
150
|
+
*/
|
|
151
|
+
static { this.MAX_OVERFETCH_FACTOR = 20; }
|
|
108
152
|
/**
|
|
109
153
|
* Resolver for a scope's declared Search Context dimensions. Overridable so a host can
|
|
110
154
|
* supply additional derivation sources (e.g. an external signal) without forking the engine.
|
|
@@ -135,7 +179,11 @@ export class SearchEngine extends BaseSingleton {
|
|
|
135
179
|
if (this._configured && !forceRefresh)
|
|
136
180
|
return;
|
|
137
181
|
this._defaultMaxResults = config.DefaultMaxResults ?? 20;
|
|
138
|
-
|
|
182
|
+
// `??` passes NaN/Infinity through; a non-finite default would have become the provider topK.
|
|
183
|
+
const configuredDefault = config.DefaultPermissionOverfetchFactor;
|
|
184
|
+
this._defaultOverfetchFactor = typeof configuredDefault === 'number' && Number.isFinite(configuredDefault)
|
|
185
|
+
? this.clampOverfetchFactor(configuredDefault, 'the engine default')
|
|
186
|
+
: 2;
|
|
139
187
|
this._providerEntries = [];
|
|
140
188
|
// Ensure SearchEngineBase has loaded provider + scope metadata
|
|
141
189
|
await this.Base.Config(forceRefresh, contextUser);
|
|
@@ -182,6 +230,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
182
230
|
let invocationBudgetGuard = null;
|
|
183
231
|
let invocationRerankerName = null;
|
|
184
232
|
try {
|
|
233
|
+
// A malformed audience fails the search here rather than being skipped later: a reader the
|
|
234
|
+
// host failed to map would otherwise restrict nothing, and the room would see the caller's reach.
|
|
235
|
+
this.validateAudience(params.Audience);
|
|
185
236
|
// Defensive null-check: `params.Query.trim()` throws on null/undefined,
|
|
186
237
|
// and Sage's LLM has been observed to emit empty/missing tool args.
|
|
187
238
|
// Coerce to string before validating so we surface a clean error
|
|
@@ -225,12 +276,14 @@ export class SearchEngine extends BaseSingleton {
|
|
|
225
276
|
const topK = params.MaxResults ?? this._defaultMaxResults;
|
|
226
277
|
const mode = params.Mode ?? 'full';
|
|
227
278
|
const isPreview = mode === 'preview';
|
|
228
|
-
const overfetchFactor = Math.max(1, params.PermissionOverfetchFactor ?? this._defaultOverfetchFactor);
|
|
229
|
-
const providerTopK = Math.max(topK, Math.ceil(topK * overfetchFactor));
|
|
230
279
|
// ──────────────────────────────────────────────────────────
|
|
231
280
|
// Resolve scopes (when supplied)
|
|
232
281
|
// ──────────────────────────────────────────────────────────
|
|
233
|
-
const resolvedScopes = this.resolveScopes(params.ScopeIDs);
|
|
282
|
+
const { Bundles: resolvedScopes, Unresolved: unresolvedScopeIDs } = this.resolveScopes(params.ScopeIDs);
|
|
283
|
+
if (unresolvedScopeIDs.length > 0) {
|
|
284
|
+
// Before the cache lookup: a scope deactivated seconds ago must not be served from its old entry.
|
|
285
|
+
return this.refuseUnresolvableScopes(unresolvedScopeIDs, params, contextUser, startTime);
|
|
286
|
+
}
|
|
234
287
|
const isUnconstrained = resolvedScopes.length === 0 || resolvedScopes.some(s => s.Scope.IsGlobal);
|
|
235
288
|
// ──────────────────────────────────────────────────────────
|
|
236
289
|
// Cache lookup (next PR #2532). Skip preview searches — they're already
|
|
@@ -250,6 +303,14 @@ export class SearchEngine extends BaseSingleton {
|
|
|
250
303
|
if (hit)
|
|
251
304
|
this._cache.delete(cacheKey); // expired
|
|
252
305
|
}
|
|
306
|
+
// Resolved after the cache lookup, so a cache hit never pays for scope-config parsing or logs a clamp.
|
|
307
|
+
const overfetchFactor = this.ResolvePermissionOverfetchFactor(params, resolvedScopes);
|
|
308
|
+
const providerTopK = Math.max(topK, Math.ceil(topK * overfetchFactor));
|
|
309
|
+
// Per-provider events report a count of hits taken before any permission pass. Cap it at the
|
|
310
|
+
// caller's own topK so the over-fetch factor does not inflate what a stream client is told.
|
|
311
|
+
const partialEvents = onProviderResolved
|
|
312
|
+
? (ev) => onProviderResolved({ ...ev, results: ev.results.slice(0, topK) })
|
|
313
|
+
: undefined;
|
|
253
314
|
// ──────────────────────────────────────────────────────────
|
|
254
315
|
// Execute providers — either unscoped (original path) or per-scope
|
|
255
316
|
// ──────────────────────────────────────────────────────────
|
|
@@ -259,14 +320,14 @@ export class SearchEngine extends BaseSingleton {
|
|
|
259
320
|
// the unconstrained path, which resolves no scope and therefore decides nothing.
|
|
260
321
|
const scopeDecisions = [];
|
|
261
322
|
if (isUnconstrained) {
|
|
262
|
-
const labeledLists = await this.executeProviders(params.Query, providerTopK, params.Filters, contextUser, isPreview, undefined,
|
|
323
|
+
const labeledLists = await this.executeProviders(params.Query, providerTopK, params.Filters, contextUser, isPreview, undefined, partialEvents, params.MinScore);
|
|
263
324
|
sourceCounts = this.countSources(labeledLists);
|
|
264
325
|
const defaultFusionWeights = params.FusionWeightsOverride;
|
|
265
326
|
fusedResults = this._fusion.Fuse(labeledLists, providerTopK, defaultFusionWeights);
|
|
266
327
|
}
|
|
267
328
|
else {
|
|
268
329
|
// Run each scope independently, then cross-scope RRF
|
|
269
|
-
const perScopeRunResults = await Promise.all(resolvedScopes.map(bundle => this.executeScopeBundle(params.Query, providerTopK, params.Filters, contextUser, isPreview, bundle, params.SearchContext, params.FusionWeightsOverride, this.principalsFrom(params),
|
|
330
|
+
const perScopeRunResults = await Promise.all(resolvedScopes.map(bundle => this.executeScopeBundle(params.Query, providerTopK, params.Filters, contextUser, isPreview, bundle, params.SearchContext, params.FusionWeightsOverride, this.principalsFrom(params), partialEvents, params.MinScore)));
|
|
270
331
|
const sc = { Vector: 0, FullText: 0, Entity: 0, Storage: 0 };
|
|
271
332
|
const perScopeFused = new Map();
|
|
272
333
|
for (const r of perScopeRunResults) {
|
|
@@ -303,16 +364,29 @@ export class SearchEngine extends BaseSingleton {
|
|
|
303
364
|
// Dedup → content-item promotion/exclusion → merge promoted entities → permission safety net → score threshold → enrich
|
|
304
365
|
// ──────────────────────────────────────────────────────────
|
|
305
366
|
let results = this._fusion.Deduplicate(fusedResults);
|
|
306
|
-
|
|
307
|
-
|
|
367
|
+
if (isUnconstrained) {
|
|
368
|
+
// Scoped results were promoted per scope, before their lane bounds were applied (boundScopeHits):
|
|
369
|
+
// promoting here, after fusion, would let a promoted hit skip its origin entity's lane ExtraFilter.
|
|
370
|
+
this._enricher.Provider = this.ProviderToUse;
|
|
371
|
+
results = await this._enricher.ExcludeEntitySourcedContentItems(results, contextUser);
|
|
372
|
+
results = this._fusion.Deduplicate(results);
|
|
373
|
+
}
|
|
308
374
|
const beforePermCount = results.length;
|
|
309
|
-
|
|
310
|
-
|
|
375
|
+
const permissionStats = { OriginGateRemoved: 0 };
|
|
376
|
+
results = await this.filterByPermissions(results, contextUser, permissionStats);
|
|
377
|
+
if (permissionStats.OriginGateRemoved > 0) {
|
|
378
|
+
// By design, not a push-down gap: content derived from a record the user may not read.
|
|
379
|
+
const removed = permissionStats.OriginGateRemoved;
|
|
380
|
+
LogStatus(`SearchEngine: origin-record gate removed ${removed} result(s) derived from records the user may not read.`);
|
|
381
|
+
}
|
|
382
|
+
// Origin-gate removals are counted above, so this stays the push-down signal it always was.
|
|
383
|
+
const lateFilteredCount = beforePermCount - results.length - permissionStats.OriginGateRemoved;
|
|
311
384
|
if (lateFilteredCount > 0) {
|
|
312
385
|
// Observability: Section 3.6 — if a provider's push-down is complete, this
|
|
313
386
|
// number should be zero (the safety net should never trim anything).
|
|
314
387
|
LogStatus(`SearchEngine: Residual permission filter removed ${lateFilteredCount} result(s) — consider tightening provider push-down.`);
|
|
315
388
|
}
|
|
389
|
+
results = await this.FilterForAudience(results, params, contextUser);
|
|
316
390
|
// MinScore was applied to the semantic lane before fusion (ApplySemanticFloor). The
|
|
317
391
|
// fused Score is rank-based RRF, so it is deliberately not compared to MinScore here.
|
|
318
392
|
// Trim to caller's requested topK (we overfetched earlier)
|
|
@@ -374,36 +448,31 @@ export class SearchEngine extends BaseSingleton {
|
|
|
374
448
|
}
|
|
375
449
|
}
|
|
376
450
|
/**
|
|
377
|
-
* Streaming variant of {@link Search}
|
|
378
|
-
*
|
|
379
|
-
* before fusion + reranking complete.
|
|
451
|
+
* Streaming variant of {@link Search}: the same pipeline, with a progress event as each provider
|
|
452
|
+
* returns, so a UI or agent can show progress before fusion, the permission pass and enrichment finish.
|
|
380
453
|
*
|
|
381
|
-
* **
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
* concurrent emission once we measure that the synthetic phase is the
|
|
389
|
-
* actual bottleneck.
|
|
454
|
+
* **Progress, not partial results.** A `provider` event carries the provider's name, its duration and
|
|
455
|
+
* `resultCount` — how many hits it returned, capped at `MaxResults` — and never the hits themselves
|
|
456
|
+
* (`results` is always empty). They arrive before the permission pass, so they include rows the caller's
|
|
457
|
+
* row filters would drop, external-index hits not yet verified against the entity they name, and content
|
|
458
|
+
* whose origin record the caller may not read. Results arrive only in `fused` and `final`, which carry
|
|
459
|
+
* exactly what {@link Search} returns. `resultCount` is counted before the permission and audience passes,
|
|
460
|
+
* like `SearchResult.SourceCounts`, so don't show it to a room.
|
|
390
461
|
*
|
|
391
|
-
* Cancellation: the consumer can stop iterating at any point — the
|
|
392
|
-
*
|
|
393
|
-
* discarded. AbortSignal-based mid-pipeline cancellation is a Phase 2C
|
|
394
|
-
* v2 concern.
|
|
462
|
+
* Cancellation: the consumer can stop iterating at any point — the underlying search runs to
|
|
463
|
+
* completion and its result is discarded. Mid-pipeline AbortSignal cancellation is not supported.
|
|
395
464
|
*
|
|
396
465
|
* Event ordering:
|
|
397
|
-
* 1.
|
|
466
|
+
* 1. One `provider` event per provider that ran, in the order they return (a provider that failed
|
|
467
|
+
* reports `resultCount: 0`)
|
|
398
468
|
* 2. Exactly one `fused` event
|
|
399
|
-
* 3.
|
|
400
|
-
* 4.
|
|
401
|
-
* 5. On error: a single `error` event in place of `final`.
|
|
469
|
+
* 3. Exactly one `final` event (`reranked` is part of the type but not emitted today)
|
|
470
|
+
* 4. On error: a single `error` event in place of `fused` and `final`.
|
|
402
471
|
*
|
|
403
472
|
* @example
|
|
404
473
|
* for await (const ev of SearchEngine.Instance.streamSearch(params, user)) {
|
|
405
474
|
* switch (ev.phase) {
|
|
406
|
-
* case 'provider': scratchpad.append(`${ev.providerName}: ${ev.
|
|
475
|
+
* case 'provider': scratchpad.append(`${ev.providerName}: ${ev.resultCount} hits`); break;
|
|
407
476
|
* case 'final': scratchpad.commit(ev.results); break;
|
|
408
477
|
* case 'error': scratchpad.fail(ev.error); break;
|
|
409
478
|
* }
|
|
@@ -450,12 +519,16 @@ export class SearchEngine extends BaseSingleton {
|
|
|
450
519
|
entity: 'Entity',
|
|
451
520
|
storage: 'Storage',
|
|
452
521
|
};
|
|
522
|
+
// A provider's hits arrive before any permission pass, so its event carries progress only: the name,
|
|
523
|
+
// the duration and a count. The hits themselves reach the caller in `fused`/`final`, after the
|
|
524
|
+
// permission pass (and, under an audience, after the audience pass).
|
|
453
525
|
const onProviderResolved = (ev) => {
|
|
454
526
|
const label = sourceTypeToLabel[ev.sourceType.toLowerCase()] ?? ev.sourceType;
|
|
455
527
|
push({
|
|
456
528
|
phase: 'provider',
|
|
457
529
|
providerName: label,
|
|
458
|
-
results:
|
|
530
|
+
results: [],
|
|
531
|
+
resultCount: ev.results.length,
|
|
459
532
|
durationMs: ev.durationMs,
|
|
460
533
|
});
|
|
461
534
|
};
|
|
@@ -598,9 +671,184 @@ export class SearchEngine extends BaseSingleton {
|
|
|
598
671
|
// into expansion queries. Two searches identical but for the active skill are NOT
|
|
599
672
|
// interchangeable, so they must not share a cache entry.
|
|
600
673
|
AISkillID: params.AISkillID ?? undefined,
|
|
674
|
+
// The audience narrows the result set, so a search the caller ran alone must never be
|
|
675
|
+
// served from the cache to a room, nor a room's result to the caller alone. Sorted so
|
|
676
|
+
// the same readers in any order share an entry. IDs only: within the TTL, a reader object
|
|
677
|
+
// with the same ID but different roles gets the cached verdict (see SearchParams.Audience).
|
|
678
|
+
AudienceReaderIDs: this.audienceReaderIDs(params.Audience, contextUser),
|
|
601
679
|
};
|
|
602
680
|
return `${userKey}|${trimmed}|${this.stableStringify(projection)}`;
|
|
603
681
|
}
|
|
682
|
+
/**
|
|
683
|
+
* Throw when `audience` is present but cannot be honoured. Called first in `searchInternal`, whose catch
|
|
684
|
+
* turns the throw into a `Success: false` result. A malformed reader is refused rather than skipped:
|
|
685
|
+
* skipping it would restrict nothing, and the room would see the caller's full reach.
|
|
686
|
+
*/
|
|
687
|
+
validateAudience(audience) {
|
|
688
|
+
if (audience === undefined)
|
|
689
|
+
return;
|
|
690
|
+
const problem = this.audienceProblem(audience);
|
|
691
|
+
if (problem)
|
|
692
|
+
throw new Error(`SearchEngine: invalid Audience — ${problem}`);
|
|
693
|
+
}
|
|
694
|
+
/** What is wrong with an audience, or `null` when it is well formed. Takes `unknown`: hosts assemble it at runtime. */
|
|
695
|
+
audienceProblem(audience) {
|
|
696
|
+
if (audience === null || typeof audience !== 'object') {
|
|
697
|
+
return `expected { Readers: UserInfo[] }, got ${this.describeValue(audience)}. Omit Audience for a search with no audience.`;
|
|
698
|
+
}
|
|
699
|
+
const readers = 'Readers' in audience ? audience.Readers : undefined;
|
|
700
|
+
if (!Array.isArray(readers)) {
|
|
701
|
+
return `Readers must be an array of hydrated UserInfo objects, got ${this.describeValue(readers)}.`;
|
|
702
|
+
}
|
|
703
|
+
const list = readers;
|
|
704
|
+
for (let i = 0; i < list.length; i++) {
|
|
705
|
+
const problem = this.audienceReaderProblem(list[i]);
|
|
706
|
+
if (problem)
|
|
707
|
+
return `Readers[${i}] ${problem}`;
|
|
708
|
+
}
|
|
709
|
+
return null;
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* What is wrong with one reader, or `null`. A reader needs a non-empty `ID` and a `UserRoles` array:
|
|
713
|
+
* `[]` is a reader with no roles (legitimate, reads nothing); a missing array means it was never hydrated.
|
|
714
|
+
*/
|
|
715
|
+
audienceReaderProblem(reader) {
|
|
716
|
+
if (reader === null || typeof reader !== 'object') {
|
|
717
|
+
return `is ${this.describeValue(reader)}, not a UserInfo — map every participant to a hydrated user before searching for them.`;
|
|
718
|
+
}
|
|
719
|
+
const id = 'ID' in reader ? reader.ID : undefined;
|
|
720
|
+
if (typeof id !== 'string' || id.trim() === '') {
|
|
721
|
+
return 'has no ID — a reader the host could not map to a user would restrict nothing, so the search is refused.';
|
|
722
|
+
}
|
|
723
|
+
const roles = 'UserRoles' in reader ? reader.UserRoles : undefined;
|
|
724
|
+
if (!Array.isArray(roles)) {
|
|
725
|
+
return `(${id}) has no UserRoles array — pass hydrated UserInfo (e.g. from UserCache); a reader with no roles is \`UserRoles: []\`.`;
|
|
726
|
+
}
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
/** `null`, `an array`, or the `typeof` name: validation messages name a bad value's kind rather than echo it. */
|
|
730
|
+
describeValue(value) {
|
|
731
|
+
if (value === null)
|
|
732
|
+
return 'null';
|
|
733
|
+
if (Array.isArray(value))
|
|
734
|
+
return 'an array';
|
|
735
|
+
return typeof value;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* The readers an audience actually adds: one per distinct ID (case-insensitive), the caller's own ID left
|
|
739
|
+
* out. Empty when the audience changes nothing. Expects an audience that passed `validateAudience`.
|
|
740
|
+
*/
|
|
741
|
+
distinctReaders(audience, contextUser) {
|
|
742
|
+
if (!audience)
|
|
743
|
+
return [];
|
|
744
|
+
const seen = new Set();
|
|
745
|
+
const callerID = contextUser.ID?.toLowerCase();
|
|
746
|
+
if (callerID)
|
|
747
|
+
seen.add(callerID);
|
|
748
|
+
const readers = [];
|
|
749
|
+
for (const reader of audience.Readers) {
|
|
750
|
+
const id = reader.ID.toLowerCase();
|
|
751
|
+
if (seen.has(id))
|
|
752
|
+
continue;
|
|
753
|
+
seen.add(id);
|
|
754
|
+
readers.push(reader);
|
|
755
|
+
}
|
|
756
|
+
return readers;
|
|
757
|
+
}
|
|
758
|
+
/** The distinct reader IDs, lower-cased and sorted, for the cache key. `undefined` when the audience adds no reader, so it keys like no audience. */
|
|
759
|
+
audienceReaderIDs(audience, contextUser) {
|
|
760
|
+
const ids = this.distinctReaders(audience, contextUser).map(r => r.ID.toLowerCase()).sort();
|
|
761
|
+
return ids.length > 0 ? ids : undefined;
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Keep only the results every reader in `params.Audience` may read, on top of the caller's own filter.
|
|
765
|
+
* Each reader gets the same safety net the caller did (`filterByPermissions`: entity read, row filters,
|
|
766
|
+
* ownership), so a shared conversation's results are the intersection of what every participant may see —
|
|
767
|
+
* the asker's reach is the ceiling, each other reader's reach lowers it. Readers are checked concurrently;
|
|
768
|
+
* a reader with the caller's own ID, or listed twice, is checked once. Expects a validated audience
|
|
769
|
+
* (`searchInternal` validates it before doing any work).
|
|
770
|
+
*
|
|
771
|
+
* The intersection is then projected for every reader in turn, so a field any one of them may not read is
|
|
772
|
+
* removed from the shared results' metadata, snippets and titles.
|
|
773
|
+
*
|
|
774
|
+
* Two things the pass cannot do, both failing closed:
|
|
775
|
+
* - **Storage hits are refused under an audience.** Their permission model is the storage account's;
|
|
776
|
+
* `filterByPermissions` re-checks a `storage-file` hit's account for the user it is given, but this pass
|
|
777
|
+
* does not yet combine those per-reader answers for storage, so a storage hit is not shown to the room.
|
|
778
|
+
* - **A reader with no roles (`UserRoles: []`) reads nothing.** Permissions and row filters are
|
|
779
|
+
* evaluated from `UserInfo.UserRoles`, so such a reader empties the result. A reader with no
|
|
780
|
+
* `UserRoles` array at all never gets here: validation refuses it.
|
|
781
|
+
*
|
|
782
|
+
* **Identity contract.** A result survives when every reader's `filterByPermissions` returns it. Survivors
|
|
783
|
+
* are matched to the input by `EntityName|RecordID` (the record the result names), falling back to object
|
|
784
|
+
* identity for a result that names no record. An override of `filterByPermissions` may therefore return
|
|
785
|
+
* copies, but must not rewrite `EntityName` or `RecordID`.
|
|
786
|
+
*
|
|
787
|
+
* Protected so a host can change how an audience combines (a host that materializes a shared reach in one
|
|
788
|
+
* query can replace the per-reader pass). It receives the whole `params`, so an override can see the anchor
|
|
789
|
+
* (`SearchContext`) and the scopes. The default is the intersection.
|
|
790
|
+
*/
|
|
791
|
+
async FilterForAudience(results, params, contextUser) {
|
|
792
|
+
const readers = this.distinctReaders(params.Audience, contextUser);
|
|
793
|
+
if (readers.length === 0 || results.length === 0)
|
|
794
|
+
return results;
|
|
795
|
+
const checkable = results.filter(r => r.ResultType !== 'storage-file');
|
|
796
|
+
if (checkable.length < results.length) {
|
|
797
|
+
LogStatus(`SearchEngine: ${results.length - checkable.length} storage result(s) dropped under an audience — ` +
|
|
798
|
+
'storage hits are re-checked for the caller only; per-reader storage checks are a follow-up.');
|
|
799
|
+
}
|
|
800
|
+
const survivors = await Promise.all(readers.map(reader => this.filterByPermissions(checkable, reader)));
|
|
801
|
+
this.logAudienceNarrowing(readers, survivors, checkable.length);
|
|
802
|
+
const keptByEveryReader = survivors.map(list => new Set(list.map(r => this.audienceIdentity(r))));
|
|
803
|
+
const kept = checkable.filter(r => {
|
|
804
|
+
const identity = this.audienceIdentity(r);
|
|
805
|
+
return keptByEveryReader.every(set => set.has(identity));
|
|
806
|
+
});
|
|
807
|
+
// Every reader sees the same results, so each one's denied fields come out of all of them.
|
|
808
|
+
return readers.reduce((projected, reader) => this.projectResultsForReader(projected, reader), kept);
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* `results` with every field `reader` may not read projected out of each result's metadata, snippet and
|
|
812
|
+
* title, entity by entity (see {@link projectEntityResultsForReader}). A result naming an entity this
|
|
813
|
+
* provider does not know is left as it is: the permission pass never admits one.
|
|
814
|
+
*/
|
|
815
|
+
projectResultsForReader(results, reader) {
|
|
816
|
+
const entities = new Map();
|
|
817
|
+
return results.map(item => {
|
|
818
|
+
if (!entities.has(item.EntityName)) {
|
|
819
|
+
entities.set(item.EntityName, this.entityOrNull(item.EntityName));
|
|
820
|
+
}
|
|
821
|
+
const entity = entities.get(item.EntityName);
|
|
822
|
+
return entity ? this.projectEntityResultsForReader(entity, [item], reader)[0] : item;
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
/** `EntityByName`, with an unknown name (which it throws on) as null. */
|
|
826
|
+
entityOrNull(entityName) {
|
|
827
|
+
try {
|
|
828
|
+
return this.ProviderToUse.EntityByName(entityName) ?? null;
|
|
829
|
+
}
|
|
830
|
+
catch {
|
|
831
|
+
return null;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
/** `EntityName|RecordID` for a result that names a record, else the object itself — see `FilterForAudience`'s identity contract. */
|
|
835
|
+
audienceIdentity(result) {
|
|
836
|
+
return result.EntityName && result.RecordID ? `${result.EntityName}|${result.RecordID}` : result;
|
|
837
|
+
}
|
|
838
|
+
/** Log, per reader, why the shared result set shrank: a reader with no roles, or results a reader cannot read. */
|
|
839
|
+
logAudienceNarrowing(readers, survivors, checkedCount) {
|
|
840
|
+
readers.forEach((reader, i) => {
|
|
841
|
+
if (reader.UserRoles.length === 0) {
|
|
842
|
+
LogStatus(`SearchEngine: Audience reader ${reader.ID} has no roles (UserRoles: []) — permissions resolve ` +
|
|
843
|
+
'from roles, so expect it to read nothing and the shared result set to be empty.');
|
|
844
|
+
}
|
|
845
|
+
const dropped = checkedCount - survivors[i].length;
|
|
846
|
+
if (dropped > 0) {
|
|
847
|
+
LogStatus(`SearchEngine: Audience reader ${reader.ID} cannot read ${dropped} result(s) the caller can — ` +
|
|
848
|
+
'removed from the shared result set.');
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
}
|
|
604
852
|
/** Insert into the LRU cache, evicting oldest entries when over capacity. */
|
|
605
853
|
cachePut(key, result) {
|
|
606
854
|
if (this._cache.size >= SearchEngine.CACHE_MAX_ENTRIES) {
|
|
@@ -661,7 +909,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
661
909
|
*
|
|
662
910
|
* Unlike a real search this never throws for a scope-level problem; a scope that would fail
|
|
663
911
|
* closed comes back with `Reachable: false` and the reason, since "it would have failed"
|
|
664
|
-
* is precisely the finding the caller asked for.
|
|
912
|
+
* is precisely the finding the caller asked for. A scope that cannot be resolved (inactive,
|
|
913
|
+
* expired, or missing) refuses the whole search, so when one is named every scope comes back
|
|
914
|
+
* unreachable, each saying why.
|
|
665
915
|
*
|
|
666
916
|
* @param input scopes to explain plus the hypothetical caller context and principals
|
|
667
917
|
* @param contextUser the user to evaluate entitlement for
|
|
@@ -672,7 +922,23 @@ export class SearchEngine extends BaseSingleton {
|
|
|
672
922
|
for (const scopeID of input.ScopeIDs) {
|
|
673
923
|
explanations.push(await this.explainOneScope(scopeID, input, contextUser));
|
|
674
924
|
}
|
|
675
|
-
return explanations;
|
|
925
|
+
return this.markRefusedTogether(explanations, this.resolveScopes(input.ScopeIDs).Unresolved);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* A search naming a scope it cannot resolve is refused outright (see `refuseUnresolvableScopes`), so a dry
|
|
929
|
+
* run over the same IDs reaches nothing through ANY of them — including a scope that is reachable on its
|
|
930
|
+
* own. Each such scope is marked unreachable with the reason; the unresolvable ones already explain
|
|
931
|
+
* themselves.
|
|
932
|
+
*/
|
|
933
|
+
markRefusedTogether(explanations, unresolved) {
|
|
934
|
+
if (unresolved.length === 0)
|
|
935
|
+
return explanations;
|
|
936
|
+
const note = `searched together with ${unresolved.join(', ')}, which cannot be resolved, the search is refused — `
|
|
937
|
+
+ 'this scope reaches nothing in it (on its own it would be searched as explained above)';
|
|
938
|
+
const unresolvedIDs = new UUIDSet(unresolved);
|
|
939
|
+
return explanations.map(e => unresolvedIDs.Has(e.ScopeID)
|
|
940
|
+
? e
|
|
941
|
+
: { ...e, Reachable: false, Diagnostics: [...e.Diagnostics, note] });
|
|
676
942
|
}
|
|
677
943
|
/**
|
|
678
944
|
* Build the principal set a dimension's expansion query may bind.
|
|
@@ -691,8 +957,10 @@ export class SearchEngine extends BaseSingleton {
|
|
|
691
957
|
}
|
|
692
958
|
/** Explain a single scope. Never throws — a failure to resolve IS the explanation. */
|
|
693
959
|
async explainOneScope(scopeID, input, contextUser) {
|
|
694
|
-
|
|
695
|
-
|
|
960
|
+
// Active first, as the search resolves it: `GetScopeBundle` alone finds a scope of any status, so an
|
|
961
|
+
// inactive or expired scope used to be explained as searchable while the search refused it.
|
|
962
|
+
const scope = this.Base.GetActiveScopeByID(scopeID);
|
|
963
|
+
const bundle = scope ? this.Base.GetScopeBundle(scopeID) : undefined;
|
|
696
964
|
if (!bundle || !scope) {
|
|
697
965
|
return this.buildUnresolvableExplanation(scopeID, input, contextUser);
|
|
698
966
|
}
|
|
@@ -726,7 +994,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
726
994
|
// principal-side — the principal IS the reason — yet their ids were still bound into the
|
|
727
995
|
// expansion query. This is the same set the Scoped Search action classifies as
|
|
728
996
|
// ACCESS_DENIED rather than PERMISSION_DENIED, for the same reason.
|
|
729
|
-
// A TOTAL MAP, NOT A LIST: `
|
|
997
|
+
// A TOTAL MAP, NOT A LIST: `EntitlementSource` is a closed union, so writing
|
|
730
998
|
// this as `Record<Source, boolean>` makes the compiler demand an answer for any source
|
|
731
999
|
// added later. As a `string[]` a new principal-side source would silently default to
|
|
732
1000
|
// "bind it" — which is the exact defect this block exists to fix, re-openable by an
|
|
@@ -746,6 +1014,8 @@ export class SearchEngine extends BaseSingleton {
|
|
|
746
1014
|
DirectGrant: false,
|
|
747
1015
|
RoleGrant: false,
|
|
748
1016
|
NoGrant: false,
|
|
1017
|
+
// Scope-side, and unreachable here: an unresolvable scope is explained before entitlement.
|
|
1018
|
+
ScopeUnresolvable: false,
|
|
749
1019
|
};
|
|
750
1020
|
const principalsJudged = entitlement.Allowed || !IS_PRINCIPAL_SIDE[entitlement.Source];
|
|
751
1021
|
if (!principalsJudged && (input.AIAgentID || input.AISkillID)) {
|
|
@@ -773,16 +1043,12 @@ export class SearchEngine extends BaseSingleton {
|
|
|
773
1043
|
const lanes = dimensionFailure
|
|
774
1044
|
? this.buildAllLanesSkipped(bundle, `dimension resolution failed: ${dimensionFailure}`)
|
|
775
1045
|
: this.explainLanes(bundle, effectiveContext);
|
|
776
|
-
//
|
|
777
|
-
//
|
|
778
|
-
//
|
|
779
|
-
//
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
if (!hasLanes) {
|
|
783
|
-
diagnostics.push(UNBOUNDED_SCOPE_DIAGNOSTIC);
|
|
784
|
-
}
|
|
785
|
-
const canRetrieve = hasLanes ? lanes.some((l) => l.Status === 'Active') : true;
|
|
1046
|
+
// What the scope's rows let it reach — which providers run (listed, configured, available, and reading
|
|
1047
|
+
// a lane kind the scope configures) over which lanes — by the same judgement the search path makes, for
|
|
1048
|
+
// a full (non-preview) search. A lane skipped here is one the real search would refuse on, so a skipped
|
|
1049
|
+
// lane makes the scope unreachable rather than "reachable through the others".
|
|
1050
|
+
const bound = this.judgeScopeBound(bundle, lanes, false);
|
|
1051
|
+
diagnostics.push(...bound.Diagnostics);
|
|
786
1052
|
return {
|
|
787
1053
|
ScopeID: scope.ID,
|
|
788
1054
|
ScopeName: scope.Name,
|
|
@@ -790,11 +1056,75 @@ export class SearchEngine extends BaseSingleton {
|
|
|
790
1056
|
Dimensions: dimensions,
|
|
791
1057
|
Lanes: lanes,
|
|
792
1058
|
Diagnostics: diagnostics,
|
|
793
|
-
Reachable: entitlement.Allowed &&
|
|
794
|
-
Unbounded:
|
|
1059
|
+
Reachable: entitlement.Allowed && bound.CanRetrieve && !dimensionFailure,
|
|
1060
|
+
Unbounded: bound.Unbounded,
|
|
795
1061
|
ResolvedContext: effectiveContext,
|
|
796
1062
|
};
|
|
797
1063
|
}
|
|
1064
|
+
/**
|
|
1065
|
+
* What a scope's configuration lets it reach. One judgement, used by the dry run and the search path — and
|
|
1066
|
+
* the search path calls exactly the `Providers` it returns, so the two cannot disagree about who runs.
|
|
1067
|
+
*
|
|
1068
|
+
* A GLOBAL scope runs unconstrained (the search path never builds constraints for it), so with no
|
|
1069
|
+
* lanes it is unbounded. A NON-global scope is bounded by its rows: it runs only the providers its enabled
|
|
1070
|
+
* rows name that are configured and available (and support preview, for a preview search), and of those
|
|
1071
|
+
* only the ones that read a lane kind the scope has an active lane of (`BaseSearchProvider.ConsumesLaneKinds`).
|
|
1072
|
+
* With none of those, it reaches nothing — an empty configuration never means "everything". A skipped lane
|
|
1073
|
+
* (only a dry run has one) is a problem the real search refuses on, so it makes the scope unreachable too.
|
|
1074
|
+
*/
|
|
1075
|
+
judgeScopeBound(bundle, lanes, isPreview) {
|
|
1076
|
+
if (bundle.Scope.IsGlobal)
|
|
1077
|
+
return this.judgeGlobalScopeBound(lanes, isPreview);
|
|
1078
|
+
const runnable = this.runnableScopeProviders(bundle, isPreview);
|
|
1079
|
+
const serving = this.providersWithAnActiveLane(runnable, lanes);
|
|
1080
|
+
const skipped = lanes.filter((l) => l.Status === 'Skipped');
|
|
1081
|
+
const diagnostics = [];
|
|
1082
|
+
if (bundle.Providers.length === 0)
|
|
1083
|
+
diagnostics.push(NO_PROVIDER_ROWS_DIAGNOSTIC);
|
|
1084
|
+
else if (runnable.length === 0)
|
|
1085
|
+
diagnostics.push(noRunnableProviderDiagnostic(isPreview));
|
|
1086
|
+
if (lanes.length === 0)
|
|
1087
|
+
diagnostics.push(NO_LANES_DIAGNOSTIC);
|
|
1088
|
+
if (skipped.length > 0)
|
|
1089
|
+
diagnostics.push(refusedLanesDiagnostic(skipped));
|
|
1090
|
+
const hasActiveLane = lanes.some((l) => l.Status === 'Active');
|
|
1091
|
+
if (runnable.length > 0 && hasActiveLane && serving.length === 0)
|
|
1092
|
+
diagnostics.push(noProviderReadsALaneDiagnostic(runnable, lanes));
|
|
1093
|
+
const canRetrieve = serving.length > 0 && skipped.length === 0;
|
|
1094
|
+
return { CanRetrieve: canRetrieve, Unbounded: false, Diagnostics: diagnostics, Providers: canRetrieve ? serving : [] };
|
|
1095
|
+
}
|
|
1096
|
+
/** {@link judgeScopeBound} for a global scope, which runs every available provider unconstrained. */
|
|
1097
|
+
judgeGlobalScopeBound(lanes, isPreview) {
|
|
1098
|
+
const hasLanes = lanes.length > 0;
|
|
1099
|
+
return {
|
|
1100
|
+
CanRetrieve: hasLanes ? lanes.some((l) => l.Status === 'Active') : true,
|
|
1101
|
+
Unbounded: !hasLanes,
|
|
1102
|
+
Diagnostics: hasLanes ? [] : [UNBOUNDED_SCOPE_DIAGNOSTIC],
|
|
1103
|
+
Providers: this.availableProviders(isPreview),
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
/** The configured entries a search may call: available now, and preview-capable for a preview search. */
|
|
1107
|
+
availableProviders(isPreview) {
|
|
1108
|
+
return this._providerEntries.filter(entry => entry.Provider.IsAvailable() && (!isPreview || entry.SupportsPreview));
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* The available entries a NON-global scope's enabled provider rows name. A non-global scope runs ONLY the
|
|
1112
|
+
* providers it lists: no enabled row means no provider, never every provider (disabling a scope's last row
|
|
1113
|
+
* used to widen it to all of them).
|
|
1114
|
+
*/
|
|
1115
|
+
runnableScopeProviders(bundle, isPreview) {
|
|
1116
|
+
const listed = new Set(bundle.Providers.map(p => NormalizeUUID(p.SearchProviderID)));
|
|
1117
|
+
return this.availableProviders(isPreview).filter(entry => listed.has(NormalizeUUID(entry.ID)));
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Of `entries`, the ones with at least one ACTIVE lane of a kind they read (`ConsumesLaneKinds`). A provider
|
|
1121
|
+
* whose lane kinds are all empty in the scope is never called: it could only search nothing, or — written with
|
|
1122
|
+
* the old `?.length` pattern — fall back to its unscoped default.
|
|
1123
|
+
*/
|
|
1124
|
+
providersWithAnActiveLane(entries, lanes) {
|
|
1125
|
+
const activeKinds = new Set(lanes.filter((l) => l.Status === 'Active').map((l) => l.Kind));
|
|
1126
|
+
return entries.filter(entry => entry.Provider.ConsumesLaneKinds.some(kind => activeKinds.has(kind)));
|
|
1127
|
+
}
|
|
798
1128
|
/** Resolve entitlement for the dry run, including the skill and tenant principals.
|
|
799
1129
|
* `protected`, like {@link principalsFrom}, so a test can drive it without weak-typed casts.
|
|
800
1130
|
*/
|
|
@@ -931,10 +1261,11 @@ export class SearchEngine extends BaseSingleton {
|
|
|
931
1261
|
Kind: 'StorageAccount',
|
|
932
1262
|
Target: row.FileStorageAccountID,
|
|
933
1263
|
LaneID: row.ID,
|
|
934
|
-
// FolderPath
|
|
935
|
-
//
|
|
936
|
-
Status: 'Active',
|
|
1264
|
+
// FolderPath restricts the lane to one folder, so a path that rendered empty, with an
|
|
1265
|
+
// empty segment, or with traversal makes the lane unusable — as buildScopeConstraints rules.
|
|
1266
|
+
Status: problems.has(row.ID) ? 'Skipped' : 'Active',
|
|
937
1267
|
RenderedFilter: rendered?.FolderPath ?? null,
|
|
1268
|
+
Reason: problems.get(row.ID),
|
|
938
1269
|
});
|
|
939
1270
|
}
|
|
940
1271
|
return lanes;
|
|
@@ -988,11 +1319,13 @@ export class SearchEngine extends BaseSingleton {
|
|
|
988
1319
|
buildUnresolvableExplanation(scopeID, input, contextUser) {
|
|
989
1320
|
return {
|
|
990
1321
|
ScopeID: scopeID,
|
|
991
|
-
|
|
1322
|
+
// An inactive or expired scope still has a row, and its name is what an admin will recognise.
|
|
1323
|
+
ScopeName: this.Base.GetScopeByID(scopeID)?.Name ?? '(not found)',
|
|
992
1324
|
Entitlement: {
|
|
993
1325
|
Allowed: false,
|
|
994
1326
|
Level: 'None',
|
|
995
|
-
|
|
1327
|
+
// Not 'NoGrant': nothing about the caller's grants was judged — the scope's status refused it.
|
|
1328
|
+
Source: 'ScopeUnresolvable',
|
|
996
1329
|
Reason: 'the scope is inactive, expired, or does not exist, so no search can use it',
|
|
997
1330
|
Principals: {
|
|
998
1331
|
UserID: contextUser.ID ?? null,
|
|
@@ -1003,7 +1336,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1003
1336
|
},
|
|
1004
1337
|
Dimensions: [],
|
|
1005
1338
|
Lanes: [],
|
|
1006
|
-
Diagnostics: [`scope "${scopeID}" is not an active scope`],
|
|
1339
|
+
Diagnostics: [`scope "${scopeID}" is not an active scope — a search naming it is refused, never widened to a global search`],
|
|
1007
1340
|
Reachable: false,
|
|
1008
1341
|
// Not "known to be bounded" — the scope could not be loaded, so nothing about its
|
|
1009
1342
|
// configuration was observed. It is unreachable either way.
|
|
@@ -1031,24 +1364,56 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1031
1364
|
// Scope resolution
|
|
1032
1365
|
// ────────────────────────────────────────────────────────────────
|
|
1033
1366
|
/**
|
|
1034
|
-
* Load `ScopeBundle`
|
|
1035
|
-
*
|
|
1367
|
+
* Load the `ScopeBundle` of each requested scope ID that names a scope active right now, and collect the IDs
|
|
1368
|
+
* that do not (inactive, expired, or missing). A search refuses when any ID is unresolved
|
|
1369
|
+
* ({@link refuseUnresolvableScopes}); `ExplainScope` reports the same. No IDs → no bundles, which the
|
|
1370
|
+
* search treats as Global.
|
|
1036
1371
|
*/
|
|
1037
1372
|
resolveScopes(scopeIDs) {
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
for (const id of scopeIDs) {
|
|
1042
|
-
const scope = this.Base.GetActiveScopeByID(id);
|
|
1043
|
-
if (!scope) {
|
|
1044
|
-
LogStatus(`SearchEngine: Requested scope "${id}" is not active or does not exist — skipping.`);
|
|
1045
|
-
continue;
|
|
1046
|
-
}
|
|
1047
|
-
const bundle = this.Base.GetScopeBundle(id);
|
|
1373
|
+
const resolution = { Bundles: [], Unresolved: [] };
|
|
1374
|
+
for (const id of scopeIDs ?? []) {
|
|
1375
|
+
const bundle = this.Base.GetActiveScopeByID(id) ? this.Base.GetScopeBundle(id) : undefined;
|
|
1048
1376
|
if (bundle)
|
|
1049
|
-
|
|
1377
|
+
resolution.Bundles.push(bundle);
|
|
1378
|
+
else
|
|
1379
|
+
resolution.Unresolved.push(id);
|
|
1050
1380
|
}
|
|
1051
|
-
return
|
|
1381
|
+
return resolution;
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Refuse a search that named a scope the engine cannot resolve (inactive, expired, or missing): an error
|
|
1385
|
+
* result and a `Failure` row in `MJ: Search Execution Logs`, never a wider search.
|
|
1386
|
+
*
|
|
1387
|
+
* Before, an unresolvable scope was skipped, and a search whose scopes were all skipped ran UNSCOPED —
|
|
1388
|
+
* every provider, every entity, no scope filter — because no resolved scope reads as Global. Refused when
|
|
1389
|
+
* ANY named scope fails, not only when all do: dropping one of several scopes silently changes what the
|
|
1390
|
+
* caller asked for, and nothing in the results would tell them. An error result is how the engine already
|
|
1391
|
+
* reports a scope it refuses (a `ScopeDimensionError`, a restricting filter that did not render).
|
|
1392
|
+
*/
|
|
1393
|
+
refuseUnresolvableScopes(unresolved, params, contextUser, startTime) {
|
|
1394
|
+
const named = `${unresolved.length === 1 ? 'scope' : 'scopes'} ${unresolved.map(id => `"${id}"`).join(', ')}`;
|
|
1395
|
+
const message = `SearchEngine: search refused — ${named} could not be resolved (inactive, expired, or not found). ` +
|
|
1396
|
+
'A search naming a scope it cannot resolve is refused, never run without that scope.';
|
|
1397
|
+
LogError(message);
|
|
1398
|
+
this.logSearchExecution({
|
|
1399
|
+
Status: 'Failure',
|
|
1400
|
+
FailureReason: message,
|
|
1401
|
+
Query: params.Query,
|
|
1402
|
+
// The log row's SearchScopeID is a foreign key, so it names a scope row that exists, or none — and it
|
|
1403
|
+
// must name a scope that was REFUSED: the first unresolved scope that has a row (inactive or expired),
|
|
1404
|
+
// never a valid scope searched beside a missing one, which would attribute the refusal to it.
|
|
1405
|
+
ScopeIDs: unresolved.filter(id => this.Base.GetScopeByID(id) !== undefined).slice(0, 1),
|
|
1406
|
+
StartTime: startTime,
|
|
1407
|
+
ResultCount: 0,
|
|
1408
|
+
RerankerName: null,
|
|
1409
|
+
RerankerCostCents: null,
|
|
1410
|
+
SourceCounts: undefined,
|
|
1411
|
+
ContextUser: contextUser,
|
|
1412
|
+
AIAgentID: params.AIAgentID ?? null,
|
|
1413
|
+
AISkillID: params.AISkillID ?? null,
|
|
1414
|
+
PrimaryScopeRecordID: params.SearchContext?.PrimaryScopeRecordID ?? null,
|
|
1415
|
+
});
|
|
1416
|
+
return this.buildErrorResult(message, startTime);
|
|
1052
1417
|
}
|
|
1053
1418
|
/**
|
|
1054
1419
|
* Execute all scoped providers for a single scope bundle and return per-scope fused results.
|
|
@@ -1086,46 +1451,27 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1086
1451
|
// than re-rendering every template a second time. Reaching this line means every lane
|
|
1087
1452
|
// guard passed (buildScopeConstraints throws otherwise), so the problem map is empty
|
|
1088
1453
|
// and every lane is Active.
|
|
1089
|
-
const
|
|
1090
|
-
|
|
1091
|
-
|
|
1454
|
+
const lanes = this.buildLaneExplanations(bundle, constraints, new Map());
|
|
1455
|
+
// The same judgement the dry run makes, so both produce the same verdict and the same prose —
|
|
1456
|
+
// an auditor reading a log row should not have to know which path wrote it. Its `Providers` are the ones
|
|
1457
|
+
// this search calls: listed by an enabled row, configured, available (preview-capable for a preview), and
|
|
1458
|
+
// reading a lane kind this scope configures.
|
|
1459
|
+
const bound = this.judgeScopeBound(bundle, lanes, isPreview);
|
|
1092
1460
|
const decision = {
|
|
1093
1461
|
ScopeID: scope.ID,
|
|
1094
1462
|
ScopeName: scope.Name,
|
|
1095
1463
|
Entitlement: null,
|
|
1096
1464
|
Dimensions: dimensionResult.Provenance,
|
|
1097
|
-
Lanes:
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
Diagnostics: unbounded
|
|
1102
|
-
? [...dimensionResult.Diagnostics, UNBOUNDED_SCOPE_DIAGNOSTIC]
|
|
1103
|
-
: dimensionResult.Diagnostics,
|
|
1104
|
-
Reachable: true,
|
|
1105
|
-
Unbounded: unbounded,
|
|
1465
|
+
Lanes: lanes,
|
|
1466
|
+
Diagnostics: [...dimensionResult.Diagnostics, ...bound.Diagnostics],
|
|
1467
|
+
Reachable: bound.CanRetrieve,
|
|
1468
|
+
Unbounded: bound.Unbounded,
|
|
1106
1469
|
ResolvedContext: effectiveContext,
|
|
1107
1470
|
};
|
|
1108
|
-
|
|
1109
|
-
const scopeProviderIDs = new Set(bundle.Providers.map(p => NormalizeUUID(p.SearchProviderID)));
|
|
1110
|
-
const allowAllProviders = scopeProviderIDs.size === 0; // empty = scope is IsGlobal or all-inclusive
|
|
1111
|
-
const applicableProviders = this._providerEntries.filter(entry => {
|
|
1112
|
-
if (!entry.Provider.IsAvailable())
|
|
1113
|
-
return false;
|
|
1114
|
-
if (isPreview && !entry.SupportsPreview)
|
|
1115
|
-
return false;
|
|
1116
|
-
if (allowAllProviders)
|
|
1117
|
-
return true;
|
|
1118
|
-
return scopeProviderIDs.has(NormalizeUUID(entry.ID));
|
|
1119
|
-
});
|
|
1471
|
+
const applicableProviders = bound.Providers;
|
|
1120
1472
|
if (applicableProviders.length === 0) {
|
|
1121
|
-
LogStatus(`SearchEngine: Scope "${scope.Name}"
|
|
1122
|
-
return {
|
|
1123
|
-
scopeID: scope.ID,
|
|
1124
|
-
fused: [],
|
|
1125
|
-
sourceCounts: { Vector: 0, FullText: 0, Entity: 0, Storage: 0 },
|
|
1126
|
-
decision: { ...decision, Reachable: false,
|
|
1127
|
-
Diagnostics: [...decision.Diagnostics, 'no applicable providers for this scope'] },
|
|
1128
|
-
};
|
|
1473
|
+
LogStatus(`SearchEngine: Scope "${scope.Name}" runs no provider — skipping. ${bound.Diagnostics.join(' ')}`);
|
|
1474
|
+
return { scopeID: scope.ID, fused: [], sourceCounts: { Vector: 0, FullText: 0, Entity: 0, Storage: 0 }, decision };
|
|
1129
1475
|
}
|
|
1130
1476
|
// Resolve per-provider `SearchScopeProvider.MaxResultsOverride` if present
|
|
1131
1477
|
const promises = applicableProviders.map(async (entry) => {
|
|
@@ -1182,7 +1528,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1182
1528
|
return { Source: entry.Provider.SourceType, Results: [] };
|
|
1183
1529
|
}
|
|
1184
1530
|
});
|
|
1185
|
-
|
|
1531
|
+
// A lane's ExtraFilter bounds its entity for EVERY provider, not only the entity lane that applies it in SQL —
|
|
1532
|
+
// including a content-item hit promoted to its origin record, which is promoted here, per scope, for that reason.
|
|
1533
|
+
const labeled = await this.boundScopeHits(await Promise.all(promises), constraints, contextUser, scope.Name);
|
|
1186
1534
|
const sourceCounts = this.countSources(labeled);
|
|
1187
1535
|
// Per-scope fusion with weight resolution:
|
|
1188
1536
|
// agent fusion weights > scope.ScopeConfig.fusionWeights > engine defaults
|
|
@@ -1193,6 +1541,148 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1193
1541
|
const fused = this._fusion.Fuse(labeled, topK, fusionWeights);
|
|
1194
1542
|
return { scopeID: scope.ID, fused, sourceCounts, decision };
|
|
1195
1543
|
}
|
|
1544
|
+
// ────────────────────────────────────────────────────────────────
|
|
1545
|
+
// Lane ExtraFilter: one bound per entity, for every provider
|
|
1546
|
+
// ────────────────────────────────────────────────────────────────
|
|
1547
|
+
/**
|
|
1548
|
+
* Hold one scope's hits to its lane bounds, before fusion, in three steps:
|
|
1549
|
+
* 1. every hit, against the lane `ExtraFilter` of the entity it names ({@link enforceLaneExtraFilters});
|
|
1550
|
+
* 2. content-item promotion: a `MJ: Content Items` hit derived from an entity record becomes that record,
|
|
1551
|
+
* marked `PromotedFromContentItemID` (`SearchEnricher.ExcludeEntitySourcedContentItems`);
|
|
1552
|
+
* 3. every PROMOTED hit, against the lane `ExtraFilter` of the origin entity it now names.
|
|
1553
|
+
*
|
|
1554
|
+
* Step 1 holds a content-item hit to a Content Items lane; step 3 holds the record it became to that
|
|
1555
|
+
* record's lane. Promotion used to run once, after cross-scope fusion, so a promoted hit met no lane bound:
|
|
1556
|
+
* a vector hit on a content item became a row of a bounded entity from outside the bound. `searchInternal`
|
|
1557
|
+
* promotes only unconstrained results (which have no lane bounds), so nothing is promoted twice.
|
|
1558
|
+
*/
|
|
1559
|
+
async boundScopeHits(lists, constraints, contextUser, scopeName) {
|
|
1560
|
+
const bounded = await this.enforceLaneExtraFilters(lists, constraints, contextUser, scopeName, 'all');
|
|
1561
|
+
const promoted = await this.promoteContentItems(bounded, contextUser);
|
|
1562
|
+
return this.enforceLaneExtraFilters(promoted, constraints, contextUser, scopeName, 'promoted');
|
|
1563
|
+
}
|
|
1564
|
+
/** Content-item promotion, per provider list. A list with no `MJ: Content Items` hit comes back unchanged, unread. */
|
|
1565
|
+
async promoteContentItems(lists, contextUser) {
|
|
1566
|
+
this._enricher.Provider = this.ProviderToUse;
|
|
1567
|
+
return Promise.all(lists.map(async (list) => ({
|
|
1568
|
+
...list,
|
|
1569
|
+
Results: await this._enricher.ExcludeEntitySourcedContentItems(list.Results, contextUser),
|
|
1570
|
+
})));
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Enforce each entity lane's rendered `ExtraFilter` on the hits of every OTHER provider.
|
|
1574
|
+
*
|
|
1575
|
+
* The entity lane applies its ExtraFilter in SQL. The full-text and tag lanes take only the lanes'
|
|
1576
|
+
* entity NAMES, and the vector and 3rd-party lanes key off their own index rows — so a scope that bounds
|
|
1577
|
+
* an entity with an ExtraFilter still returned rows outside it through every lane but one. Here a hit for
|
|
1578
|
+
* an entity with a lane ExtraFilter in this scope is kept only when its record satisfies that filter,
|
|
1579
|
+
* read as the user: `PK IN (...) AND (<ExtraFilter>)`, one RunView per filtered entity per scope (the
|
|
1580
|
+
* permission pass's readability check, with the lane's filter as the clause). The filter is the exact
|
|
1581
|
+
* string the entity lane runs: same template, same context, same escaping.
|
|
1582
|
+
*
|
|
1583
|
+
* Exemption follows the provider the ENGINE stamped on the hit (`ProviderId`, through
|
|
1584
|
+
* {@link ProviderForResult}): only a provider declaring `BaseSearchProvider.AppliesLaneExtraFilter` (the entity
|
|
1585
|
+
* provider) applied the filter already. `SourceType` is provider-declared and proves nothing, and a promoted
|
|
1586
|
+
* content-item hit is never exempt (the filter it met, if any, was the Content Items lane's). Storage files are
|
|
1587
|
+
* not entity records and pass. `pass` is `'promoted'` to check only promoted hits ({@link boundScopeHits}).
|
|
1588
|
+
* Fails closed: a failed read drops that entity's hits from the other providers.
|
|
1589
|
+
*/
|
|
1590
|
+
async enforceLaneExtraFilters(lists, constraints, contextUser, scopeName, pass) {
|
|
1591
|
+
const bounds = this.laneEntityBounds(constraints.Entities);
|
|
1592
|
+
if (bounds.size === 0)
|
|
1593
|
+
return lists;
|
|
1594
|
+
const boundOf = (item) => this.laneBoundFor(item, bounds, pass);
|
|
1595
|
+
const candidates = new Map();
|
|
1596
|
+
for (const item of lists.flatMap(l => l.Results)) {
|
|
1597
|
+
const bound = boundOf(item);
|
|
1598
|
+
if (bound)
|
|
1599
|
+
candidates.set(bound, [...(candidates.get(bound) ?? []), item]);
|
|
1600
|
+
}
|
|
1601
|
+
if (candidates.size === 0)
|
|
1602
|
+
return lists;
|
|
1603
|
+
const kept = await this.hitsInsideLaneFilters(candidates, contextUser, scopeName);
|
|
1604
|
+
const bounded = lists.map(list => ({ ...list, Results: list.Results.filter(r => !boundOf(r) || kept.has(r)) }));
|
|
1605
|
+
const removed = lists.reduce((n, l) => n + l.Results.length, 0) - bounded.reduce((n, l) => n + l.Results.length, 0);
|
|
1606
|
+
if (removed > 0) {
|
|
1607
|
+
LogStatus(`SearchEngine: scope "${scopeName}" — lane ExtraFilters removed ${removed} hit(s) ` +
|
|
1608
|
+
'that other providers returned outside the entity lane\'s bound.');
|
|
1609
|
+
}
|
|
1610
|
+
return bounded;
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* Each entity's lane bound, keyed by {@link laneEntityKey}. Several lanes on one entity are a union (the
|
|
1614
|
+
* entity lane searches each), so their filters are ORed; an entity with any UNFILTERED lane is unbounded
|
|
1615
|
+
* for this scope and gets no entry. A lane whose entity could not be named is skipped.
|
|
1616
|
+
*/
|
|
1617
|
+
laneEntityBounds(lanes) {
|
|
1618
|
+
const filters = new Map();
|
|
1619
|
+
for (const lane of lanes ?? []) {
|
|
1620
|
+
const key = this.laneEntityKey(lane.EntityName);
|
|
1621
|
+
if (!key)
|
|
1622
|
+
continue;
|
|
1623
|
+
const filter = lane.ExtraFilter?.trim();
|
|
1624
|
+
const prior = filters.get(key);
|
|
1625
|
+
const merged = !filter || prior?.Filters === null ? null : [...(prior?.Filters ?? []), filter];
|
|
1626
|
+
filters.set(key, { EntityName: lane.EntityName, Filters: merged });
|
|
1627
|
+
}
|
|
1628
|
+
const bounds = new Map();
|
|
1629
|
+
for (const [key, entry] of filters) {
|
|
1630
|
+
if (!entry.Filters)
|
|
1631
|
+
continue;
|
|
1632
|
+
const clause = entry.Filters.length === 1 ? entry.Filters[0] : entry.Filters.map(f => `(${f})`).join(' OR ');
|
|
1633
|
+
bounds.set(key, { EntityName: entry.EntityName, Clause: clause });
|
|
1634
|
+
}
|
|
1635
|
+
return bounds;
|
|
1636
|
+
}
|
|
1637
|
+
/** An entity name normalised for matching a hit's `EntityName` to a lane's. */
|
|
1638
|
+
laneEntityKey(entityName) {
|
|
1639
|
+
return (entityName ?? '').trim().toLowerCase();
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* The lane bound `item` must satisfy in this `pass`, or `undefined` when it has none: a storage file, a hit
|
|
1643
|
+
* from a provider that applied the lane filter itself, a hit for an entity with no filtered lane — or, in the
|
|
1644
|
+
* `'promoted'` pass, a hit that was not promoted (step 1 of {@link boundScopeHits} already checked it).
|
|
1645
|
+
*/
|
|
1646
|
+
laneBoundFor(item, bounds, pass) {
|
|
1647
|
+
if (item.ResultType === 'storage-file')
|
|
1648
|
+
return undefined;
|
|
1649
|
+
if (pass === 'promoted' && !item.PromotedFromContentItemID)
|
|
1650
|
+
return undefined;
|
|
1651
|
+
if (this.providerThatReadRow(item)?.AppliesLaneExtraFilter === true)
|
|
1652
|
+
return undefined;
|
|
1653
|
+
return bounds.get(this.laneEntityKey(item.EntityName));
|
|
1654
|
+
}
|
|
1655
|
+
/** The candidate hits whose record satisfies its entity's lane bound — one read per entity, in parallel. */
|
|
1656
|
+
async hitsInsideLaneFilters(candidates, contextUser, scopeName) {
|
|
1657
|
+
const kept = new Set();
|
|
1658
|
+
await Promise.all(Array.from(candidates.entries()).map(async ([bound, hits]) => {
|
|
1659
|
+
for (const hit of await this.hitsInsideLaneFilter(bound, hits, contextUser, scopeName))
|
|
1660
|
+
kept.add(hit);
|
|
1661
|
+
}));
|
|
1662
|
+
return kept;
|
|
1663
|
+
}
|
|
1664
|
+
/** `hits` (all of `bound`'s entity) whose record satisfies the lane filter, read as the user; none when the read fails. */
|
|
1665
|
+
async hitsInsideLaneFilter(bound, hits, contextUser, scopeName) {
|
|
1666
|
+
try {
|
|
1667
|
+
const entity = this.ProviderToUse.EntityByName(bound.EntityName);
|
|
1668
|
+
if (!entity)
|
|
1669
|
+
throw new Error('the entity is not in metadata');
|
|
1670
|
+
const recordIDs = Array.from(new Set(hits.map(h => h.RecordID)));
|
|
1671
|
+
const keys = await this.readableRecordKeys(entity, recordIDs, bound.Clause, contextUser);
|
|
1672
|
+
if (!keys)
|
|
1673
|
+
throw new Error('the read failed');
|
|
1674
|
+
return hits.filter(h => {
|
|
1675
|
+
const key = this.recordMatchKey(entity, h.RecordID);
|
|
1676
|
+
return key !== null && keys.has(key);
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
catch (e) {
|
|
1680
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1681
|
+
LogError(`SearchEngine: scope "${scopeName}" — ${hits.length} hit(s) of "${bound.EntityName}" ` +
|
|
1682
|
+
`could not be checked against the lane ExtraFilter, so they were dropped: ${msg}`);
|
|
1683
|
+
return [];
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1196
1686
|
/**
|
|
1197
1687
|
* Assemble a `ScopeConstraints` for a single scope: Nunjucks-render each template
|
|
1198
1688
|
* field against the `SearchContext`, then hand the rendered values to providers.
|
|
@@ -1201,12 +1691,12 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1201
1691
|
* Fail a search CLOSED when a scope field that RESTRICTS was authored but did not render
|
|
1202
1692
|
* usably (see `CheckRenderedTemplate`).
|
|
1203
1693
|
*
|
|
1204
|
-
* Throwing rather than dropping the offending row is deliberate. Dropping
|
|
1205
|
-
* the
|
|
1206
|
-
* `undefined` —
|
|
1207
|
-
*
|
|
1208
|
-
*
|
|
1209
|
-
*
|
|
1694
|
+
* Throwing rather than dropping the offending row is deliberate. Dropping one lane of
|
|
1695
|
+
* several would quietly change what the scope covers, and a scope's ONLY lane dropped used to
|
|
1696
|
+
* collapse to `undefined` — "unscoped" to every provider. (A non-global scope now hands providers
|
|
1697
|
+
* an empty list, which means "nothing", but a silently narrowed scope is still a wrong answer.)
|
|
1698
|
+
* A broken restricting template is a misconfiguration and should be loud and actionable, never
|
|
1699
|
+
* silently degraded.
|
|
1210
1700
|
*/
|
|
1211
1701
|
assertRestrictingTemplateRendered(source, rendered, fieldName, scopeLabel, rowLabel, laneID, collector) {
|
|
1212
1702
|
const check = CheckRenderedTemplate(source, rendered);
|
|
@@ -1259,55 +1749,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1259
1749
|
}
|
|
1260
1750
|
buildScopeConstraints(bundle, searchContext, collector) {
|
|
1261
1751
|
const scopeLabel = `${bundle.Scope.Name} (${bundle.Scope.ID})`;
|
|
1262
|
-
const externalIndexes = bundle.ExternalIndexes.map(row =>
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
const laneKind = LaneKindForIndexType(row.IndexType);
|
|
1266
|
-
const metadataFilter = RenderScopeJsonTemplate(row.MetadataFilter, searchContext, undefined, laneKind);
|
|
1267
|
-
this.assertRestrictingTemplateRendered(row.MetadataFilter, metadataFilter, 'MetadataFilter', scopeLabel, rowLabel, row.ID, collector);
|
|
1268
|
-
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, metadataFilter, scopeLabel, rowLabel, collector);
|
|
1269
|
-
// ExternalIndexConfig is JSON (namespace/routing), regardless of the filter dialect.
|
|
1270
|
-
const externalIndexConfig = RenderScopeTemplate(row.ExternalIndexConfig, searchContext, undefined, 'json');
|
|
1271
|
-
// ExternalIndexConfig can carry tenant routing (e.g. Pinecone `namespace`), so a
|
|
1272
|
-
// silent render failure here can widen retrieval just like a filter can.
|
|
1273
|
-
this.assertRestrictingTemplateRendered(row.ExternalIndexConfig, externalIndexConfig, 'ExternalIndexConfig', scopeLabel, rowLabel, row.ID, collector);
|
|
1274
|
-
return {
|
|
1275
|
-
SearchScopeExternalIndexID: row.ID,
|
|
1276
|
-
IndexType: row.IndexType,
|
|
1277
|
-
VectorIndexID: row.VectorIndexID ?? undefined,
|
|
1278
|
-
ExternalIndexName: row.ExternalIndexName ?? undefined,
|
|
1279
|
-
ExternalIndexConfig: this.parseJson(externalIndexConfig),
|
|
1280
|
-
MetadataFilter: metadataFilter
|
|
1281
|
-
};
|
|
1282
|
-
});
|
|
1283
|
-
const entities = bundle.Entities.map(row => {
|
|
1284
|
-
// The entity lane is T-SQL, so single quotes must be doubled.
|
|
1285
|
-
const extraFilter = row.ExtraFilter ? RenderScopeTemplate(row.ExtraFilter, searchContext, undefined, 'sql') : undefined;
|
|
1286
|
-
const entityLabel = this.lookupEntityName(row.EntityID) || row.EntityID;
|
|
1287
|
-
this.assertRestrictingTemplateRendered(row.ExtraFilter, extraFilter, 'ExtraFilter', scopeLabel, entityLabel, row.ID, collector);
|
|
1288
|
-
// The SQL lane loses a guarded clause exactly the way an index lane does — same
|
|
1289
|
-
// renderer, same SearchContext, same optional {% if %} blocks — and it is the lane
|
|
1290
|
-
// that reads the operational database, so it gets the same contract.
|
|
1291
|
-
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, extraFilter, scopeLabel, entityLabel, collector);
|
|
1292
|
-
return {
|
|
1293
|
-
SearchScopeEntityID: row.ID,
|
|
1294
|
-
EntityID: row.EntityID,
|
|
1295
|
-
EntityName: this.lookupEntityName(row.EntityID),
|
|
1296
|
-
ExtraFilter: extraFilter,
|
|
1297
|
-
// UserSearchString and FolderPath are NOT restrictions — they shape the query
|
|
1298
|
-
// text / a path prefix — so a soft render there cannot widen an access bound
|
|
1299
|
-
// and is deliberately left unguarded.
|
|
1300
|
-
// 'none' deliberately: this becomes QUERY TEXT, not syntax. Escaping it would corrupt
|
|
1301
|
-
// the search rather than protect it, and it cannot express a bound.
|
|
1302
|
-
UserSearchString: row.UserSearchString ? RenderScopeTemplate(row.UserSearchString, searchContext, undefined, 'none') : undefined
|
|
1303
|
-
};
|
|
1304
|
-
});
|
|
1305
|
-
const storage = bundle.StorageAccounts.map(row => ({
|
|
1306
|
-
SearchScopeStorageAccountID: row.ID,
|
|
1307
|
-
FileStorageAccountID: row.FileStorageAccountID,
|
|
1308
|
-
// Path traversal, not quoting, is the risk on a storage lane.
|
|
1309
|
-
FolderPath: row.FolderPath ? RenderScopeTemplate(row.FolderPath, searchContext, undefined, 'path') : undefined
|
|
1310
|
-
}));
|
|
1752
|
+
const externalIndexes = bundle.ExternalIndexes.map(row => this.buildExternalIndexConstraint(row, searchContext, scopeLabel, collector));
|
|
1753
|
+
const entities = bundle.Entities.map(row => this.buildEntityConstraint(row, searchContext, scopeLabel, collector));
|
|
1754
|
+
const storage = bundle.StorageAccounts.map(row => this.buildStorageConstraint(row, searchContext, scopeLabel, collector));
|
|
1311
1755
|
// Per-provider query transforms: resolved from SearchScopeProvider.QueryTransformTemplateID
|
|
1312
1756
|
// For stored template IDs we need the TemplateEngine — that resolution happens in
|
|
1313
1757
|
// Phase 1C (AgentPreExecutionRAG) before this engine is called. We still honor any
|
|
@@ -1317,15 +1761,106 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1317
1761
|
const queryTransforms = rawTransforms && typeof rawTransforms === 'object'
|
|
1318
1762
|
? { ...rawTransforms }
|
|
1319
1763
|
: undefined;
|
|
1764
|
+
// A NON-global scope hands every provider a defined list, even an empty one: an empty list means
|
|
1765
|
+
// "nothing for you", and `undefined` would read as "unscoped" — every entity, every index, no
|
|
1766
|
+
// filter. Only a global scope keeps the old collapse (it runs unconstrained anyway).
|
|
1767
|
+
const lanesOrUnscoped = (rows) => (rows.length || !bundle.Scope.IsGlobal ? rows : undefined);
|
|
1320
1768
|
return {
|
|
1321
|
-
ExternalIndexes: externalIndexes
|
|
1322
|
-
Entities: entities
|
|
1323
|
-
StorageAccounts: storage
|
|
1769
|
+
ExternalIndexes: lanesOrUnscoped(externalIndexes),
|
|
1770
|
+
Entities: lanesOrUnscoped(entities),
|
|
1771
|
+
StorageAccounts: lanesOrUnscoped(storage),
|
|
1324
1772
|
Context: searchContext,
|
|
1325
1773
|
QueryTransforms: queryTransforms,
|
|
1326
1774
|
ScopeConfig: scopeConfig ?? undefined
|
|
1327
1775
|
};
|
|
1328
1776
|
}
|
|
1777
|
+
/** One external-index lane's constraint, with its restricting fields guarded. */
|
|
1778
|
+
buildExternalIndexConstraint(row, searchContext, scopeLabel, collector) {
|
|
1779
|
+
const rowLabel = row.ExternalIndexName ?? row.ID;
|
|
1780
|
+
// §5.4: values are escaped for THIS lane's dialect automatically, derived from IndexType.
|
|
1781
|
+
const laneKind = LaneKindForIndexType(row.IndexType);
|
|
1782
|
+
const metadataFilter = RenderScopeJsonTemplate(row.MetadataFilter, searchContext, undefined, laneKind);
|
|
1783
|
+
this.assertRestrictingTemplateRendered(row.MetadataFilter, metadataFilter, 'MetadataFilter', scopeLabel, rowLabel, row.ID, collector);
|
|
1784
|
+
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, metadataFilter, scopeLabel, rowLabel, collector);
|
|
1785
|
+
// ExternalIndexConfig is JSON (namespace/routing), regardless of the filter dialect.
|
|
1786
|
+
const externalIndexConfig = RenderScopeTemplate(row.ExternalIndexConfig, searchContext, undefined, 'json');
|
|
1787
|
+
// ExternalIndexConfig can carry tenant routing (e.g. Pinecone `namespace`), so a
|
|
1788
|
+
// silent render failure here can widen retrieval just like a filter can.
|
|
1789
|
+
this.assertRestrictingTemplateRendered(row.ExternalIndexConfig, externalIndexConfig, 'ExternalIndexConfig', scopeLabel, rowLabel, row.ID, collector);
|
|
1790
|
+
return {
|
|
1791
|
+
SearchScopeExternalIndexID: row.ID,
|
|
1792
|
+
IndexType: row.IndexType,
|
|
1793
|
+
VectorIndexID: row.VectorIndexID ?? undefined,
|
|
1794
|
+
ExternalIndexName: row.ExternalIndexName ?? undefined,
|
|
1795
|
+
ExternalIndexConfig: this.parseJson(externalIndexConfig),
|
|
1796
|
+
MetadataFilter: metadataFilter
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1799
|
+
/** One entity lane's constraint: its `ExtraFilter` rendered for T-SQL and guarded. */
|
|
1800
|
+
buildEntityConstraint(row, searchContext, scopeLabel, collector) {
|
|
1801
|
+
// The entity lane is T-SQL, so single quotes must be doubled.
|
|
1802
|
+
const extraFilter = row.ExtraFilter ? RenderScopeTemplate(row.ExtraFilter, searchContext, undefined, 'sql') : undefined;
|
|
1803
|
+
const entityLabel = this.lookupEntityName(row.EntityID) || row.EntityID;
|
|
1804
|
+
this.assertRestrictingTemplateRendered(row.ExtraFilter, extraFilter, 'ExtraFilter', scopeLabel, entityLabel, row.ID, collector);
|
|
1805
|
+
// The SQL lane loses a guarded clause exactly the way an index lane does — same
|
|
1806
|
+
// renderer, same SearchContext, same optional {% if %} blocks — and it is the lane
|
|
1807
|
+
// that reads the operational database, so it gets the same contract.
|
|
1808
|
+
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, extraFilter, scopeLabel, entityLabel, collector);
|
|
1809
|
+
return {
|
|
1810
|
+
SearchScopeEntityID: row.ID,
|
|
1811
|
+
EntityID: row.EntityID,
|
|
1812
|
+
EntityName: this.lookupEntityName(row.EntityID),
|
|
1813
|
+
ExtraFilter: extraFilter,
|
|
1814
|
+
// UserSearchString is NOT a restriction — it shapes the query text — so a soft
|
|
1815
|
+
// render there cannot widen an access bound and is deliberately left unguarded.
|
|
1816
|
+
// (FolderPath, by contrast, restricts; see buildStorageConstraint.)
|
|
1817
|
+
// 'none' deliberately: this becomes QUERY TEXT, not syntax. Escaping it would corrupt
|
|
1818
|
+
// the search rather than protect it, and it cannot express a bound.
|
|
1819
|
+
UserSearchString: row.UserSearchString ? RenderScopeTemplate(row.UserSearchString, searchContext, undefined, 'none') : undefined
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
* One storage lane's constraint. `FolderPath` RESTRICTS — it is what confines the lane to one folder
|
|
1824
|
+
* of the account — so a FolderPath that was authored but renders empty, with an empty segment, with
|
|
1825
|
+
* a `..` segment, or with an interpolated value the `path` escaper refuses makes the lane unusable:
|
|
1826
|
+
* the search is refused (or, in a dry run, the lane is reported skipped). An absent FolderPath still
|
|
1827
|
+
* means the whole account.
|
|
1828
|
+
*/
|
|
1829
|
+
buildStorageConstraint(row, searchContext, scopeLabel, collector) {
|
|
1830
|
+
let folderPath;
|
|
1831
|
+
if (row.FolderPath) {
|
|
1832
|
+
folderPath = this.renderFolderPath(row.FolderPath, searchContext, scopeLabel, row, collector);
|
|
1833
|
+
if (folderPath !== undefined) {
|
|
1834
|
+
const check = CheckRenderedFolderPath(row.FolderPath, folderPath);
|
|
1835
|
+
if (check.Status === 'unusable')
|
|
1836
|
+
this.reportFolderPathProblem(check.Reason, scopeLabel, row, collector);
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
return {
|
|
1840
|
+
SearchScopeStorageAccountID: row.ID,
|
|
1841
|
+
FileStorageAccountID: row.FileStorageAccountID,
|
|
1842
|
+
FolderPath: folderPath,
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
/**
|
|
1846
|
+
* Render a storage lane's FolderPath on the `path` lane. The renderer throws when an interpolated value
|
|
1847
|
+
* is `..` or `.`, or contains a separator; that is reported as the lane's problem (undefined is returned
|
|
1848
|
+
* only in a dry run, where the problem is collected instead of thrown).
|
|
1849
|
+
*/
|
|
1850
|
+
renderFolderPath(source, searchContext, scopeLabel, row, collector) {
|
|
1851
|
+
try {
|
|
1852
|
+
return RenderScopeTemplate(source, searchContext, undefined, 'path');
|
|
1853
|
+
}
|
|
1854
|
+
catch (e) {
|
|
1855
|
+
this.reportFolderPathProblem(e instanceof Error ? e.message : String(e), scopeLabel, row, collector);
|
|
1856
|
+
return undefined;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
/** A FolderPath problem, in the wording `assertRestrictingTemplateRendered` uses for every restricting field. */
|
|
1860
|
+
reportFolderPathProblem(reason, scopeLabel, row, collector) {
|
|
1861
|
+
this.reportLaneProblem(`SearchEngine: scope ${scopeLabel} — FolderPath for storage account "${row.FileStorageAccountID}" ` +
|
|
1862
|
+
`could not be rendered safely, so the search was NOT run. ${reason}`, row.ID, collector);
|
|
1863
|
+
}
|
|
1329
1864
|
/** Resolve the EntityID → EntityName via MJ Metadata (for passing to providers that key by name). */
|
|
1330
1865
|
lookupEntityName(entityID) {
|
|
1331
1866
|
try {
|
|
@@ -1367,6 +1902,50 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1367
1902
|
}
|
|
1368
1903
|
return null;
|
|
1369
1904
|
}
|
|
1905
|
+
/**
|
|
1906
|
+
* The per-provider over-fetch multiplier for this search, in priority order: the caller's
|
|
1907
|
+
* `SearchParams.PermissionOverfetchFactor`; else the **largest** of each resolved scope's declared
|
|
1908
|
+
* `ScopeConfig.permissionOverfetchFactor` (a scope that declares none counts as the engine default);
|
|
1909
|
+
* else the engine default. Clamped to `[1, MAX_OVERFETCH_FACTOR]`.
|
|
1910
|
+
*
|
|
1911
|
+
* The largest wins across scopes, not the first: over-fetch exists to compensate for late
|
|
1912
|
+
* permission filtering, and a lane trimmed heavily by it needs the extra candidates whichever
|
|
1913
|
+
* scope it belongs to. A larger factor never changes which results the caller gets (the final
|
|
1914
|
+
* list is still trimmed to `MaxResults`), but it does cost more: every provider returns more
|
|
1915
|
+
* candidates, dedup, the content exclusion and the permission passes do more work, a re-ranker is
|
|
1916
|
+
* fed up to its `inputTopN` from a bigger pool, and `streamSearch`'s per-provider partial events
|
|
1917
|
+
* (capped to the caller's `MaxResults`) draw from it. This is why a scope may declare it at all:
|
|
1918
|
+
* the scope's author knows how sparse its lanes are after permissions, and every caller shouldn't
|
|
1919
|
+
* have to.
|
|
1920
|
+
*/
|
|
1921
|
+
ResolvePermissionOverfetchFactor(params, resolvedScopes) {
|
|
1922
|
+
if (typeof params.PermissionOverfetchFactor === 'number' && Number.isFinite(params.PermissionOverfetchFactor)) {
|
|
1923
|
+
return this.clampOverfetchFactor(params.PermissionOverfetchFactor, 'the caller');
|
|
1924
|
+
}
|
|
1925
|
+
// A scope that declares nothing counts as the default, so one scope's low factor never pulls
|
|
1926
|
+
// down a neighbour that was happy with the default (the max is a floor, never a ceiling).
|
|
1927
|
+
const factors = resolvedScopes.map(bundle => this.scopeOverfetchFactor(bundle.Scope.ScopeConfig) ?? this._defaultOverfetchFactor);
|
|
1928
|
+
if (factors.length > 0)
|
|
1929
|
+
return this.clampOverfetchFactor(Math.max(...factors), 'a scope');
|
|
1930
|
+
return this._defaultOverfetchFactor;
|
|
1931
|
+
}
|
|
1932
|
+
/** A scope's declared `ScopeConfig.permissionOverfetchFactor`, when it is a finite number. Anything else is "not declared". */
|
|
1933
|
+
scopeOverfetchFactor(scopeConfigJson) {
|
|
1934
|
+
const factor = this.parseJson(scopeConfigJson)?.permissionOverfetchFactor;
|
|
1935
|
+
return typeof factor === 'number' && Number.isFinite(factor) ? factor : undefined;
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Hold the factor to `[1, MAX_OVERFETCH_FACTOR]`. Below 1 would under-fetch the caller's own `topK`;
|
|
1939
|
+
* above the ceiling, a single metadata edit would multiply every provider call for every caller of
|
|
1940
|
+
* the scope (vector providers bill per candidate). A clamped value is logged so the author sees it.
|
|
1941
|
+
*/
|
|
1942
|
+
clampOverfetchFactor(factor, from) {
|
|
1943
|
+
const clamped = Math.min(SearchEngine.MAX_OVERFETCH_FACTOR, Math.max(1, factor));
|
|
1944
|
+
if (clamped !== factor) {
|
|
1945
|
+
LogStatus(`SearchEngine: permission over-fetch factor ${factor} from ${from} clamped to ${clamped} (allowed range 1–${SearchEngine.MAX_OVERFETCH_FACTOR}).`);
|
|
1946
|
+
}
|
|
1947
|
+
return clamped;
|
|
1948
|
+
}
|
|
1370
1949
|
async runReRanker(query, candidates, cfg, contextUser, budgetGuard) {
|
|
1371
1950
|
if (!cfg.driverClass || candidates.length === 0)
|
|
1372
1951
|
return candidates;
|
|
@@ -1474,13 +2053,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1474
2053
|
* When isPreview is true, only providers with SupportsPreview=true are included.
|
|
1475
2054
|
*/
|
|
1476
2055
|
async executeProviders(query, topK, filters, contextUser, isPreview, scopeConstraints, onProviderResolved, minScore) {
|
|
1477
|
-
const entries = this.
|
|
1478
|
-
if (!e.Provider.IsAvailable())
|
|
1479
|
-
return false;
|
|
1480
|
-
if (isPreview && !e.SupportsPreview)
|
|
1481
|
-
return false;
|
|
1482
|
-
return true;
|
|
1483
|
-
});
|
|
2056
|
+
const entries = this.availableProviders(isPreview);
|
|
1484
2057
|
if (entries.length === 0) {
|
|
1485
2058
|
LogStatus('SearchEngine: No providers available');
|
|
1486
2059
|
return [];
|
|
@@ -1559,34 +2132,47 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1559
2132
|
return counts;
|
|
1560
2133
|
}
|
|
1561
2134
|
// ────────────────────────────────────────────────────────────────
|
|
1562
|
-
// Permission filtering (residual late safety net)
|
|
2135
|
+
// Permission filtering (residual late safety net, then the origin-record gate)
|
|
1563
2136
|
// ────────────────────────────────────────────────────────────────
|
|
1564
2137
|
/**
|
|
1565
|
-
* Filter search results by entity-level and row-level security permissions
|
|
2138
|
+
* Filter search results by entity-level and row-level security permissions, then by whether the user
|
|
2139
|
+
* may read the record each content result was derived from.
|
|
1566
2140
|
*
|
|
1567
|
-
* **
|
|
1568
|
-
* push-down (Section 3.6 of plans/search-scopes-rag-plus.md). If
|
|
1569
|
-
*
|
|
1570
|
-
*
|
|
2141
|
+
* **Steps 1–4 are a safety net.** Providers are expected to do per-provider permission
|
|
2142
|
+
* push-down (Section 3.6 of plans/search-scopes-rag-plus.md). If those steps remove more
|
|
2143
|
+
* than a handful of results in practice, the responsible provider's push-down is incomplete
|
|
2144
|
+
* and should be fixed. **Step 5 is not**: it drops by design, because no provider can push
|
|
2145
|
+
* an origin record's own row filters down into a content index. Its removals are counted
|
|
2146
|
+
* into `stats.OriginGateRemoved`, so the late-filter count keeps its meaning.
|
|
1571
2147
|
*
|
|
1572
2148
|
* Groups results by entity for efficient permission checking:
|
|
1573
2149
|
* 1. Unknown entities are excluded (fail closed).
|
|
1574
2150
|
* 2. If the user lacks entity-level CanRead, all results for that entity are dropped.
|
|
1575
2151
|
* 3. If the user is exempt from RLS, all results pass through.
|
|
1576
2152
|
* 4. If RLS applies, a RunView validates which record IDs the user can read.
|
|
2153
|
+
* 5. Content items and chunks are kept only when the user may read the record they were
|
|
2154
|
+
* derived from ({@link VerifyOriginRecords}).
|
|
2155
|
+
* 6. Fields the user may not read are projected out of what is kept: metadata keys, and any
|
|
2156
|
+
* snippet or title taken from them ({@link projectEntityResultsForReader}). The returned
|
|
2157
|
+
* results are copies wherever something was removed.
|
|
2158
|
+
*
|
|
2159
|
+
* `storage-file` results take their own path ({@link filterStorageResults}): they are re-checked against
|
|
2160
|
+
* the storage-account permission model for this user, never passed through on the strength of their type.
|
|
2161
|
+
*
|
|
2162
|
+
* @param stats optional per-call counters; `OriginGateRemoved` is incremented by step 5's removals
|
|
1577
2163
|
*/
|
|
1578
|
-
async filterByPermissions(results, contextUser) {
|
|
2164
|
+
async filterByPermissions(results, contextUser, stats) {
|
|
1579
2165
|
if (results.length === 0)
|
|
1580
2166
|
return results;
|
|
1581
|
-
// Storage file results have their own permission model (FileStorageAccountPermission)
|
|
1582
|
-
//
|
|
2167
|
+
// Storage file results have their own permission model (FileStorageAccountPermission) — re-checked
|
|
2168
|
+
// here for this user rather than trusted from the provider (see filterStorageResults)
|
|
1583
2169
|
const storageResults = results.filter(r => r.ResultType === 'storage-file');
|
|
1584
2170
|
const entityResults = results.filter(r => r.ResultType !== 'storage-file');
|
|
1585
2171
|
const byEntity = this.groupResultsByEntity(entityResults);
|
|
1586
|
-
const permitted = [
|
|
1587
|
-
const promises = [];
|
|
2172
|
+
const permitted = [];
|
|
2173
|
+
const promises = [this.filterStorageResults(storageResults, contextUser, permitted)];
|
|
1588
2174
|
for (const [entityName, groupResults] of byEntity) {
|
|
1589
|
-
promises.push(this.filterEntityResults(entityName, groupResults, contextUser, permitted));
|
|
2175
|
+
promises.push(this.filterEntityResults(entityName, groupResults, contextUser, permitted, stats));
|
|
1590
2176
|
}
|
|
1591
2177
|
await Promise.all(promises);
|
|
1592
2178
|
// Preserve the input order (which is the RRF/re-rank order). groupResultsByEntity
|
|
@@ -1597,6 +2183,112 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1597
2183
|
permitted.sort((a, b) => (inputIndex.get(a) ?? 0) - (inputIndex.get(b) ?? 0));
|
|
1598
2184
|
return permitted;
|
|
1599
2185
|
}
|
|
2186
|
+
/**
|
|
2187
|
+
* The storage half of {@link filterByPermissions}: re-check `storage-file` results for `contextUser` and push the
|
|
2188
|
+
* ones that pass into `permitted`.
|
|
2189
|
+
*
|
|
2190
|
+
* `ResultType` is set by whichever provider produced a result, so being typed `storage-file` proves nothing. A
|
|
2191
|
+
* storage hit is kept only when ALL hold:
|
|
2192
|
+
* - its `ProviderId` — stamped by this engine on every result, overwriting whatever the provider set — names a
|
|
2193
|
+
* configured entry whose provider is a {@link StorageSearchProvider};
|
|
2194
|
+
* - the account it names (`RawMetadata.accountId`, as that provider writes it) is one `contextUser` may read now,
|
|
2195
|
+
* per `StorageAccessEvaluator` (per call; the account-without-rows rule lives there); and
|
|
2196
|
+
* - the object it names (`RawMetadata.path` / `objectId`) does not back an `MJ: Files` row `contextUser` may not
|
|
2197
|
+
* read — the tracked-file rule `CreatePreAuthDownloadUrl` applies, so a hit never names (or excerpts) a file the
|
|
2198
|
+
* caller would be refused ({@link dropUnreadableTrackedStorageHits}).
|
|
2199
|
+
*
|
|
2200
|
+
* Anything else — no or a foreign `ProviderId`, missing or unparseable metadata, an evaluator failure or throw —
|
|
2201
|
+
* drops the result (fail closed). Order is restored by the caller.
|
|
2202
|
+
*/
|
|
2203
|
+
async filterStorageResults(results, contextUser, permitted) {
|
|
2204
|
+
if (results.length === 0)
|
|
2205
|
+
return;
|
|
2206
|
+
try {
|
|
2207
|
+
const candidates = this.storageCandidates(results);
|
|
2208
|
+
if (candidates.length === 0)
|
|
2209
|
+
return;
|
|
2210
|
+
const readable = await StorageAccessEvaluator.Instance.AccessibleAccountIDs(candidates.map(c => c.AccountID), contextUser, 'Read', this.ProviderToUse);
|
|
2211
|
+
const onReadableAccounts = candidates.filter(c => readable.has(NormalizeUUID(c.AccountID)));
|
|
2212
|
+
const visible = await this.dropUnreadableTrackedStorageHits(onReadableAccounts, contextUser);
|
|
2213
|
+
permitted.push(...visible.map(c => c.Item));
|
|
2214
|
+
}
|
|
2215
|
+
catch (error) {
|
|
2216
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2217
|
+
LogError(`SearchEngine: Storage permission filtering failed — ${results.length} storage result(s) dropped: ${msg}`);
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* The tracked-file rule on storage hits: grouped by account, each account's hits are checked in one batched lookup
|
|
2222
|
+
* against the `MJ: Files` rows on that account's provider (`StorageAccessEvaluator.UnreadableTrackedObjectKeys`,
|
|
2223
|
+
* compared the way the account's driver addresses keys), and a hit whose path or object ID backs a row the caller
|
|
2224
|
+
* may not read is dropped. An account whose provider or driver cannot be resolved loses all its hits (fail closed).
|
|
2225
|
+
*/
|
|
2226
|
+
async dropUnreadableTrackedStorageHits(candidates, contextUser) {
|
|
2227
|
+
const byAccount = new Map();
|
|
2228
|
+
for (const candidate of candidates) {
|
|
2229
|
+
const key = NormalizeUUID(candidate.AccountID);
|
|
2230
|
+
byAccount.set(key, [...(byAccount.get(key) ?? []), candidate]);
|
|
2231
|
+
}
|
|
2232
|
+
const kept = await Promise.all([...byAccount.values()].map(group => this.readableTrackedStorageHits(group, contextUser)));
|
|
2233
|
+
return kept.flat();
|
|
2234
|
+
}
|
|
2235
|
+
/** {@link dropUnreadableTrackedStorageHits} for one account's hits; any failure drops them all. */
|
|
2236
|
+
async readableTrackedStorageHits(group, contextUser) {
|
|
2237
|
+
const accountID = group[0].AccountID;
|
|
2238
|
+
try {
|
|
2239
|
+
await FileStorageEngine.Instance.Config(false, contextUser, this.ProviderToUse);
|
|
2240
|
+
const account = FileStorageEngine.Instance.GetAccountById(accountID);
|
|
2241
|
+
if (!account) {
|
|
2242
|
+
LogError(`SearchEngine: storage account ${accountID} is not in the storage cache — its ${group.length} hit(s) dropped`);
|
|
2243
|
+
return [];
|
|
2244
|
+
}
|
|
2245
|
+
const driver = await FileStorageEngine.Instance.GetDriver(account.ID, contextUser);
|
|
2246
|
+
const unreadable = await StorageAccessEvaluator.Instance.UnreadableTrackedObjectKeys(account.ProviderID, group.flatMap(c => c.ObjectKeys), contextUser, this.ProviderToUse, driver);
|
|
2247
|
+
return group.filter(c => !c.ObjectKeys.some(key => unreadable.has(key)));
|
|
2248
|
+
}
|
|
2249
|
+
catch (error) {
|
|
2250
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2251
|
+
LogError(`SearchEngine: tracked-file check failed for storage account ${accountID} — its ${group.length} hit(s) dropped: ${msg}`);
|
|
2252
|
+
return [];
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
/**
|
|
2256
|
+
* The storage results that came from a configured {@link StorageSearchProvider} entry and name a well-formed account
|
|
2257
|
+
* and at least one object key, paired with them. Everything else is left out, which drops it.
|
|
2258
|
+
*/
|
|
2259
|
+
storageCandidates(results) {
|
|
2260
|
+
const storageProviderIDs = new Set(this._providerEntries.filter(e => e.Provider instanceof StorageSearchProvider).map(e => NormalizeUUID(e.ID)));
|
|
2261
|
+
const candidates = [];
|
|
2262
|
+
for (const item of results) {
|
|
2263
|
+
if (!item.ProviderId || !storageProviderIDs.has(NormalizeUUID(item.ProviderId)))
|
|
2264
|
+
continue;
|
|
2265
|
+
const location = this.storageLocationOf(item);
|
|
2266
|
+
if (location)
|
|
2267
|
+
candidates.push({ Item: item, ...location });
|
|
2268
|
+
}
|
|
2269
|
+
return candidates;
|
|
2270
|
+
}
|
|
2271
|
+
/**
|
|
2272
|
+
* The account (`RawMetadata.accountId`) and object keys (`RawMetadata.path`, `RawMetadata.objectId`) a
|
|
2273
|
+
* `storage-file` result names, or null when the account is absent or malformed or no object key is present.
|
|
2274
|
+
*/
|
|
2275
|
+
storageLocationOf(item) {
|
|
2276
|
+
if (!item.RawMetadata)
|
|
2277
|
+
return null;
|
|
2278
|
+
try {
|
|
2279
|
+
const parsed = JSON.parse(item.RawMetadata);
|
|
2280
|
+
if (!parsed || typeof parsed !== 'object')
|
|
2281
|
+
return null;
|
|
2282
|
+
const accountId = parsed.accountId;
|
|
2283
|
+
const objectKeys = [parsed.path, parsed.objectId].filter((k) => typeof k === 'string' && k.length > 0);
|
|
2284
|
+
if (typeof accountId !== 'string' || !IsValidUUID(accountId) || objectKeys.length === 0)
|
|
2285
|
+
return null;
|
|
2286
|
+
return { AccountID: accountId, ObjectKeys: objectKeys };
|
|
2287
|
+
}
|
|
2288
|
+
catch {
|
|
2289
|
+
return null;
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
1600
2292
|
/**
|
|
1601
2293
|
* Group search result items by EntityName for batch permission checking.
|
|
1602
2294
|
*/
|
|
@@ -1615,10 +2307,11 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1615
2307
|
}
|
|
1616
2308
|
/**
|
|
1617
2309
|
* Check permissions for a single entity's batch of results.
|
|
1618
|
-
* Permitted results are pushed into the shared `permitted` array
|
|
2310
|
+
* Permitted results are pushed into the shared `permitted` array; rows the origin-record gate removes are
|
|
2311
|
+
* counted into `stats` when it is supplied.
|
|
1619
2312
|
* On any error, results are excluded (fail closed).
|
|
1620
2313
|
*/
|
|
1621
|
-
async filterEntityResults(entityName, entityResults, contextUser, permitted) {
|
|
2314
|
+
async filterEntityResults(entityName, entityResults, contextUser, permitted, stats) {
|
|
1622
2315
|
try {
|
|
1623
2316
|
const md = this.ProviderToUse;
|
|
1624
2317
|
let entity = null;
|
|
@@ -1637,33 +2330,13 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1637
2330
|
return;
|
|
1638
2331
|
// Check row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
1639
2332
|
const rlsClause = entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, '');
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
// documents that are not that entity's records at all.
|
|
1648
|
-
//
|
|
1649
|
-
// Results from a lane that queried the entity directly need no such check — their ids
|
|
1650
|
-
// came out of a RunView against it. So pass those through untouched (this is the hot
|
|
1651
|
-
// path and its cost is unchanged) and verify only the rest.
|
|
1652
|
-
const selfEvident = [];
|
|
1653
|
-
const unverified = [];
|
|
1654
|
-
for (const item of entityResults) {
|
|
1655
|
-
(SearchEngine.lanesWithSelfEvidentOwnership.has(item.SourceType) ? selfEvident : unverified)
|
|
1656
|
-
.push(item);
|
|
1657
|
-
}
|
|
1658
|
-
permitted.push(...selfEvident);
|
|
1659
|
-
if (unverified.length > 0) {
|
|
1660
|
-
await this.verifyOwnershipAndRowFilters(entity, unverified, undefined, contextUser, permitted);
|
|
1661
|
-
}
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
// A row filter applies — validate record IDs via RunView. Unchanged: this path already
|
|
1665
|
-
// verified ownership as a side effect of filtering, for every lane.
|
|
1666
|
-
await this.verifyOwnershipAndRowFilters(entity, entityResults, rlsClause, contextUser, permitted);
|
|
2333
|
+
// A row the user may read is not yet a row they may be shown: content derived from a record they
|
|
2334
|
+
// cannot read is still theirs to miss, so the admitted rows pass the origin gate next.
|
|
2335
|
+
const ownRows = await this.admitOwnRows(entity, entityResults, rlsClause, contextUser);
|
|
2336
|
+
const kept = await this.VerifyOriginRecords(entity, ownRows, contextUser);
|
|
2337
|
+
if (stats)
|
|
2338
|
+
stats.OriginGateRemoved += Math.max(0, ownRows.length - kept.length);
|
|
2339
|
+
permitted.push(...this.projectEntityResultsForReader(entity, kept, contextUser));
|
|
1667
2340
|
}
|
|
1668
2341
|
catch (error) {
|
|
1669
2342
|
// Fail closed — if anything goes wrong, exclude the results
|
|
@@ -1672,10 +2345,104 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1672
2345
|
}
|
|
1673
2346
|
}
|
|
1674
2347
|
/**
|
|
1675
|
-
*
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
*
|
|
2348
|
+
* Field-level security for results the user may read: the fields of `entity` they may not read come out
|
|
2349
|
+
* of each result's `RawMetadata`, and a `Snippet`, `Title` or `RecordName` taken from one is cleared.
|
|
2350
|
+
*
|
|
2351
|
+
* Indexes are built once, under the identity of whoever ran the indexing job, and shared by every reader,
|
|
2352
|
+
* so a row the user may read can still carry a value they may not. Results their provider read through
|
|
2353
|
+
* `RunView` as this user ({@link isSelfEvidentRow}) were projected at the source; the rest are checked
|
|
2354
|
+
* against their metadata, and lose their text when there is none to check it against. Returns copies;
|
|
2355
|
+
* `EntityName` and `RecordID` are never changed (see {@link FilterForAudience}'s identity contract).
|
|
2356
|
+
*/
|
|
2357
|
+
projectEntityResultsForReader(entity, results, contextUser) {
|
|
2358
|
+
const denied = entity.GetDeniedReadFields(contextUser);
|
|
2359
|
+
if (denied.size === 0)
|
|
2360
|
+
return results;
|
|
2361
|
+
return results.map(item => ProjectSearchResultForReader(item, denied, { TextAlreadyProjected: this.isSelfEvidentRow(item) }));
|
|
2362
|
+
}
|
|
2363
|
+
/**
|
|
2364
|
+
* Gate 1: the results that are rows of `entity` the user may read.
|
|
2365
|
+
*
|
|
2366
|
+
* With no row filter (or a user exempt from row filtering) that settles WHICH ROWS of this entity they may
|
|
2367
|
+
* see — it does not establish that these results ARE this entity's rows. `EntityName` is provider output,
|
|
2368
|
+
* and for the vector and 3rd-party lanes it comes from the index: vector metadata's `Entity` key, or the
|
|
2369
|
+
* index name. Admitting on that label alone lets whoever writes the index choose which entity's
|
|
2370
|
+
* permissions get evaluated, so a label naming an entity the user CAN read admits documents that are not
|
|
2371
|
+
* that entity's records at all.
|
|
2372
|
+
*
|
|
2373
|
+
* Results that came out of a RunView against the entity need no such check, so those pass untouched (this
|
|
2374
|
+
* is the hot path and its cost is unchanged) and only the rest are verified — see {@link isSelfEvidentRow}
|
|
2375
|
+
* for which results qualify. When a row filter applies, every result is verified: ownership is checked as
|
|
2376
|
+
* a side effect of filtering.
|
|
2377
|
+
*/
|
|
2378
|
+
async admitOwnRows(entity, entityResults, rlsClause, contextUser) {
|
|
2379
|
+
const ownRows = [];
|
|
2380
|
+
if (rlsClause) {
|
|
2381
|
+
await this.verifyOwnershipAndRowFilters(entity, entityResults, rlsClause, contextUser, ownRows);
|
|
2382
|
+
return ownRows;
|
|
2383
|
+
}
|
|
2384
|
+
const unverified = [];
|
|
2385
|
+
for (const item of entityResults) {
|
|
2386
|
+
(this.isSelfEvidentRow(item) ? ownRows : unverified).push(item);
|
|
2387
|
+
}
|
|
2388
|
+
if (unverified.length > 0) {
|
|
2389
|
+
await this.verifyOwnershipAndRowFilters(entity, unverified, undefined, contextUser, ownRows);
|
|
2390
|
+
}
|
|
2391
|
+
return ownRows;
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* Whether `item` is self-evidently a row of the entity it is labelled with: the engine stamped it with a
|
|
2395
|
+
* configured provider that reads that entity through `RunView`
|
|
2396
|
+
* ({@link BaseSearchProvider.ResultsAreRowsOfLabelledEntity}), AND it carries one of the lanes in
|
|
2397
|
+
* {@link lanesWithSelfEvidentOwnership}.
|
|
2398
|
+
*
|
|
2399
|
+
* Trust follows the engine's stamp, never the label. `SourceType` is provider output and `SearchSource` is a
|
|
2400
|
+
* closed union, so every shipped external-index provider (Azure AI Search, Typesense, Elasticsearch,
|
|
2401
|
+
* OpenSearch) stamps `'fulltext'` with the index name as `EntityName`, and a third-party provider may stamp
|
|
2402
|
+
* `'entity'`. A result with no `ProviderId` (a fusion fallback, a hand-built hit) or one naming no configured
|
|
2403
|
+
* provider is verified, and so is a hit promoted from a content item to its origin record
|
|
2404
|
+
* (`PromotedFromContentItemID`): its provider read the content item, never the origin row.
|
|
2405
|
+
*
|
|
2406
|
+
* Fusion and dedup never move a `ProviderId` onto another item's `EntityName`/`RecordID`/`SourceType`: each
|
|
2407
|
+
* merged result is one provider's item, whole, and only scores, `ScoreBreakdown`, tags and (dedup) a snippet
|
|
2408
|
+
* replacing a generic one are taken from the items it absorbed. Those may be from rows nothing verified:
|
|
2409
|
+
* `Deduplicate` merges items sharing `EntityName` + `RecordID`, but per-scope RRF (`SearchFusion.applyRRF`)
|
|
2410
|
+
* merges `ScoreBreakdown` across items sharing only a `RecordID` — of any entity — keeping the first. So a
|
|
2411
|
+
* merge can lend a trusted item another item's scores, never its trust: trust is the surviving item's own.
|
|
2412
|
+
*/
|
|
2413
|
+
isSelfEvidentRow(item) {
|
|
2414
|
+
if (!SearchEngine.lanesWithSelfEvidentOwnership.has(item.SourceType))
|
|
2415
|
+
return false;
|
|
2416
|
+
return this.providerThatReadRow(item)?.ResultsAreRowsOfLabelledEntity === true;
|
|
2417
|
+
}
|
|
2418
|
+
/**
|
|
2419
|
+
* The configured provider that read the row `item` names — {@link ProviderForResult}, except for a hit the
|
|
2420
|
+
* engine promoted from a content item to its origin record (`PromotedFromContentItemID`), whose row no
|
|
2421
|
+
* provider read. Both per-provider trust decisions resolve through here: ownership
|
|
2422
|
+
* (`ResultsAreRowsOfLabelledEntity`, {@link isSelfEvidentRow}) and the lane `ExtraFilter` exemption
|
|
2423
|
+
* (`AppliesLaneExtraFilter`, {@link laneBoundFor}).
|
|
2424
|
+
*/
|
|
2425
|
+
providerThatReadRow(item) {
|
|
2426
|
+
return item.PromotedFromContentItemID ? undefined : this.ProviderForResult(item);
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* The configured provider whose engine-stamped `ProviderId` `item` carries, or `undefined` when it carries
|
|
2430
|
+
* none or names no configured provider. The engine overwrites `ProviderId` on every result a provider
|
|
2431
|
+
* returns, before fusion.
|
|
2432
|
+
*
|
|
2433
|
+
* Protected so a probe can map a hand-built hit to a provider instance without configuring the engine. It
|
|
2434
|
+
* decides which results skip ownership verification and which skip the lane `ExtraFilter` re-check, so an
|
|
2435
|
+
* override must only ever return the provider that actually produced the result.
|
|
2436
|
+
*/
|
|
2437
|
+
ProviderForResult(item) {
|
|
2438
|
+
if (!item.ProviderId)
|
|
2439
|
+
return undefined;
|
|
2440
|
+
return this._providerEntries.find(e => UUIDsEqual(e.ID, item.ProviderId))?.Provider;
|
|
2441
|
+
}
|
|
2442
|
+
/**
|
|
2443
|
+
* Lanes whose results can be self-evident rows of the entity they are labelled with — a necessary
|
|
2444
|
+
* condition only: the provider that produced the result must also say it reads that entity through
|
|
2445
|
+
* `RunView` (see {@link isSelfEvidentRow}). The vector lane, and anything else, is always verified.
|
|
1679
2446
|
*
|
|
1680
2447
|
* An allowlist rather than a denylist on purpose: a `SourceType` nobody anticipated is verified by
|
|
1681
2448
|
* default instead of trusted by default.
|
|
@@ -1688,11 +2455,43 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1688
2455
|
* record of this entity is dropped whether or not a row filter exists.
|
|
1689
2456
|
*/
|
|
1690
2457
|
async verifyOwnershipAndRowFilters(entity, entityResults, rlsClause, contextUser, permitted) {
|
|
2458
|
+
const validKeys = await this.readableRecordKeys(entity, entityResults.map(r => r.RecordID), rlsClause, contextUser);
|
|
2459
|
+
if (!validKeys)
|
|
2460
|
+
return; // fail closed — already logged
|
|
2461
|
+
for (const item of entityResults) {
|
|
2462
|
+
const key = this.recordMatchKey(entity, item.RecordID);
|
|
2463
|
+
if (key !== null && validKeys.has(key)) {
|
|
2464
|
+
permitted.push(item);
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* Ask the database, as `contextUser`, which of `recordIDs` are rows of `entity` the user may read:
|
|
2470
|
+
* `PK IN (...)`, ANDed with `rlsClause` when one applies, run through RunView so the user's own row
|
|
2471
|
+
* filters apply as well. Returns the matching keys in {@link canonicalKeyValues} form, or `null`
|
|
2472
|
+
* when the question could not be asked (no primary key, no usable record id, RunView failed) — the
|
|
2473
|
+
* caller fails closed.
|
|
2474
|
+
*/
|
|
2475
|
+
async readableRecordKeys(entity, recordIDs, rlsClause, contextUser) {
|
|
2476
|
+
const params = this.readableKeysParams(entity, recordIDs, rlsClause);
|
|
2477
|
+
if (!params)
|
|
2478
|
+
return null;
|
|
2479
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
2480
|
+
return this.readableKeySet(entity, await rv.RunView(params, contextUser));
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* The RunView behind {@link readableRecordKeys}, projecting only the key. `null` when it cannot be asked:
|
|
2484
|
+
* the entity has no primary key, or no record id names a key of it (both logged).
|
|
2485
|
+
*
|
|
2486
|
+
* `MaxRows` is the number of ids, since each matches at most one row: left unset, the entity's
|
|
2487
|
+
* `UserViewMaxRows` could truncate the answer and silently drop readable results.
|
|
2488
|
+
*/
|
|
2489
|
+
readableKeysParams(entity, recordIDs, rlsClause) {
|
|
1691
2490
|
const pkField = entity.FirstPrimaryKey; // first-pk-ok: presence check; Name is only used under the PrimaryKeys.length === 1 branch
|
|
1692
2491
|
if (!pkField) {
|
|
1693
2492
|
// Cannot verify without a primary key — exclude results
|
|
1694
2493
|
LogError(`SearchEngine: Entity "${entity.Name}" has no primary key, cannot verify result ownership`);
|
|
1695
|
-
return;
|
|
2494
|
+
return null;
|
|
1696
2495
|
}
|
|
1697
2496
|
// `RecordID` is a compact CompositeKey segment: the bare value for a single-column key, a
|
|
1698
2497
|
// "F1|v1||F2|v2" segment for a composite one. A single-column key is verified with one IN();
|
|
@@ -1700,40 +2499,393 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1700
2499
|
// alone could never match the segment, and this check fails closed, so every composite-key
|
|
1701
2500
|
// result would have been dropped as unauthorized.
|
|
1702
2501
|
const membership = entity.PrimaryKeys.length === 1
|
|
1703
|
-
? this.buildSingleKeyMembership(pkField.Name,
|
|
1704
|
-
: this.buildCompositeKeyMembership(entity,
|
|
2502
|
+
? this.buildSingleKeyMembership(entity, pkField.Name, recordIDs)
|
|
2503
|
+
: this.buildCompositeKeyMembership(entity, recordIDs);
|
|
2504
|
+
if (!membership)
|
|
2505
|
+
return null;
|
|
1705
2506
|
// Without a row filter this is a pure existence check against the entity's own view.
|
|
1706
2507
|
const filter = rlsClause ? `(${membership}) AND (${rlsClause})` : membership;
|
|
1707
|
-
|
|
1708
|
-
const result = await rv.RunView({
|
|
2508
|
+
return {
|
|
1709
2509
|
EntityName: entity.Name,
|
|
1710
2510
|
ExtraFilter: filter,
|
|
1711
2511
|
Fields: entity.PrimaryKeys.map(pk => pk.Name),
|
|
1712
|
-
ResultType: 'simple'
|
|
1713
|
-
|
|
1714
|
-
|
|
2512
|
+
ResultType: 'simple',
|
|
2513
|
+
MaxRows: recordIDs.length
|
|
2514
|
+
};
|
|
2515
|
+
}
|
|
2516
|
+
/** The keys a {@link readableKeysParams} RunView returned, in {@link canonicalKeyValues} form; `null` (logged) when it failed. */
|
|
2517
|
+
readableKeySet(entity, result) {
|
|
2518
|
+
if (!result?.Success) {
|
|
1715
2519
|
// RunView failed — fail closed, exclude all results
|
|
1716
|
-
LogError(`SearchEngine: ownership/RLS RunView failed for entity "${entity.Name}": ${result
|
|
1717
|
-
return;
|
|
2520
|
+
LogError(`SearchEngine: ownership/RLS RunView failed for entity "${entity.Name}": ${result?.ErrorMessage ?? 'unknown error'}`);
|
|
2521
|
+
return null;
|
|
1718
2522
|
}
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
2523
|
+
return new Set(result.Results.map(r => this.canonicalKeyValues(entity, CompositeKey.FromEntityRecord(entity, r))));
|
|
2524
|
+
}
|
|
2525
|
+
/**
|
|
2526
|
+
* `PK IN ('a','b',...)` — the fast path for the overwhelmingly common single-column key. Each id is
|
|
2527
|
+
* read as a key segment first, so a bare value and a prefixed `ID|value` segment (the encoding
|
|
2528
|
+
* `CompositeKey.ToRecordID()` writes) both compare on the value alone.
|
|
2529
|
+
*/
|
|
2530
|
+
buildSingleKeyMembership(entity, pkFieldName, recordIDs) {
|
|
2531
|
+
const values = recordIDs.map(id => {
|
|
2532
|
+
const key = CompositeKey.FromURLSegment(entity, id);
|
|
2533
|
+
return String(key.KeyValuePairs[0]?.Value ?? id);
|
|
2534
|
+
});
|
|
2535
|
+
const ids = values.map(v => `'${EscapeSQLString(v)}'`).join(',');
|
|
2536
|
+
return `${pkFieldName} IN (${ids})`;
|
|
2537
|
+
}
|
|
2538
|
+
/**
|
|
2539
|
+
* `(F1='v1' AND F2='v2') OR (...)` — one term per composite-key record. The field names come from the
|
|
2540
|
+
* record id, so only a segment {@link parseCompositeKey} accepts reaches the SQL, under the metadata's own
|
|
2541
|
+
* names; any other is dropped (logged). Empty when no segment is usable.
|
|
2542
|
+
*/
|
|
2543
|
+
buildCompositeKeyMembership(entity, recordIDs) {
|
|
2544
|
+
const terms = [];
|
|
2545
|
+
for (const id of recordIDs) {
|
|
2546
|
+
const key = this.parseCompositeKey(entity, id);
|
|
2547
|
+
if (key)
|
|
2548
|
+
terms.push(`(${key.ToWhereClause()})`);
|
|
2549
|
+
else
|
|
2550
|
+
LogError(`SearchEngine: record id "${id}" does not name the primary key of "${entity.Name}"; dropping it`);
|
|
2551
|
+
}
|
|
2552
|
+
return terms.join(' OR ');
|
|
2553
|
+
}
|
|
2554
|
+
/**
|
|
2555
|
+
* A composite-key segment rebuilt on `entity`'s own primary-key names, or `null` when it names a field that
|
|
2556
|
+
* is not a primary key of `entity` or leaves one out. Names match case-insensitively and are replaced by
|
|
2557
|
+
* the metadata's, so nothing parsed from a record id is interpolated into SQL as an identifier.
|
|
2558
|
+
*/
|
|
2559
|
+
parseCompositeKey(entity, recordID) {
|
|
2560
|
+
const pairs = CompositeKey.FromURLSegment(entity, recordID).KeyValuePairs;
|
|
2561
|
+
if (pairs.length !== entity.PrimaryKeys.length)
|
|
2562
|
+
return null;
|
|
2563
|
+
const rebuilt = [];
|
|
2564
|
+
for (const pk of entity.PrimaryKeys) {
|
|
2565
|
+
const match = pairs.find(kv => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
|
|
2566
|
+
if (!match)
|
|
2567
|
+
return null;
|
|
2568
|
+
rebuilt.push(new KeyValuePair(pk.Name, match.Value));
|
|
2569
|
+
}
|
|
2570
|
+
return CompositeKey.FromKeyValuePairs(rebuilt);
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* The {@link canonicalKeyValues} form of the key `recordID` names in `entity`, to match against the rows a
|
|
2574
|
+
* readability check returned. `null` for a composite-key segment {@link parseCompositeKey} rejects.
|
|
2575
|
+
*/
|
|
2576
|
+
recordMatchKey(entity, recordID) {
|
|
2577
|
+
if (entity.PrimaryKeys.length === 1)
|
|
2578
|
+
return this.canonicalKeyValues(entity, CompositeKey.FromURLSegment(entity, recordID));
|
|
2579
|
+
const key = this.parseCompositeKey(entity, recordID);
|
|
2580
|
+
return key ? this.canonicalKeyValues(entity, key) : null;
|
|
2581
|
+
}
|
|
2582
|
+
// ────────────────────────────────────────────────────────────────────────────────────────────
|
|
2583
|
+
// Origin records: a second gate for content derived from another MJ record
|
|
2584
|
+
// ────────────────────────────────────────────────────────────────────────────────────────────
|
|
2585
|
+
/**
|
|
2586
|
+
* Second gate, after a result is known to be a readable row of its own entity: may the user also
|
|
2587
|
+
* read the record the row was DERIVED from?
|
|
2588
|
+
*
|
|
2589
|
+
* Row-level security on a content entity settles who may read the content table. It cannot say
|
|
2590
|
+
* whether the person may read the file, task or conversation that content was extracted from —
|
|
2591
|
+
* that permission lives on the origin entity, under its own row filters. Without this gate, a
|
|
2592
|
+
* chunk of a document the user may not open passes the first gate and is quoted anyway.
|
|
2593
|
+
*
|
|
2594
|
+
* For `MJ: Content Items` and `MJ: Content Item Chunks` (and any IS-A subtype of either) the
|
|
2595
|
+
* default follows chunk → item (→ root item, for a split child) → `MJ: Entity Record Documents`
|
|
2596
|
+
* → the origin record, and keeps a result only when the origin is a row the user may read,
|
|
2597
|
+
* verified the way {@link verifyOwnershipAndRowFilters} verifies the result's own entity. A
|
|
2598
|
+
* content row with no Entity Record Document (crawled, uploaded, external) has no origin and
|
|
2599
|
+
* passes unchanged, as does every result of a non-content entity.
|
|
2600
|
+
*
|
|
2601
|
+
* Every lookup runs as the user, and that is a NEW requirement on who may see content hits: read on
|
|
2602
|
+
* the base `MJ: Content Items` for anyone who sees chunk hits (the chunk → item hop reads it), and read
|
|
2603
|
+
* on `MJ: Entity Record Documents` for anyone who sees hits derived from a record (the item → document
|
|
2604
|
+
* hop reads it). An app that indexes documents behind its own permissions grants those, under its
|
|
2605
|
+
* own row filters. Without them the affected rows are dropped: every row of the group for the chunk
|
|
2606
|
+
* and item hops, only the document-bearing rows for the document hop.
|
|
2607
|
+
*
|
|
2608
|
+
* The origin's own permissions are checked once; an origin that is itself a content row is not walked
|
|
2609
|
+
* again. Protected so a host can extend the rule to another derived-content family. Fails closed: a
|
|
2610
|
+
* lookup that reports failure, or returns a row without a column it asked for (field-level security),
|
|
2611
|
+
* drops the rows that depended on it; a lookup that throws drops the whole group. It never widens.
|
|
2612
|
+
*/
|
|
2613
|
+
async VerifyOriginRecords(entity, results, contextUser) {
|
|
2614
|
+
if (results.length === 0)
|
|
2615
|
+
return results;
|
|
2616
|
+
const level = this.contentFamilyLevel(entity);
|
|
2617
|
+
if (!level)
|
|
2618
|
+
return results;
|
|
2619
|
+
try {
|
|
2620
|
+
const origins = await this.resolveContentOrigins(entity, level, results, contextUser);
|
|
2621
|
+
return await this.keepReadableOrigins(entity, results, origins, contextUser);
|
|
2622
|
+
}
|
|
2623
|
+
catch (error) {
|
|
2624
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2625
|
+
LogError(`SearchEngine: origin-record check failed for entity "${entity.Name}": ${msg}`);
|
|
2626
|
+
return [];
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* Where `entity` sits in the content family: `'chunk'` for `MJ: Content Item Chunks` or a subtype,
|
|
2631
|
+
* `'item'` for `MJ: Content Items` or a subtype, `null` for anything else. Walks `ParentID` on the
|
|
2632
|
+
* request's provider; a cycle in the metadata ends the walk rather than looping.
|
|
2633
|
+
*/
|
|
2634
|
+
contentFamilyLevel(entity) {
|
|
2635
|
+
const provider = this.ProviderToUse;
|
|
2636
|
+
const visited = new Set();
|
|
2637
|
+
let current = entity;
|
|
2638
|
+
while (current && !visited.has(current.ID)) {
|
|
2639
|
+
if (current.Name === 'MJ: Content Item Chunks')
|
|
2640
|
+
return 'chunk';
|
|
2641
|
+
if (current.Name === 'MJ: Content Items')
|
|
2642
|
+
return 'item';
|
|
2643
|
+
visited.add(current.ID);
|
|
2644
|
+
current = current.ParentID ? provider.EntityByID(current.ParentID) : undefined;
|
|
2645
|
+
}
|
|
2646
|
+
return null;
|
|
2647
|
+
}
|
|
2648
|
+
/**
|
|
2649
|
+
* A content result's `RecordID` as the key value the origin lookups query and the origin map is keyed by.
|
|
2650
|
+
* Read as a key segment, exactly as gate 1 reads it, so a prefixed `ID|value` id resolves to its value.
|
|
2651
|
+
* Empty when the segment does not name the entity's key.
|
|
2652
|
+
*/
|
|
2653
|
+
contentRecordKey(entity, recordID) {
|
|
2654
|
+
// canonicalKeyValues of a single-column key is the NormalizeUUID'd value itself.
|
|
2655
|
+
const key = CompositeKey.FromURLSegment(entity, recordID);
|
|
2656
|
+
return this.canonicalKeyValues(entity, key); // first-pk-ok: the content family is single-column by design (IS-A subtypes share the base key)
|
|
2657
|
+
}
|
|
2658
|
+
/**
|
|
2659
|
+
* Resolve each result to its origin record. The returned map is keyed by {@link contentRecordKey}; a
|
|
2660
|
+
* value of `null` means "a content row with no origin" (it passes); a missing key means a link in the
|
|
2661
|
+
* chain could not be read as this user (it is dropped).
|
|
2662
|
+
*
|
|
2663
|
+
* Failures are scoped to the rows that depended on the failed hop. Every row depends on the chunk
|
|
2664
|
+
* and item hops, so a failed lookup there throws and the caller drops the group. Only split children
|
|
2665
|
+
* depend on the root hop, and only document-bearing items on the Entity Record Document hop, so a
|
|
2666
|
+
* failure there leaves just those rows unresolved and lets the rest through on their own merits.
|
|
2667
|
+
*/
|
|
2668
|
+
async resolveContentOrigins(entity, level, results, contextUser) {
|
|
2669
|
+
const recordIDs = Array.from(new Set(results.map(r => this.contentRecordKey(entity, r.RecordID)))).filter(id => id !== '');
|
|
2670
|
+
const itemOfRecord = level === 'chunk'
|
|
2671
|
+
? await this.lookupChunkItems(entity, recordIDs, contextUser)
|
|
2672
|
+
: new Map(recordIDs.map(id => [id, id]));
|
|
2673
|
+
const itemIDs = Array.from(new Set(itemOfRecord.values()));
|
|
2674
|
+
const erdOfItem = await this.lookupItemOrigins(itemIDs, contextUser);
|
|
2675
|
+
const erdIDs = Array.from(new Set(Array.from(erdOfItem.values()).filter((id) => id !== null)));
|
|
2676
|
+
const originOfErd = await this.lookupEntityRecordDocuments(erdIDs, contextUser);
|
|
2677
|
+
const origins = new Map();
|
|
2678
|
+
for (const id of recordIDs) {
|
|
2679
|
+
const itemID = itemOfRecord.get(id);
|
|
2680
|
+
if (itemID === undefined)
|
|
2681
|
+
continue; // the chunk is not a row the user can read
|
|
2682
|
+
const erdID = erdOfItem.get(itemID);
|
|
2683
|
+
if (erdID === undefined)
|
|
2684
|
+
continue; // the item (or its root) is not a row the user can read
|
|
2685
|
+
if (erdID === null) {
|
|
2686
|
+
origins.set(id, null);
|
|
2687
|
+
continue;
|
|
2688
|
+
} // external content: no origin
|
|
2689
|
+
const origin = originOfErd.get(erdID);
|
|
2690
|
+
if (origin)
|
|
2691
|
+
origins.set(id, origin); // else: the document is not readable → dropped
|
|
2692
|
+
}
|
|
2693
|
+
return origins;
|
|
2694
|
+
}
|
|
2695
|
+
/**
|
|
2696
|
+
* chunk id → owning Content Item id, read through the chunk entity's own view as the user. Every
|
|
2697
|
+
* chunk result depends on this hop, so a failed lookup throws and the group is dropped.
|
|
2698
|
+
*/
|
|
2699
|
+
async lookupChunkItems(entity, chunkIDs, contextUser) {
|
|
2700
|
+
const pkName = entity.FirstPrimaryKey.Name; // first-pk-ok: IS-A family shares the parent's single-column key
|
|
2701
|
+
const rows = await this.runLookup(entity.Name, [pkName, 'ContentItemID'], pkName, chunkIDs, contextUser);
|
|
2702
|
+
if (!rows)
|
|
2703
|
+
throw new Error(`lookup of "${entity.Name}" failed; every result depends on it`);
|
|
2704
|
+
const map = new Map();
|
|
2705
|
+
for (const row of rows) {
|
|
2706
|
+
const itemID = row['ContentItemID'];
|
|
2707
|
+
if (typeof row[pkName] === 'string' && typeof itemID === 'string') {
|
|
2708
|
+
map.set(NormalizeUUID(row[pkName]), NormalizeUUID(itemID));
|
|
1724
2709
|
}
|
|
1725
2710
|
}
|
|
2711
|
+
return map;
|
|
1726
2712
|
}
|
|
1727
|
-
/**
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
2713
|
+
/**
|
|
2714
|
+
* Content Item id → its Entity Record Document id, `null` when it has none.
|
|
2715
|
+
*
|
|
2716
|
+
* Always read through the base `MJ: Content Items`, whatever entity the result was labelled with:
|
|
2717
|
+
* `RootParentID` is a view-computed column, and an IS-A subtype's view projects only its parent's
|
|
2718
|
+
* base columns, so reading a subtype would silently lose the root link and let a split child
|
|
2719
|
+
* through as "no origin". The key is shared across the family, so the base view holds every row.
|
|
2720
|
+
*
|
|
2721
|
+
* A split child is judged by its own document first and by its root's only when it has none — one more
|
|
2722
|
+
* hop, taken once. A failed root lookup leaves only those children unresolved (dropped); a failed item
|
|
2723
|
+
* lookup throws, since every row depends on it.
|
|
2724
|
+
*/
|
|
2725
|
+
async lookupItemOrigins(itemIDs, contextUser) {
|
|
2726
|
+
const fields = ['ID', 'ParentID', 'RootParentID', 'EntityRecordDocumentID'];
|
|
2727
|
+
const rows = await this.runLookup('MJ: Content Items', fields, 'ID', itemIDs, contextUser);
|
|
2728
|
+
if (!rows)
|
|
2729
|
+
throw new Error('lookup of "MJ: Content Items" failed; every result depends on it');
|
|
2730
|
+
const map = new Map();
|
|
2731
|
+
const rootOfChild = this.classifyItemRows(rows, map);
|
|
2732
|
+
if (rootOfChild.size === 0)
|
|
2733
|
+
return map;
|
|
2734
|
+
const roots = Array.from(new Set(rootOfChild.values()));
|
|
2735
|
+
const rootRows = (await this.runLookup('MJ: Content Items', fields, 'ID', roots, contextUser)) ?? [];
|
|
2736
|
+
const docOfRoot = new Map(rootRows.map(r => [NormalizeUUID(r.ID), r.EntityRecordDocumentID ? NormalizeUUID(r.EntityRecordDocumentID) : null]));
|
|
2737
|
+
for (const [child, root] of rootOfChild) {
|
|
2738
|
+
const doc = docOfRoot.get(root);
|
|
2739
|
+
if (doc !== undefined)
|
|
2740
|
+
map.set(child, doc); // an unreadable root leaves the child unresolved → dropped
|
|
2741
|
+
}
|
|
2742
|
+
return map;
|
|
2743
|
+
}
|
|
2744
|
+
/**
|
|
2745
|
+
* Sort item rows: an item with its own document, or a root (no `ParentID`) with none, goes straight into
|
|
2746
|
+
* `map`; a split child with no document of its own is returned as child → root, to be judged by its root.
|
|
2747
|
+
* The view gives a root its own id as `RootParentID`, so a root is never re-read. A child whose
|
|
2748
|
+
* `RootParentID` is missing or names itself (the view could not walk its `ParentID` chain) goes nowhere:
|
|
2749
|
+
* unresolved, so dropped, rather than passed as "no origin".
|
|
2750
|
+
*/
|
|
2751
|
+
classifyItemRows(rows, map) {
|
|
2752
|
+
const rootOfChild = new Map();
|
|
2753
|
+
for (const row of rows) {
|
|
2754
|
+
const id = NormalizeUUID(row.ID);
|
|
2755
|
+
const root = row.RootParentID ? NormalizeUUID(row.RootParentID) : null;
|
|
2756
|
+
if (row.EntityRecordDocumentID)
|
|
2757
|
+
map.set(id, NormalizeUUID(row.EntityRecordDocumentID));
|
|
2758
|
+
else if (!row.ParentID)
|
|
2759
|
+
map.set(id, null); // a root with no document: no origin
|
|
2760
|
+
else if (root && root !== id)
|
|
2761
|
+
rootOfChild.set(id, root); // a split child: judged by its root
|
|
2762
|
+
else
|
|
2763
|
+
LogError(`SearchEngine: content item ${id} has a ParentID but no resolvable root; its hits are dropped`);
|
|
2764
|
+
}
|
|
2765
|
+
return rootOfChild;
|
|
1731
2766
|
}
|
|
1732
|
-
/**
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
2767
|
+
/**
|
|
2768
|
+
* Entity Record Document id → the (entity, record) it documents, read as the user. Only document-bearing
|
|
2769
|
+
* items depend on this hop, so a failed lookup resolves nothing here and drops those rows alone. A
|
|
2770
|
+
* document that names no entity or record resolves nothing either.
|
|
2771
|
+
*/
|
|
2772
|
+
async lookupEntityRecordDocuments(erdIDs, contextUser) {
|
|
2773
|
+
const map = new Map();
|
|
2774
|
+
if (erdIDs.length === 0)
|
|
2775
|
+
return map;
|
|
2776
|
+
const fields = ['ID', 'Entity', 'RecordID'];
|
|
2777
|
+
const rows = (await this.runLookup('MJ: Entity Record Documents', fields, 'ID', erdIDs, contextUser)) ?? [];
|
|
2778
|
+
for (const row of rows) {
|
|
2779
|
+
if (row.Entity && row.RecordID)
|
|
2780
|
+
map.set(NormalizeUUID(row.ID), { EntityName: row.Entity, RecordID: row.RecordID });
|
|
2781
|
+
}
|
|
2782
|
+
return map;
|
|
2783
|
+
}
|
|
2784
|
+
/**
|
|
2785
|
+
* One `Fields` projection of `entityName` where `keyField IN (ids)`, as the user. `null` (logged) when the
|
|
2786
|
+
* RunView fails, or when a row comes back without one of `fields`: field-level security drops a denied
|
|
2787
|
+
* column from the projection silently, and reading the absent column as null would turn "may not see the
|
|
2788
|
+
* link" into "has no origin" and let the hit through. The caller decides how far the failure reaches.
|
|
2789
|
+
* `MaxRows` is the number of ids (each matches at most one row), so `UserViewMaxRows` cannot truncate it.
|
|
2790
|
+
*/
|
|
2791
|
+
async runLookup(entityName, fields, keyField, ids, contextUser) {
|
|
2792
|
+
if (ids.length === 0)
|
|
2793
|
+
return [];
|
|
2794
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
2795
|
+
const result = await rv.RunView({
|
|
2796
|
+
EntityName: entityName,
|
|
2797
|
+
Fields: fields,
|
|
2798
|
+
ExtraFilter: `${keyField} IN (${ids.map(id => `'${EscapeSQLString(id)}'`).join(',')})`,
|
|
2799
|
+
ResultType: 'simple',
|
|
2800
|
+
MaxRows: ids.length
|
|
2801
|
+
}, contextUser);
|
|
2802
|
+
if (!result.Success) {
|
|
2803
|
+
LogError(`SearchEngine: origin lookup of "${entityName}" failed for user ${contextUser.ID}: ${result.ErrorMessage ?? 'unknown error'}`);
|
|
2804
|
+
return null;
|
|
2805
|
+
}
|
|
2806
|
+
const missing = fields.find(field => result.Results.some(row => !Object.prototype.hasOwnProperty.call(row, field)));
|
|
2807
|
+
if (missing) {
|
|
2808
|
+
LogError(`SearchEngine: origin lookup of "${entityName}" returned no "${missing}" column for user ${contextUser.ID} ` +
|
|
2809
|
+
'(denied by field-level security?); the rows that depend on it are dropped');
|
|
2810
|
+
return null;
|
|
2811
|
+
}
|
|
2812
|
+
return result.Results;
|
|
2813
|
+
}
|
|
2814
|
+
/**
|
|
2815
|
+
* Keep the results whose origin record the user may read. Origins are verified through
|
|
2816
|
+
* {@link ReadableOriginRecordIDs}: one batch, one view per origin entity.
|
|
2817
|
+
*/
|
|
2818
|
+
async keepReadableOrigins(entity, results, origins, contextUser) {
|
|
2819
|
+
const idsByEntity = new Map();
|
|
2820
|
+
for (const origin of origins.values()) {
|
|
2821
|
+
if (!origin)
|
|
2822
|
+
continue;
|
|
2823
|
+
const ids = idsByEntity.get(origin.EntityName) ?? new Set();
|
|
2824
|
+
ids.add(origin.RecordID);
|
|
2825
|
+
idsByEntity.set(origin.EntityName, ids);
|
|
2826
|
+
}
|
|
2827
|
+
const readable = await this.ReadableOriginRecordIDs(new Map(Array.from(idsByEntity, ([entityName, ids]) => [entityName, Array.from(ids)])), contextUser);
|
|
2828
|
+
return results.filter(r => {
|
|
2829
|
+
const origin = origins.get(this.contentRecordKey(entity, r.RecordID));
|
|
2830
|
+
if (origin === undefined)
|
|
2831
|
+
return false;
|
|
2832
|
+
if (origin === null)
|
|
2833
|
+
return true;
|
|
2834
|
+
return readable.get(origin.EntityName)?.has(origin.RecordID) ?? false;
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
2837
|
+
/**
|
|
2838
|
+
* For each origin entity, those of its record ids the user may read under that entity's own permissions and
|
|
2839
|
+
* row filters — the check {@link verifyOwnershipAndRowFilters} gives a result's own entity. All entities are
|
|
2840
|
+
* asked in one `RunViews` batch. An entity the provider does not know, the user may not read at all, or
|
|
2841
|
+
* whose view fails gets no entry, so only the rows derived from it are dropped.
|
|
2842
|
+
*
|
|
2843
|
+
* Protected so a host extending {@link VerifyOriginRecords} to another derived-content family can reuse it.
|
|
2844
|
+
*
|
|
2845
|
+
* @param idsByEntity origin entity name → record ids, each a bare key value or a key segment
|
|
2846
|
+
* @returns origin entity name → the ids (as given) of the rows the user may read
|
|
2847
|
+
*/
|
|
2848
|
+
async ReadableOriginRecordIDs(idsByEntity, contextUser) {
|
|
2849
|
+
const readable = new Map();
|
|
2850
|
+
const checks = this.originReadChecks(idsByEntity, contextUser);
|
|
2851
|
+
if (checks.length === 0)
|
|
2852
|
+
return readable;
|
|
2853
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
2854
|
+
const results = await rv.RunViews(checks.map(c => c.Params), contextUser);
|
|
2855
|
+
checks.forEach((check, i) => {
|
|
2856
|
+
const keys = this.readableKeySet(check.Entity, results[i]);
|
|
2857
|
+
if (!keys)
|
|
2858
|
+
return; // logged; only the rows derived from this entity are dropped
|
|
2859
|
+
readable.set(check.EntityName, new Set(check.RecordIDs.filter(id => {
|
|
2860
|
+
const key = this.recordMatchKey(check.Entity, id);
|
|
2861
|
+
return key !== null && keys.has(key);
|
|
2862
|
+
})));
|
|
2863
|
+
});
|
|
2864
|
+
return readable;
|
|
2865
|
+
}
|
|
2866
|
+
/** The readability view for each origin entity the user may read at all. The rest get none: not readable. */
|
|
2867
|
+
originReadChecks(idsByEntity, contextUser) {
|
|
2868
|
+
const checks = [];
|
|
2869
|
+
for (const [entityName, recordIDs] of idsByEntity) {
|
|
2870
|
+
let entity;
|
|
2871
|
+
try {
|
|
2872
|
+
entity = this.ProviderToUse.EntityByName(entityName);
|
|
2873
|
+
}
|
|
2874
|
+
catch {
|
|
2875
|
+
entity = undefined;
|
|
2876
|
+
}
|
|
2877
|
+
if (!entity) {
|
|
2878
|
+
LogError(`SearchEngine: origin entity "${entityName}" is not in metadata; the hits derived from it are dropped`);
|
|
2879
|
+
continue;
|
|
2880
|
+
}
|
|
2881
|
+
if (!entity.GetUserPermisions(contextUser)?.CanRead)
|
|
2882
|
+
continue;
|
|
2883
|
+
const rlsClause = entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, '') || undefined;
|
|
2884
|
+
const params = this.readableKeysParams(entity, recordIDs, rlsClause);
|
|
2885
|
+
if (params)
|
|
2886
|
+
checks.push({ EntityName: entityName, Entity: entity, RecordIDs: recordIDs, Params: params });
|
|
2887
|
+
}
|
|
2888
|
+
return checks;
|
|
1737
2889
|
}
|
|
1738
2890
|
/**
|
|
1739
2891
|
* Key values in primary-key metadata order, UUID-normalized and joined — the comparison form for
|