dynamo-bao 0.8.2 → 0.9.0

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.
@@ -25,6 +25,16 @@ const SYSTEM_FILTERABLE_FIELDS = {
25
25
  },
26
26
  };
27
27
 
28
+ // Deep nesting is never needed in practice and would otherwise let a
29
+ // forwarded filter overflow the stack.
30
+ const MAX_FILTER_DEPTH = 16;
31
+
32
+ // Filter keys are often user input, so look fields up as own properties only;
33
+ // keys like "constructor" or "__proto__" must not resolve through prototypes.
34
+ function lookupOwn(obj, key) {
35
+ return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
36
+ }
37
+
28
38
  /**
29
39
  * Supporting class for building DynamoDB filter expressions.
30
40
  * @class
@@ -42,27 +52,28 @@ class FilterExpressionBuilder {
42
52
  this.valueCount = 0;
43
53
  }
44
54
 
45
- // Generate unique name placeholder
55
+ // Placeholders use a "__" prefix: user field names can't start with "_",
56
+ // so these never collide with the "#field"/":field" update placeholders
57
+ // they get merged with in conditional writes.
46
58
  generateName(fieldName) {
47
- const key = `#n${++this.nameCount}`;
59
+ const key = `#__f${++this.nameCount}`;
48
60
  this.names[key] = fieldName;
49
61
  return key;
50
62
  }
51
63
 
52
- // Generate unique value placeholder
53
64
  generateValue(value) {
54
- const key = `:v${++this.valueCount}`;
65
+ const key = `:__f${++this.valueCount}`;
55
66
  this.values[key] = value;
56
67
  return key;
57
68
  }
58
69
 
59
70
  // Simplified value conversion - let the field handle it
60
71
  convertValue(value, model, fieldName) {
61
- const systemField = SYSTEM_FILTERABLE_FIELDS[fieldName];
72
+ const systemField = lookupOwn(SYSTEM_FILTERABLE_FIELDS, fieldName);
62
73
  if (systemField) {
63
74
  return systemField.convertValue(value, model);
64
75
  }
65
- const field = model.fields[fieldName];
76
+ const field = lookupOwn(model.fields, fieldName);
66
77
  return field.toDy(value);
67
78
  }
68
79
 
@@ -214,7 +225,7 @@ class FilterExpressionBuilder {
214
225
  expressions.push(this.buildLogicalExpression(key, value, model));
215
226
  } else if (key === "$not") {
216
227
  const innerExpr = this.buildFilterExpression(value, model);
217
- expressions.push(`NOT ${innerExpr}`);
228
+ expressions.push(`NOT (${innerExpr})`);
218
229
  } else {
219
230
  expressions.push(this.buildFieldExpression(key, value, model));
220
231
  }
@@ -235,6 +246,10 @@ class FilterExpressionBuilder {
235
246
  * - $or: [{condition1}, {condition2}] - At least one condition must match
236
247
  * - $not: {condition} - Condition must not match
237
248
  * @param {BaoModel} model - The model to build the expression for. Used to validate field names.
249
+ * @param {Object} [options]
250
+ * @param {string[]} [options.allowedFields] - When set, the filter may only reference
251
+ * these fields. Pass this whenever the filter comes from user input, so callers
252
+ * can't probe fields they shouldn't see.
238
253
  * @example
239
254
  * filterExp1 = {
240
255
  * status: 'active', // Exact match
@@ -264,9 +279,9 @@ class FilterExpressionBuilder {
264
279
  * - ExpressionAttributeNames: Map of attribute name placeholders
265
280
  * - ExpressionAttributeValues: Map of attribute value placeholders
266
281
  */
267
- build(filter, model) {
282
+ build(filter, model, options = {}) {
268
283
  // Validate field names against model
269
- this.validateFields(filter, model);
284
+ this.validateFields(filter, model, options);
270
285
 
271
286
  const filterExpression = this.buildFilterExpression(filter, model);
272
287
 
@@ -282,27 +297,41 @@ class FilterExpressionBuilder {
282
297
  }
283
298
 
284
299
  // Validate fields against model definition
285
- validateFields(filter, model) {
286
- const validateObject = (obj) => {
300
+ validateFields(filter, model, { allowedFields } = {}) {
301
+ const validateObject = (obj, depth) => {
302
+ if (depth > MAX_FILTER_DEPTH) {
303
+ throw new QueryError(
304
+ `Filter is nested more than ${MAX_FILTER_DEPTH} levels deep`,
305
+ );
306
+ }
307
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
308
+ throw new QueryError("Filter conditions must be objects");
309
+ }
287
310
  for (const [key, value] of Object.entries(obj)) {
288
311
  // Skip logical operators
289
312
  if (["$and", "$or", "$not"].includes(key)) {
290
- if (Array.isArray(value)) {
291
- value.forEach(validateObject);
313
+ if (key === "$not") {
314
+ validateObject(value, depth + 1);
315
+ } else if (Array.isArray(value)) {
316
+ value.forEach((condition) => validateObject(condition, depth + 1));
292
317
  } else {
293
- validateObject(value);
318
+ throw new QueryError(`${key} requires an array of conditions`);
294
319
  }
295
320
  continue;
296
321
  }
297
322
 
323
+ if (allowedFields && !allowedFields.includes(key)) {
324
+ throw new QueryError(`Field not allowed in filter: ${key}`);
325
+ }
326
+
298
327
  // Allow whitelisted system fields (e.g., _searchText) without
299
328
  // requiring a matching entry in model.fields. Operator validation
300
329
  // below still runs so bad operators are rejected the same way.
301
- const isSystemField = !!SYSTEM_FILTERABLE_FIELDS[key];
330
+ const isSystemField = !!lookupOwn(SYSTEM_FILTERABLE_FIELDS, key);
302
331
 
303
332
  if (!isSystemField) {
304
333
  // Validate field exists in model
305
- const field = model.fields[key];
334
+ const field = lookupOwn(model.fields, key);
306
335
  if (!field) {
307
336
  throw new QueryError(`Unknown field in filter: ${key}`);
308
337
  }
@@ -338,7 +367,7 @@ class FilterExpressionBuilder {
338
367
  }
339
368
  };
340
369
 
341
- validateObject(filter);
370
+ validateObject(filter, 0);
342
371
  }
343
372
  }
344
373
 
package/src/index.js CHANGED
@@ -183,9 +183,10 @@ function initModels(userConfig = {}) {
183
183
  models: userConfig.models || config.models || null,
184
184
  };
185
185
 
186
- // Validate tenant context if tenancy enabled
187
- if (finalConfig.tenancy?.enabled) {
188
- TenantContext.validateTenantRequired(finalConfig);
186
+ // The logger is created at import, before this config exists. The
187
+ // environment variable still wins, as it does at import.
188
+ if (finalConfig.logging?.level && !process.env.DYNAMO_BAO_LOG_LEVEL) {
189
+ logger.currentLevel = finalConfig.logging.level.toUpperCase();
189
190
  }
190
191
 
191
192
  const modelsDir = finalConfig.paths.modelsDir;
@@ -18,13 +18,13 @@ class KeyConditionBuilder {
18
18
  }
19
19
 
20
20
  generateName(fieldName) {
21
- const key = `#n${++this.nameCount}`;
21
+ const key = `#__k${++this.nameCount}`;
22
22
  this.names[key] = fieldName;
23
23
  return key;
24
24
  }
25
25
 
26
26
  generateValue(value) {
27
- const key = `:v${++this.valueCount}`;
27
+ const key = `:__k${++this.valueCount}`;
28
28
  this.values[key] = value;
29
29
  return key;
30
30
  }
@@ -716,14 +716,22 @@ function runWithBatchContext(fn) {
716
716
  timers: new Set(),
717
717
  startTime: Date.now(),
718
718
  capacityAccumulator: { read: 0, write: 0 }, // Track total capacity consumed
719
+ // A tenant set with setCurrentTenant() inside a batch context lives here,
720
+ // scoped to the request. Nested contexts inherit it.
721
+ tenantId: batchContext.getStore()?.tenantId ?? null,
719
722
  };
720
723
 
721
724
  return batchContext.run(context, fn);
722
725
  }
723
726
 
727
+ function getBatchContextStore() {
728
+ return batchContext?.getStore() ?? null;
729
+ }
730
+
724
731
  module.exports = {
725
732
  BatchLoadingMethods,
726
733
  runWithBatchContext,
734
+ getBatchContextStore,
727
735
  getBatchContextCapacity,
728
736
  _accumulateCapacityToContext,
729
737
  BATCH_REQUEST_TIMEOUT,
@@ -8,6 +8,7 @@ const {
8
8
  const { defaultLogger: logger } = require("../utils/logger");
9
9
  const { pluginManager } = require("../plugin-manager");
10
10
  const { retryOperation } = require("../utils/retry-helper");
11
+ const { ulid } = require("ulid");
11
12
  const assert = require("assert");
12
13
  const { FilterExpressionBuilder } = require("../filter-expression");
13
14
  const {
@@ -16,7 +17,7 @@ const {
16
17
  ValidationError,
17
18
  } = require("../exceptions");
18
19
  const { computeSearchTextUpdate } = require("../utils/search-text");
19
- const { SEARCH_TEXT_FIELD } = require("../constants");
20
+ const { SEARCH_TEXT_FIELD, GID_SEPARATOR } = require("../constants");
20
21
 
21
22
  /**
22
23
  * AND a guard onto an optional ConditionExpression. The existing expression
@@ -222,10 +223,14 @@ const MutationMethods = {
222
223
  }
223
224
  }
224
225
 
226
+ // The token makes a retry after a lost response a no-op instead of
227
+ // applying the transaction twice.
228
+ const clientRequestToken = ulid();
225
229
  response = await retryOperation(() =>
226
230
  this.documentClient.send(
227
231
  new TransactWriteCommand({
228
232
  TransactItems: transactItems,
233
+ ClientRequestToken: clientRequestToken,
229
234
  ReturnConsumedCapacity: "TOTAL",
230
235
  }),
231
236
  ),
@@ -324,7 +329,7 @@ const MutationMethods = {
324
329
  /**
325
330
  * AND an `attribute_exists(_pk)` guard into a write's ConditionExpression.
326
331
  * Uses a "#__" placeholder so it can't clobber a field placeholder (user
327
- * field names can't start with "_"; filter placeholders are "#nN").
332
+ * field names can't start with "_"; filter placeholders are "#__fN").
328
333
  * @private
329
334
  */
330
335
  _addExistsGuard(params) {
@@ -486,11 +491,48 @@ const MutationMethods = {
486
491
  return { relocated: true, from: sourceKey._pk, to: canonicalKey._pk };
487
492
  },
488
493
 
494
+ /**
495
+ * An update can't move a row to a different key, so reject a change to any
496
+ * field the primary key is built from. Re-sending the current value is fine.
497
+ * @private
498
+ */
499
+ _assertPrimaryKeyUnchanged(primaryId, jsUpdates) {
500
+ const current = this._parsePrimaryId(primaryId);
501
+ for (const [part, fieldName] of [
502
+ ["pk", this.primaryKey.pk],
503
+ ["sk", this.primaryKey.sk],
504
+ ]) {
505
+ if (
506
+ !fieldName ||
507
+ fieldName === "modelPrefix" ||
508
+ jsUpdates[fieldName] === undefined
509
+ ) {
510
+ continue;
511
+ }
512
+ const field = this._getField(fieldName);
513
+ if (String(field.toGsi(jsUpdates[fieldName])) !== String(current[part])) {
514
+ throw new ValidationError(
515
+ `Cannot change primary key field ${fieldName} on update`,
516
+ );
517
+ }
518
+ }
519
+ },
520
+
489
521
  _createNewPrimaryId(jsUpdates) {
490
522
  // Now calculate primary key values using the processed data
491
523
  const pkValue = this._getPkValue(jsUpdates);
492
524
  const skValue = this._getSkValue(jsUpdates);
493
525
 
526
+ // The primary id joins pk and sk with GID_SEPARATOR, so a key value that
527
+ // contains it would parse back to a different record's key.
528
+ for (const value of [pkValue, skValue]) {
529
+ if (typeof value === "string" && value.includes(GID_SEPARATOR)) {
530
+ throw new ValidationError(
531
+ `Primary key values cannot contain "${GID_SEPARATOR}"`,
532
+ );
533
+ }
534
+ }
535
+
494
536
  // Format the primary key
495
537
  const pk = this._formatPrimaryKey(this.modelPrefix, pkValue);
496
538
  const primaryId = this.getPrimaryId({
@@ -535,8 +577,16 @@ const MutationMethods = {
535
577
 
536
578
  logger.debug("jsUpdates", jsUpdates);
537
579
 
580
+ if (!isNew) {
581
+ this._assertPrimaryKeyUnchanged(primaryId, jsUpdates);
582
+ }
583
+
538
584
  // Generate Dynamo Updates to save
539
585
  for (const [key, field] of Object.entries(this.fields)) {
586
+ if (field.serverGenerated || (!isNew && field.immutable)) {
587
+ delete jsUpdates[key];
588
+ }
589
+
540
590
  if (isNew && jsUpdates[key] === undefined) {
541
591
  // Only set initial values during creation
542
592
  const initialValue = field.getInitialValue();
@@ -589,7 +639,10 @@ const MutationMethods = {
589
639
  // the loaded value plus the delta, guarded on the loaded value, so a
590
640
  // concurrent change fails the update (ConditionalError) instead of
591
641
  // leaving the index key stale. Other counters keep the atomic ADD.
592
- const counterGuards = [];
642
+ // Fields whose stored value must still equal the loaded value for the
643
+ // write to apply. Filled for index-key counters here and for unchanged
644
+ // unique values below.
645
+ const loadedValueGuards = [];
593
646
  const { CounterFieldClass } = require("../fields");
594
647
  for (const [key, field] of Object.entries(this.fields)) {
595
648
  const dyValue = dyUpdatesToSave[key];
@@ -612,7 +665,7 @@ const MutationMethods = {
612
665
  ) {
613
666
  const loadedValue = currentItem._loadedDyData[key];
614
667
  value = Number(loadedValue ?? 0) + delta;
615
- counterGuards.push({ fieldName: key, loadedValue });
668
+ loadedValueGuards.push({ fieldName: key, loadedValue });
616
669
  } else {
617
670
  continue;
618
671
  }
@@ -728,6 +781,15 @@ const MutationMethods = {
728
781
  ),
729
782
  );
730
783
  }
784
+ } else if (dyNewValue !== undefined && currentItem) {
785
+ // Re-sending the unchanged value writes no constraint rows, so guard
786
+ // the update on the stored value: if a concurrent update moved this
787
+ // record off the value (releasing its constraint), this write must
788
+ // not set it back without owning the constraint.
789
+ loadedValueGuards.push({
790
+ fieldName,
791
+ loadedValue: dyCurrentValue,
792
+ });
731
793
  }
732
794
  }
733
795
 
@@ -870,9 +932,9 @@ const MutationMethods = {
870
932
  );
871
933
  }
872
934
 
873
- for (const { fieldName, loadedValue } of counterGuards) {
874
- const name = `#__counterGuard_${fieldName}`;
875
- const value = `:__counterGuard_${fieldName}`;
935
+ for (const { fieldName, loadedValue } of loadedValueGuards) {
936
+ const name = `#__loadedGuard_${fieldName}`;
937
+ const value = `:__loadedGuard_${fieldName}`;
876
938
  updateParams.ExpressionAttributeNames = {
877
939
  ...updateParams.ExpressionAttributeNames,
878
940
  [name]: fieldName,
@@ -907,10 +969,14 @@ const MutationMethods = {
907
969
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
908
970
  }
909
971
 
972
+ // The token makes a retry after a lost response a no-op instead of
973
+ // applying the transaction twice.
974
+ const clientRequestToken = ulid();
910
975
  response = await retryOperation(() =>
911
976
  this.documentClient.send(
912
977
  new TransactWriteCommand({
913
978
  TransactItems: transactItems,
979
+ ClientRequestToken: clientRequestToken,
914
980
  ReturnConsumedCapacity: "TOTAL",
915
981
  }),
916
982
  ),
@@ -980,14 +1046,18 @@ const MutationMethods = {
980
1046
  logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
981
1047
  }
982
1048
 
983
- response = await retryOperation(() =>
1049
+ // ADD isn't idempotent: if a request times out after DynamoDB applied
1050
+ // it, a retry would apply it again. Only retry pure SET/REMOVE writes.
1051
+ const sendUpdate = () =>
984
1052
  this.documentClient.send(
985
1053
  new UpdateCommand({
986
1054
  ...updateParams,
987
1055
  ReturnConsumedCapacity: "TOTAL",
988
1056
  }),
989
- ),
990
- );
1057
+ );
1058
+ response = hasAtomicOps
1059
+ ? await sendUpdate()
1060
+ : await retryOperation(sendUpdate);
991
1061
 
992
1062
  const savedItem = this._createFromDyItem(response.Attributes);
993
1063
  logger.debug("savedItem", savedItem);
@@ -102,6 +102,7 @@ const QueryMethods = {
102
102
  * @param {Object} options.startKey - Exclusive start key for pagination
103
103
  * @param {boolean} options.countOnly - If true, returns only the count of matching items
104
104
  * @param {Object} options.filter - Additional filter conditions for the query. For full filter syntax, see {@link FilterExpressionBuilder#build}
105
+ * @param {string[]} options.allowedFilterFields - Fields `filter` may reference. Set this when the filter comes from user input.
105
106
  * @param {boolean} options.returnWrapped - If false, returns raw DynamoDB items instead of model instances
106
107
  * @param {boolean} options.loadRelated - If true, loads related models for RelatedFields
107
108
  * @param {string[]} options.relatedFields - Array of field names to load related data for (used with loadRelated)
@@ -268,7 +269,9 @@ const QueryMethods = {
268
269
  // Add filter expression if provided
269
270
  if (options.filter) {
270
271
  const filterBuilder = new FilterExpressionBuilder();
271
- const filterExpression = filterBuilder.build(options.filter, this);
272
+ const filterExpression = filterBuilder.build(options.filter, this, {
273
+ allowedFields: options.allowedFilterFields,
274
+ });
272
275
 
273
276
  if (filterExpression) {
274
277
  params.FilterExpression = filterExpression.FilterExpression;
@@ -63,7 +63,7 @@ const UniqueConstraintMethods = {
63
63
  if (innerError instanceof ConditionalError) {
64
64
  throw innerError;
65
65
  }
66
- console.error("Error checking unique constraint:", innerError);
66
+ logger.error("Error checking unique constraint:", innerError);
67
67
  throw new ConditionalError(
68
68
  `Failed to validate ${constraint.field} uniqueness`,
69
69
  "unique_constraint",
@@ -5,6 +5,9 @@ const { ConfigurationError } = require("./exceptions");
5
5
 
6
6
  class ModelManager {
7
7
  static _instances = new Map();
8
+ // The most recently initialized manager. Runtime tenants borrow its models,
9
+ // client and config through forTenant().
10
+ static _primary = null;
8
11
 
9
12
  constructor(config = {}) {
10
13
  this._initialized = false;
@@ -26,11 +29,36 @@ class ModelManager {
26
29
  return ModelManager._instances.get(key);
27
30
  }
28
31
 
29
- async init(config = {}) {
30
- // Validate tenant requirement
31
- const { TenantContext } = require("./tenant-context");
32
- TenantContext.validateTenantRequired(config);
32
+ /**
33
+ * Returns the manager to use for a tenant at request time. A manager that
34
+ * was explicitly initialized for this tenant wins; otherwise this returns a
35
+ * lightweight view of the primary manager with the tenant id swapped in.
36
+ * Views are not cached, so arbitrary tenant ids don't grow memory.
37
+ */
38
+ static forTenant(tenantId) {
39
+ // Keys are built as "[tenant]#prefix#value", so a tenant id containing
40
+ // "]" or "#" could produce another tenant's keys.
41
+ if (
42
+ tenantId != null &&
43
+ (typeof tenantId !== "string" || /[\]#]/.test(tenantId))
44
+ ) {
45
+ throw new ConfigurationError(
46
+ `Invalid tenant id ${JSON.stringify(tenantId)}: must be a string without "]" or "#"`,
47
+ );
48
+ }
49
+ const existing = ModelManager._instances.get(tenantId || "default");
50
+ if (existing) {
51
+ return existing;
52
+ }
53
+ if (!ModelManager._primary) {
54
+ return ModelManager.getInstance(tenantId);
55
+ }
56
+ const view = Object.create(ModelManager._primary);
57
+ view._tenantId = tenantId;
58
+ return view;
59
+ }
33
60
 
61
+ async init(config = {}) {
34
62
  // Store config for models to access
35
63
  this._config = config;
36
64
 
@@ -55,6 +83,7 @@ class ModelManager {
55
83
  }
56
84
 
57
85
  this._initialized = true;
86
+ ModelManager._primary = this;
58
87
  return this;
59
88
  }
60
89
 
package/src/model.js CHANGED
@@ -28,8 +28,6 @@ const {
28
28
  UniqueConstraintConfig: UniqueConstraintConfigClass,
29
29
  } = require("./model-config");
30
30
 
31
- const GID_SEPARATOR = "##__SK__##";
32
-
33
31
  // Passed to the constructor by _createFromDyItem: the instance is about to
34
32
  // take its data from a stored row, so skip computing initial field values
35
33
  // (which for auto-assigned ULID and version fields means generating ids
@@ -51,6 +49,7 @@ const {
51
49
  ITERATION_PK_FIELD,
52
50
  ITERATION_SK_FIELD,
53
51
  SEARCH_TEXT_FIELD,
52
+ GID_SEPARATOR,
54
53
  } = require("./constants");
55
54
  const {
56
55
  ConfigurationError,
@@ -115,7 +114,17 @@ class BaoModel {
115
114
  static get manager() {
116
115
  const { TenantContext } = require("./tenant-context");
117
116
  const tenantId = TenantContext.getCurrentTenant();
118
- return ModelManager.getInstance(tenantId || this._tenantId);
117
+ if (tenantId) {
118
+ return ModelManager.forTenant(tenantId);
119
+ }
120
+ // Fail closed: never fall back to the tenant that was current at init.
121
+ if (this._config?.tenancy?.enabled) {
122
+ throw new ConfigurationError(
123
+ `No tenant in context for ${this.name}. Wrap the operation in ` +
124
+ "TenantContext.runWithTenant(tenantId, fn) or register a resolver.",
125
+ );
126
+ }
127
+ return ModelManager.getInstance(this._tenantId);
119
128
  }
120
129
 
121
130
  static _getField(fieldName) {
@@ -352,6 +361,8 @@ class BaoModel {
352
361
  * and so the upper bound on each yielded batch.
353
362
  * @param {Object} [options.filter] - Filter on attributes projected onto
354
363
  * the iteration index.
364
+ * @param {string[]} [options.allowedFilterFields] - Fields `filter` may
365
+ * reference. Set this when the filter comes from user input.
355
366
  * @param {number} [options.concurrency=1] - Buckets to read concurrently.
356
367
  * @yields {BaoModel[]} One batch of loaded instances at a time.
357
368
  */
@@ -360,20 +371,33 @@ class BaoModel {
360
371
  throw new Error(`Model ${this.name} is not configured as iterable`);
361
372
  }
362
373
 
363
- const { batchSize = 100, filter = null, concurrency = 1 } = options;
374
+ const {
375
+ batchSize = 100,
376
+ filter = null,
377
+ allowedFilterFields,
378
+ concurrency = 1,
379
+ } = options;
364
380
  if (!Number.isInteger(concurrency) || concurrency < 1) {
365
381
  throw new Error("concurrency must be a positive integer");
366
382
  }
367
383
 
368
384
  if (this.iterationBuckets === 1) {
369
- yield* this._iterateSingleBucket(null, { batchSize, filter });
385
+ yield* this._iterateSingleBucket(null, {
386
+ batchSize,
387
+ filter,
388
+ allowedFilterFields,
389
+ });
370
390
  return;
371
391
  }
372
392
 
373
393
  const buckets = Array.from({ length: this.iterationBuckets }, (_, b) => b);
374
394
  if (concurrency === 1) {
375
395
  for (const bucket of buckets) {
376
- yield* this._iterateSingleBucket(bucket, { batchSize, filter });
396
+ yield* this._iterateSingleBucket(bucket, {
397
+ batchSize,
398
+ filter,
399
+ allowedFilterFields,
400
+ });
377
401
  }
378
402
  return;
379
403
  }
@@ -381,7 +405,11 @@ class BaoModel {
381
405
  yield* this._interleaveGenerators(
382
406
  buckets.map(
383
407
  (bucket) => () =>
384
- this._iterateSingleBucket(bucket, { batchSize, filter }),
408
+ this._iterateSingleBucket(bucket, {
409
+ batchSize,
410
+ filter,
411
+ allowedFilterFields,
412
+ }),
385
413
  ),
386
414
  concurrency,
387
415
  );
@@ -515,6 +543,8 @@ class BaoModel {
515
543
  * @param {Object} [options.filter] - Additional filter combined via AND
516
544
  * with the search predicate. Must reference only attributes projected
517
545
  * on `iter_search_index` (i.e., `_searchText` and the index/base keys).
546
+ * @param {string[]} [options.allowedFilterFields] - Fields `filter` may
547
+ * reference. Set this when the filter comes from user input.
518
548
  * @returns {Promise<{items: BaoModel[], cursor: string|null}>} `items` is
519
549
  * never longer than `limit`. `cursor` is `null` when the search is
520
550
  * fully exhausted; otherwise pass it back to get the next page.
@@ -597,6 +627,7 @@ class BaoModel {
597
627
  operator = "$and",
598
628
  batchSize = 100,
599
629
  filter = null,
630
+ allowedFilterFields,
600
631
  limit = 100,
601
632
  maxQueriesPerBucket = 50,
602
633
  parallel = true,
@@ -693,6 +724,7 @@ class BaoModel {
693
724
  const page = await this._searchSingleBucketPage(bucketArg(bucketIdx), {
694
725
  batchSize,
695
726
  filter,
727
+ allowedFilterFields,
696
728
  searchPredicate,
697
729
  exclusiveStartKey: lek || null,
698
730
  });
@@ -908,6 +940,7 @@ class BaoModel {
908
940
  const {
909
941
  batchSize = 100,
910
942
  filter = null,
943
+ allowedFilterFields,
911
944
  searchPredicate = null,
912
945
  exclusiveStartKey = null,
913
946
  } = options;
@@ -929,7 +962,9 @@ class BaoModel {
929
962
  if (filter) {
930
963
  const { FilterExpressionBuilder } = require("./filter-expression");
931
964
  const filterBuilder = new FilterExpressionBuilder();
932
- const filterExpression = filterBuilder.build(filter, this);
965
+ const filterExpression = filterBuilder.build(filter, this, {
966
+ allowedFields: allowedFilterFields,
967
+ });
933
968
  if (filterExpression) {
934
969
  this._assertFilterFitsIterIndex(
935
970
  indexName,
@@ -973,7 +1008,12 @@ class BaoModel {
973
1008
  }
974
1009
 
975
1010
  static async *_iterateSingleBucket(bucketNum, options = {}) {
976
- const { batchSize = 100, filter = null, searchPredicate = null } = options;
1011
+ const {
1012
+ batchSize = 100,
1013
+ filter = null,
1014
+ allowedFilterFields,
1015
+ searchPredicate = null,
1016
+ } = options;
977
1017
  const iterPk = this._getIterationPk(bucketNum);
978
1018
  const indexName = this.manager.getIterationIndexName();
979
1019
 
@@ -993,7 +1033,9 @@ class BaoModel {
993
1033
  if (filter) {
994
1034
  const { FilterExpressionBuilder } = require("./filter-expression");
995
1035
  const filterBuilder = new FilterExpressionBuilder();
996
- const filterExpression = filterBuilder.build(filter, this);
1036
+ const filterExpression = filterBuilder.build(filter, this, {
1037
+ allowedFields: allowedFilterFields,
1038
+ });
997
1039
  if (filterExpression) {
998
1040
  // Preflight: filter attributes must be in the GSI's projection.
999
1041
  // Otherwise DynamoDB returns an opaque "does not project one or
@@ -1274,7 +1316,11 @@ class BaoModel {
1274
1316
  }
1275
1317
 
1276
1318
  if (primaryId.indexOf(GID_SEPARATOR) !== -1) {
1277
- const [pk, sk] = primaryId.split(GID_SEPARATOR);
1319
+ const parts = primaryId.split(GID_SEPARATOR);
1320
+ if (parts.length !== 2) {
1321
+ throw new ValidationError(`Invalid primary id: ${primaryId}`);
1322
+ }
1323
+ const [pk, sk] = parts;
1278
1324
  return { pk, sk };
1279
1325
  } else {
1280
1326
  if (this.primaryKey.pk === "modelPrefix") {