@memberjunction/generic-database-provider 6.1.5 → 6.1.7

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.
@@ -15,15 +15,15 @@
15
15
  *
16
16
  * @module @memberjunction/generic-database-provider
17
17
  */
18
- import { DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
- import { MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
18
+ import { BaseEntity, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
+ import { IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
20
20
  import { QueryPagingEngine } from './queryPagingEngine.js';
21
21
  // QueryParameterProcessor is now called internally by RenderPipeline
22
22
  import { createHash } from 'node:crypto';
23
23
  import { v4 as uuidv4 } from 'uuid';
24
24
  import { SqlLoggingSessionImpl } from './SqlLogger.js';
25
25
  import { GetDialect } from '@memberjunction/sql-dialect';
26
- import { SQLParser, IsReadOnlyQuery } from '@memberjunction/sql-parser';
26
+ import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
27
27
  // QueryCompositionEngine is now owned by RenderPipeline
28
28
  import { RenderPipeline } from './renderPipeline.js';
29
29
  import { useJsonArgShape } from './crudSprocFieldRules.js';
@@ -34,6 +34,7 @@ import { QueueManager } from '@memberjunction/queue';
34
34
  import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
35
35
  import { BuildEntityChangeContext } from '@memberjunction/actions-base';
36
36
  import { TransactionFrameTracker } from './TransactionFrameTracker.js';
37
+ import { ClientClauseScreen } from './clientClauseScreen.js';
37
38
  import { EncryptionEngine } from '@memberjunction/encryption';
38
39
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
39
40
  /**
@@ -1328,6 +1329,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1328
1329
  TransformExternalSQLClause(clause, _entityInfo) {
1329
1330
  return clause;
1330
1331
  }
1332
+ /**
1333
+ * Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
1334
+ * WhereClause) stays inside the parentheses this provider puts around it, read with this
1335
+ * provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
1336
+ * security, which also carries API-key row filters and guest scope; a piece that closes its
1337
+ * parentheses early, such as `1=1) OR (1=1`, would leave those filters on one side of an OR the
1338
+ * caller controls.
1339
+ */
1340
+ AssertClauseBalanced(clause, label, options) {
1341
+ const check = IsBalancedSQLFragment(clause, this.Dialect, options);
1342
+ if (!check.IsBalanced) {
1343
+ throw new Error(`Invalid ${label}: ${check.Reason}`);
1344
+ }
1345
+ }
1346
+ /**
1347
+ * Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
1348
+ * {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
1349
+ * top-level AND terms, each term is transformed, checked and parenthesized on its own. A
1350
+ * PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
1351
+ * runs before this transform, so a rewrite that changes the caller's term cannot reach the
1352
+ * hook's term.
1353
+ */
1354
+ PrepareExtraFilterSQL(extraFilter, entityInfo) {
1355
+ if (!extraFilter)
1356
+ return '';
1357
+ const transformed = this.TransformExternalSQLClause(extraFilter, entityInfo);
1358
+ const terms = transformed === extraFilter ? null : SplitTopLevelAndTerms(extraFilter, this.Dialect);
1359
+ if (!terms || terms.length < 2) {
1360
+ this.AssertClauseBalanced(transformed, 'ExtraFilter');
1361
+ return transformed;
1362
+ }
1363
+ return terms
1364
+ .map((term) => {
1365
+ const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
1366
+ this.AssertClauseBalanced(termSQL, 'ExtraFilter');
1367
+ return `(${termSQL})`;
1368
+ })
1369
+ .join(' AND ');
1370
+ }
1331
1371
  /**
1332
1372
  * Optionally wraps a view query with user view run logging.
1333
1373
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
@@ -1403,11 +1443,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1403
1443
  return externalResult;
1404
1444
  }
1405
1445
  // ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
1406
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
1446
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
1407
1447
  const userSearchString = params.UserSearchString ?? '';
1408
1448
  const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
1409
1449
  const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
1410
1450
  const saveViewResults = params.SaveViewResults ?? false;
1451
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
1452
+ this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
1411
1453
  // ── TOP / pagination mode ──
1412
1454
  // Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
1413
1455
  // and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
@@ -1468,18 +1510,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1468
1510
  // 1. View where clause
1469
1511
  if (viewEntity?.WhereClause && viewEntity.WhereClause.length > 0) {
1470
1512
  const renderedWhere = await this.RenderViewWhereClause(viewEntity, user);
1471
- // SECURITY: a stored view WhereClause originates from a client save, so pass the
1472
- // rendered clause through the same screen ExtraFilter gets. The one exemption is
1473
- // CustomWhereClause views: those are admin-authored (MJUserViewEntityServer's save
1474
- // gate restricts setting/changing them to Owner-type users) and may legitimately
1475
- // contain constructs the screen blocks. Auto-generated clauses (FilterState /
1476
- // SmartFilter / nested {%UserView%} templates) always pass — the screen permits
1477
- // plain SELECT subqueries and blocks only stacked statements, DML, comments,
1478
- // UNION and WAITFOR.
1513
+ // SECURITY: a stored view WhereClause originates from a client save, so the rendered
1514
+ // clause passes the full client-clause screen (ScreenStoredViewWhereClause) and the
1515
+ // keyword denylist ExtraFilter gets. The one exemption is CustomWhereClause views:
1516
+ // those are admin-authored (MJUserViewEntityServer's save gate restricts setting/
1517
+ // changing them to Owner-type users) and may legitimately contain constructs the
1518
+ // screens block. Auto-generated clauses (FilterState / SmartFilter / nested
1519
+ // {%UserView%} templates) are written against entity base views, which the screens
1520
+ // permit when the running user reads each of those entities unscoped.
1521
+ this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
1479
1522
  const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
1480
1523
  if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
1481
1524
  throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
1482
1525
  }
1526
+ // CustomWhereClause views too: an unbalanced clause would take row-level security
1527
+ // out of force for everyone who runs the view. Only their admin-written text may
1528
+ // carry comments.
1529
+ this.AssertClauseBalanced(renderedWhere, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
1530
+ AllowComments: isCustomWhereClause,
1531
+ });
1483
1532
  whereSQL = `(${renderedWhere})`;
1484
1533
  bHasWhere = true;
1485
1534
  }
@@ -1524,8 +1573,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1524
1573
  // first column's value with a prior run — refuse rather than return the wrong rows.
1525
1574
  this.assertSingleColumnPrimaryKey(entityInfo, 'ExcludeUserViewRunID / ExcludeDataFromAllPriorViewRuns');
1526
1575
  let sExcludeSQL = `${this.QuoteIdentifier(entityInfo.FirstPrimaryKey.Name)} NOT IN (SELECT RecordID FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwUserViewRunDetails')} WHERE EntityID='${viewEntity?.EntityID}' AND`; // first-pk-ok: guarded above — view-run RecordID is a single bare key value, PrimaryKeys.length === 1 enforced
1527
- if (params.ExcludeDataFromAllPriorViewRuns === true)
1576
+ if (params.ExcludeDataFromAllPriorViewRuns === true) {
1577
+ // SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
1578
+ if (!IsValidUUID(String(viewEntity?.ID ?? '')))
1579
+ throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
1528
1580
  sExcludeSQL += ` UserViewID=${viewEntity?.ID})`;
1581
+ }
1529
1582
  else {
1530
1583
  // SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
1531
1584
  // interpolated directly into SQL here. Unlike ExtraFilter/OrderBy/
@@ -1541,6 +1594,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1541
1594
  if (overrideExcludeFilter.length > 0) {
1542
1595
  if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
1543
1596
  throw new Error(`Invalid OverrideExcludeFilter: ${overrideExcludeFilter}, contains one more for forbidden keywords`);
1597
+ this.AssertClauseBalanced(overrideExcludeFilter, 'OverrideExcludeFilter');
1544
1598
  sExcludeSQL += ' OR (' + overrideExcludeFilter + ')';
1545
1599
  }
1546
1600
  whereSQL = bHasWhere ? `${whereSQL} AND (${sExcludeSQL})` : `(${sExcludeSQL})`;
@@ -1603,6 +1657,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1603
1657
  const orderBy = rawOrderBy.length > 0
1604
1658
  ? (usingKeyset || orderByIsPkFallback ? rawOrderBy : this.TransformExternalSQLClause(rawOrderBy, entityInfo))
1605
1659
  : '';
1660
+ if (orderBy.length > 0 && !usingKeyset && !orderByIsPkFallback) {
1661
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
1662
+ // No caller OrderBy means the sort came from the saved view's stored sort state.
1663
+ if (!params.OrderBy && viewEntity)
1664
+ this.ScreenStoredViewOrderBy(orderBy, user);
1665
+ }
1606
1666
  // View run logging (SQL Server-specific, others return null)
1607
1667
  let userViewRunID = '';
1608
1668
  if (viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user) {
@@ -1767,6 +1827,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1767
1827
  /**************************************************************************/
1768
1828
  // InternalRunView Helpers
1769
1829
  /**************************************************************************/
1830
+ /**
1831
+ * Builds the aggregate query without running the caller's text. Each expression must be a single
1832
+ * aggregate function call over this entity's columns: the query runs the SQL that
1833
+ * {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
1834
+ * dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
1835
+ * per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
1836
+ * request order, which is how `RunViewCore` reads their values back.
1837
+ */
1838
+ BuildAggregateSQL(aggregates, entityInfo, schemaName, baseView, whereSQL) {
1839
+ const columns = entityInfo.Fields.map((f) => f.Name);
1840
+ const items = [];
1841
+ const validationErrors = [];
1842
+ for (const agg of aggregates ?? []) {
1843
+ const screened = this.screenAggregateExpression(agg.expression, columns);
1844
+ if ('SQL' in screened) {
1845
+ items.push(`${screened.SQL} AS ${this.QuoteIdentifier(`Agg_${items.length}`)}`);
1846
+ }
1847
+ else {
1848
+ validationErrors.push({ expression: agg.expression, alias: agg.alias || agg.expression, value: null, error: screened.Error });
1849
+ }
1850
+ }
1851
+ if (items.length === 0)
1852
+ return { aggregateSQL: null, validationErrors };
1853
+ const where = whereSQL ? ` WHERE ${whereSQL}` : '';
1854
+ return { aggregateSQL: `SELECT ${items.join(', ')} FROM ${this.QuoteSchemaAndView(schemaName, baseView)}${where}`, validationErrors };
1855
+ }
1856
+ /** The SQL to run for one caller aggregate expression, or why it is refused. */
1857
+ screenAggregateExpression(expression, columns) {
1858
+ const check = CheckAggregateExpression(expression, this.Dialect, columns);
1859
+ if (!check.IsAllowed || check.SQL === null)
1860
+ return { Error: `Invalid aggregate expression: ${check.Reason}` };
1861
+ const keywordCheck = SQLExpressionValidator.Instance.validate(check.SQL, { context: 'aggregate', entityFields: columns });
1862
+ return keywordCheck.valid ? { SQL: check.SQL } : { Error: keywordCheck.error || 'Validation failed' };
1863
+ }
1770
1864
  /**
1771
1865
  * Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
1772
1866
  * the columns this user is allowed to read when field security denies them any.
@@ -1956,9 +2050,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1956
2050
  // Note this restores the pre-#4392 screen for this path; it does not close the
1957
2051
  // unquoted-format hole, which the denylist never covered (`1) OR 1=1` carries no
1958
2052
  // forbidden keyword). Quoting `{0}` in the format is what actually closes that.
1959
- if (this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields) && !this.ValidateUserProvidedSQLClause(userSearchString)) {
2053
+ //
2054
+ // The screen reads the quote-doubled term, because that is the text `{0}` becomes.
2055
+ if (this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields) && !this.ValidateUserProvidedSQLClause(safeUserSearchString)) {
1960
2056
  throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
1961
- `which splices the term directly into SQL, and the term contains forbidden keywords.`);
2057
+ `which splices the term directly into SQL, and the term is not allowed there: it contains ` +
2058
+ `a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
2059
+ `tokens, such as an unbalanced quote or bracket.`);
1962
2060
  }
1963
2061
  const escapedTerm = this.escapeLikeTerm(safeUserSearchString);
1964
2062
  for (const field of entityInfo.Fields) {
@@ -1976,6 +2074,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1976
2074
  if (sUserSearchSQL.length > 0)
1977
2075
  sUserSearchSQL = '(' + sUserSearchSQL + ')';
1978
2076
  }
2077
+ // A UserSearchParamFormatAPI format may splice the term outside quotes; the term must not end the statement there.
2078
+ this.AssertClauseFragmentIsSingleStatement(sUserSearchSQL, 'UserSearchString');
1979
2079
  return sUserSearchSQL;
1980
2080
  }
1981
2081
  /**
@@ -2075,6 +2175,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2075
2175
  return true;
2076
2176
  }
2077
2177
  /**************************************************************************/
2178
+ // Client clause screening
2179
+ /**************************************************************************/
2180
+ /**
2181
+ * SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
2182
+ * Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
2183
+ * fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
2184
+ */
2185
+ AssertClauseFragmentIsSingleStatement(clause, label) {
2186
+ ClientClauseScreen.AssertSingleStatementFragment(clause, label, this.Dialect);
2187
+ }
2188
+ /**
2189
+ * SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
2190
+ * against this provider's entities and dialect, with `contextUser` as the acting user. With
2191
+ * `entityInfo`, the clause is screened in the form this provider runs a client clause for that
2192
+ * entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
2193
+ * outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
2194
+ * saved-view save gate (`MJUserViewEntityServer`).
2195
+ */
2196
+ ScreenClientClause(clause, label, contextUser, entityInfo) {
2197
+ const text = clause && entityInfo ? this.TransformExternalSQLClause(clause, entityInfo) : clause;
2198
+ ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
2199
+ }
2200
+ /**
2201
+ * SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
2202
+ * Any user who can save a view can write its WhereClause, directly or through FilterState or a
2203
+ * Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
2204
+ * can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
2205
+ * request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
2206
+ * `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
2207
+ */
2208
+ ScreenStoredViewWhereClause(viewEntity, renderedWhere, user) {
2209
+ if (viewEntity instanceof BaseEntity && !!viewEntity.CustomWhereClause)
2210
+ return; // truthy — the DB may hand back true or 1
2211
+ this.AssertClauseFragmentIsSingleStatement(renderedWhere, 'view WhereClause');
2212
+ this.ScreenClientClause(renderedWhere, 'view WhereClause', user);
2213
+ }
2214
+ /**
2215
+ * SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
2216
+ * the full client-clause screen. Any user who can save a view can write those.
2217
+ */
2218
+ ScreenStoredViewOrderBy(orderBy, user) {
2219
+ this.ScreenClientClause(orderBy, 'OrderBy', user);
2220
+ }
2221
+ /**************************************************************************/
2078
2222
  // RenderViewWhereClause — View Template Rendering
2079
2223
  /**************************************************************************/
2080
2224
  /**
@@ -2487,7 +2631,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2487
2631
  async buildWhereClauseForCacheCheck(params, entityInfo, user) {
2488
2632
  let whereSQL = '';
2489
2633
  let bHasWhere = false;
2490
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
2634
+ // PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
2635
+ // check then runs on the result, as on the main view path.
2636
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
2637
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
2491
2638
  if (extraFilter.length > 0) {
2492
2639
  if (!this.ValidateUserProvidedSQLClause(extraFilter))
2493
2640
  throw new Error(`Invalid Extra Filter: ${extraFilter}`);
@@ -2884,6 +3031,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2884
3031
  if (orderBy.length > 0) {
2885
3032
  if (!this.ValidateUserProvidedSQLClause(orderBy))
2886
3033
  throw new Error(`Invalid OrderBy clause: ${orderBy}`);
3034
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
2887
3035
  sql += ` ORDER BY ${orderBy}`;
2888
3036
  }
2889
3037
  return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
@@ -3106,22 +3254,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3106
3254
  const promises = items.map(async ({ index, query }) => {
3107
3255
  try {
3108
3256
  const rows = await this.ExecuteSQL(query.CacheValidationSQL, undefined, undefined, contextUser);
3109
- if (rows && rows.length > 0) {
3110
- const row = rows[0];
3111
- results.set(index, {
3112
- success: true,
3113
- // Both spellings accepted. The shipped `CacheValidationSQL` field description tells authors
3114
- // to return `TotalRows`, while this has only ever read `RowCount` — so a query written
3115
- // from the documentation yields `Number(undefined)` = NaN, `NaN !== NaN` makes the slot
3116
- // never validate, and NaN is then written back into the client's cache entry where `??`
3117
- // cannot clear it. Silent, permanent degradation to always-refetch, with no error.
3118
- rowCount: Number(row['RowCount'] ?? row['TotalRows']),
3119
- maxUpdatedAt: row['MaxUpdatedAt'] ? new Date(String(row['MaxUpdatedAt'])).toISOString() : undefined,
3120
- });
3121
- }
3122
- else {
3123
- results.set(index, { success: true, rowCount: 0, maxUpdatedAt: undefined });
3124
- }
3257
+ results.set(index, this.QueryCacheStatusFromRow(rows?.[0]));
3125
3258
  }
3126
3259
  catch (e) {
3127
3260
  results.set(index, { success: false, errorMessage: e instanceof Error ? e.message : String(e) });
@@ -3130,6 +3263,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3130
3263
  await Promise.all(promises);
3131
3264
  return results;
3132
3265
  }
3266
+ /**
3267
+ * Reads the first row a query's CacheValidationSQL returned into a cache status. No row means
3268
+ * an empty result: zero rows, no timestamp.
3269
+ *
3270
+ * Both spellings of the count are accepted. The shipped `CacheValidationSQL` field description
3271
+ * tells authors to return `TotalRows`, while older queries return `RowCount`. Reading only one
3272
+ * of them yields `Number(undefined)` = NaN for the other, `NaN !== NaN` makes the slot never
3273
+ * validate, and NaN is then written back into the client's cache entry where `??` cannot clear
3274
+ * it: a silent, permanent degradation to always-refetch, with no error. Platform providers that
3275
+ * batch the validation SQL read their rows through this too.
3276
+ */
3277
+ QueryCacheStatusFromRow(row) {
3278
+ if (!row) {
3279
+ return { success: true, rowCount: 0, maxUpdatedAt: undefined };
3280
+ }
3281
+ const maxUpdatedAt = row['MaxUpdatedAt'];
3282
+ return {
3283
+ success: true,
3284
+ rowCount: Number(row['RowCount'] ?? row['TotalRows']),
3285
+ maxUpdatedAt: maxUpdatedAt
3286
+ ? (maxUpdatedAt instanceof Date ? maxUpdatedAt : new Date(String(maxUpdatedAt))).toISOString()
3287
+ : undefined,
3288
+ };
3289
+ }
3133
3290
  /**
3134
3291
  * Runs a full query and returns results with cache metadata.
3135
3292
  */
@@ -3658,7 +3815,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3658
3815
  async ExecuteAdhocQuery(params, contextUser) {
3659
3816
  try {
3660
3817
  const validator = SQLExpressionValidator.Instance;
3661
- const validation = validator.validateFullQuery(params.SQL);
3818
+ const validation = validator.validateFullQuery(params.SQL, this.PlatformKey);
3662
3819
  const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
3663
3820
  if (!validation.valid || !statementCheck.IsReadOnly) {
3664
3821
  return {
@@ -4254,6 +4411,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4254
4411
  /**
4255
4412
  * Checks whether a new record's field values pass the Create RLS filter.
4256
4413
  * Builds a synthetic single-row subquery from entity field values, then tests the RLS filter against it.
4414
+ * Null fields are projected as typed NULLs (see {@link BuildRLSSyntheticRowProjections}), so a
4415
+ * filter that references a column the new row leaves NULL evaluates instead of failing to bind.
4416
+ * The row is what the caller sends: a column the database fills on insert (a non-literal default
4417
+ * or a trigger) is seen as NULL here.
4257
4418
  */
4258
4419
  async CheckCreateRLS(entity, user) {
4259
4420
  const entityInfo = entity.EntityInfo;
@@ -4261,7 +4422,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4261
4422
  if (!rlsWhereClause || rlsWhereClause.length === 0) {
4262
4423
  return true;
4263
4424
  }
4264
- const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo, false);
4425
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
4265
4426
  const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
4266
4427
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
4267
4428
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
@@ -4294,7 +4455,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4294
4455
  return true; // pre-image check already passed and no filter-referenced column changed
4295
4456
  }
4296
4457
  }
4297
- const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo, true);
4458
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
4298
4459
  const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
4299
4460
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
4300
4461
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
@@ -4330,22 +4491,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4330
4491
  * Builds field projections for an RLS synthetic-row subquery (Create post-image and
4331
4492
  * Update post-image checks).
4332
4493
  *
4333
- * @param includeNulls - The Update post-image REQUIRES null fields to be projected as
4334
- * typed NULLs: a filter referencing a column the caller just nulled must see SQL NULL,
4335
- * not a missing column. A bare `SELECT NULL AS Col` is untyped and can evaluate
4336
- * differently from a real row, so nulls are emitted as `CAST(NULL AS <sqltype>)` using
4337
- * the field's metadata-resolved type. An unresolvable type fails the save (throw)
4338
- * rather than emitting an untyped NULL. The Create check keeps its historical
4339
- * skip-nulls behavior (includeNulls=false).
4340
- */
4341
- BuildRLSSyntheticRowProjections(entity, entityInfo, includeNulls) {
4494
+ * Every non-virtual field is projected, null fields included: a filter referencing a
4495
+ * column the row leaves NULL must see SQL NULL, not a missing column (which fails to
4496
+ * bind with `Invalid column name` instead of evaluating). A bare `SELECT NULL AS Col` is
4497
+ * untyped and can evaluate differently from a real row, so nulls are emitted as
4498
+ * `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
4499
+ * type fails the save (throw) rather than emitting an untyped NULL.
4500
+ */
4501
+ BuildRLSSyntheticRowProjections(entity, entityInfo) {
4342
4502
  const parts = [];
4343
4503
  for (const field of entityInfo.Fields) {
4344
4504
  if (field.IsVirtual)
4345
4505
  continue;
4346
4506
  const val = entity.Get(field.Name);
4347
- if (val == null && !includeNulls)
4348
- continue;
4349
4507
  parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
4350
4508
  }
4351
4509
  return parts.join(', ');
@@ -4374,7 +4532,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4374
4532
  // spot check and still emits `CAST(NULL AS nvarchar(50))` on the very next field.
4375
4533
  const baseType = field.Type;
4376
4534
  if (!baseType || baseType.trim().length === 0) {
4377
- throw new Error(`Cannot build RLS post-image projection: field ${field.Name} has no resolvable SQL type for a typed NULL`);
4535
+ throw new Error(`Cannot build RLS row projection: field ${field.Name} has no resolvable SQL type for a typed NULL`);
4378
4536
  }
4379
4537
  // `field.Length` is the SYSTEM (byte) length from `sys.columns`, but
4380
4538
  // `MapDataTypeToString` takes a CHARACTER count — `RuntimeSchemaManager` calls it as
@@ -4419,12 +4577,56 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4419
4577
  BuildParameterPlaceholder(index) {
4420
4578
  return `$${index + 1}`;
4421
4579
  }
4580
+ /**
4581
+ * Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
4582
+ * denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
4583
+ * that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
4584
+ * user checks: every authenticated client loads it to learn the schema, including principals
4585
+ * (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
4586
+ */
4587
+ resolveDatasetItemScope(datasetName, item, itemFilters, contextUser) {
4588
+ const code = String(item['Code']);
4589
+ const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
4590
+ const clientFilter = itemFilters?.find(f => f?.ItemCode === code)?.Filter ?? '';
4591
+ if (clientFilter && !this.ValidateUserProvidedSQLClause(clientFilter)) {
4592
+ return { Filter: '', RowFilter: '', Refusal: `Invalid ItemFilter for dataset item '${code}': contains one or more forbidden keywords` };
4593
+ }
4594
+ const filter = whereClause && clientFilter ? `${whereClause} AND (${clientFilter})` : (whereClause || clientFilter);
4595
+ if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
4596
+ return { Filter: filter, RowFilter: '', Refusal: null };
4597
+ }
4598
+ const entityName = String(item['Entity']);
4599
+ const entity = this.EntityByName(entityName);
4600
+ if (!entity) {
4601
+ return { Filter: filter, RowFilter: '', Refusal: `Entity '${entityName}' of dataset item '${code}' not found in metadata` };
4602
+ }
4603
+ if (!entity.GetUserPermisions(contextUser)?.CanRead) {
4604
+ return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
4605
+ }
4606
+ return { Filter: filter, RowFilter: entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
4607
+ }
4608
+ /**
4609
+ * The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
4610
+ * item's filter sits two parentheses deep because a client ItemFilter is screened inside one
4611
+ * level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
4612
+ */
4613
+ datasetItemWhereClause(scope) {
4614
+ if (!scope.RowFilter)
4615
+ return scope.Filter;
4616
+ if (!scope.Filter)
4617
+ return scope.RowFilter;
4618
+ return `(${scope.RowFilter}) AND ((${scope.Filter}))`;
4619
+ }
4422
4620
  /**
4423
4621
  * Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
4424
4622
  * and aggregating results. Uses dialect-neutral quoting for all SQL construction.
4425
4623
  *
4426
4624
  * ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
4427
4625
  * while PG (and the default) use parallel individual queries.
4626
+ *
4627
+ * An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
4628
+ * CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
4629
+ * item runs no SQL and fails the dataset.
4428
4630
  */
4429
4631
  async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
4430
4632
  const provider = (providerToUse ?? this);
@@ -4470,7 +4672,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4470
4672
  const code = String(item['Code']);
4471
4673
  const entityName = String(item['Entity']);
4472
4674
  const entityID = String(item['EntityID']);
4473
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
4474
4675
  // External-data-source entities have no MJ base view — their data is proxied live and
4475
4676
  // can't be served through the dataset's batched MJ-DB SQL path. Fail loud for that item
4476
4677
  // rather than silently querying a non-existent (or wrongly same-named) local view.
@@ -4487,19 +4688,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4487
4688
  });
4488
4689
  continue;
4489
4690
  }
4490
- // Build effective filter (WhereClause + optional runtime ItemFilter)
4491
- let effectiveFilter = whereClause;
4492
- if (itemFilters && itemFilters.length > 0) {
4493
- const filter = itemFilters.find(f => f.ItemCode === code);
4494
- if (filter) {
4495
- effectiveFilter = whereClause
4496
- ? `${whereClause} AND (${filter.Filter})`
4497
- : filter.Filter;
4498
- }
4691
+ // The item's filter and the caller's row filter, or why it is refused. A refused item
4692
+ // never reaches the cache or the database.
4693
+ const scope = provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser);
4694
+ if (scope.Refusal) {
4695
+ errorResults.push({
4696
+ EntityID: entityID,
4697
+ EntityName: entityName,
4698
+ Code: code,
4699
+ Results: [],
4700
+ LatestUpdateDate: undefined,
4701
+ Status: scope.Refusal,
4702
+ Success: false,
4703
+ });
4704
+ continue;
4499
4705
  }
4706
+ // The row filter keys the slot, so one user's filtered rows are never served to another.
4707
+ const rowFilterKey = scope.RowFilter || undefined;
4500
4708
  // Try cache first
4501
4709
  if (cacheAvailable) {
4502
- const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString, undefined, this.datasetCacheSegment(datasetName, code));
4710
+ const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code));
4503
4711
  const cached = await cache.GetRunViewResult(fingerprint);
4504
4712
  if (cached) {
4505
4713
  cacheHitCount++;
@@ -4531,12 +4739,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4531
4739
  });
4532
4740
  continue;
4533
4741
  }
4534
- const filterSQL = effectiveFilter ? 'WHERE ' + effectiveFilter : '';
4742
+ const whereSQL = this.datasetItemWhereClause(scope);
4743
+ const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
4535
4744
  uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
4536
4745
  uncachedItems.push(item);
4537
4746
  // Store fingerprint for write-through caching after SQL
4538
4747
  const fp = cacheAvailable
4539
- ? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString, undefined, this.datasetCacheSegment(datasetName, code))
4748
+ ? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
4540
4749
  : '';
4541
4750
  uncachedFingerprints.push(fp);
4542
4751
  }
@@ -4636,6 +4845,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4636
4845
  /**
4637
4846
  * Retrieves status information for a dataset by name: per-entity row count and
4638
4847
  * latest update date. Uses ExecuteSQLBatch for per-item status queries.
4848
+ *
4849
+ * Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
4850
+ * status fails with the refusal and no status SQL runs.
4639
4851
  */
4640
4852
  async GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse) {
4641
4853
  const overallStart = performance.now();
@@ -4673,33 +4885,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4673
4885
  // in GetDatasetByName.
4674
4886
  const updateDates = [];
4675
4887
  let overallLatestDate = new Date(1900, 1, 1);
4888
+ // Same scope as GetDatasetByName's data read — the stored item WhereClause, the caller's
4889
+ // ItemFilter and the caller's row filter — so status and data describe the same row set.
4890
+ // (Every shipped MJ_Metadata item has a NULL WhereClause and no row filter, so for
4891
+ // metadata this is an unfiltered aggregate.)
4892
+ const scopes = items.map(item => provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser));
4893
+ const refusal = scopes.find(scope => scope.Refusal)?.Refusal;
4894
+ if (refusal) {
4895
+ return {
4896
+ DatasetID: String(items[0]['DatasetID']),
4897
+ DatasetName: datasetName,
4898
+ Success: false,
4899
+ Status: refusal,
4900
+ LatestUpdateDate: new Date(0),
4901
+ EntityUpdateDates: [],
4902
+ };
4903
+ }
4676
4904
  const itemMeta = [];
4677
- const queries = items.map((item) => {
4905
+ const queries = items.map((item, index) => {
4678
4906
  const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
4679
4907
  const entityBaseView = String(item['EntityBaseView']);
4680
- const code = String(item['Code']);
4681
4908
  const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
4682
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
4683
4909
  itemMeta.push({ entityID: String(item['EntityID']), entityName: String(item['Entity']) });
4684
4910
  // The floor for the reported timestamp: an edit to the dataset DEFINITION itself
4685
4911
  // (item added, filter changed) must read as a change even when no entity row moved.
4686
4912
  const itemUpdatedAt = new Date(String(item['DatasetItemUpdatedAt']));
4687
4913
  const datasetUpdatedAt = new Date(String(item['DatasetUpdatedAt']));
4688
4914
  const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime())).toISOString();
4689
- // Same filter composition as GetDatasetByName's data read — the stored item
4690
- // WhereClause AND'd with any runtime filter — so status and data describe the same
4691
- // row set. (Every shipped MJ_Metadata item has a NULL WhereClause, so for metadata
4692
- // this is identical to an unfiltered aggregate.)
4693
- let effectiveFilter = whereClause;
4694
- if (itemFilters && itemFilters.length > 0) {
4695
- const filter = itemFilters.find(f => f.ItemCode === code);
4696
- if (filter) {
4697
- effectiveFilter = whereClause
4698
- ? `${whereClause} AND (${filter.Filter})`
4699
- : filter.Filter;
4700
- }
4701
- }
4702
- const filterSQL = effectiveFilter ? ' WHERE ' + effectiveFilter : '';
4915
+ const whereSQL = this.datasetItemWhereClause(scopes[index]);
4916
+ const filterSQL = whereSQL ? ' WHERE ' + whereSQL : '';
4703
4917
  return `SELECT ` +
4704
4918
  `CASE ` +
4705
4919
  `WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +