@open-mercato/shared 0.6.5-develop.5048.1.fd82f4ae17 → 0.6.5-develop.5116.1.f0af9e5080

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.
@@ -22,6 +22,7 @@ export interface KmsService {
22
22
  getTenantDek(tenantId: string): Promise<TenantDek | null>
23
23
  createTenantDek(tenantId: string): Promise<TenantDek | null>
24
24
  isHealthy(): boolean
25
+ invalidateDek?(tenantId: string): void
25
26
  }
26
27
 
27
28
  class FallbackKmsService implements KmsService {
@@ -76,6 +77,11 @@ class FallbackKmsService implements KmsService {
76
77
  }
77
78
  return null
78
79
  }
80
+
81
+ invalidateDek(tenantId: string): void {
82
+ this.primary.invalidateDek?.(tenantId)
83
+ this.fallback?.invalidateDek?.(tenantId)
84
+ }
79
85
  }
80
86
 
81
87
  type VaultClientOpts = {
@@ -90,6 +96,10 @@ type VaultReadResponse = {
90
96
  data?: { data?: { key?: string; version?: number }; metadata?: Record<string, unknown> }
91
97
  }
92
98
 
99
+ // 'conflict' = a check-and-set write lost to a concurrent writer (normal race
100
+ // outcome, Vault still healthy); 'error' = the write genuinely failed.
101
+ type VaultWriteOutcome = 'ok' | 'conflict' | 'error'
102
+
93
103
  function normalizeEnv(value: string | undefined): string {
94
104
  if (!value) return ''
95
105
  return value.trim().replace(/(?:^['"]|['"]$)/g, '')
@@ -230,11 +240,13 @@ export class HashicorpVaultKmsService implements KmsService {
230
240
  }
231
241
  }
232
242
 
233
- private async writeVault(path: string, key: string): Promise<boolean> {
243
+ private async writeVault(path: string, key: string, opts?: { cas?: number }): Promise<VaultWriteOutcome> {
234
244
  if (!this.vaultAddr || !this.vaultToken) {
235
245
  this.healthy = false
236
- return false
246
+ return 'error'
237
247
  }
248
+ const body: { data: { key: string }; options?: { cas: number } } = { data: { key } }
249
+ if (typeof opts?.cas === 'number') body.options = { cas: opts.cas }
238
250
  try {
239
251
  const res = await fetchWithTimeout(`${this.vaultAddr}/v1/${path}`, {
240
252
  method: 'POST',
@@ -242,14 +254,23 @@ export class HashicorpVaultKmsService implements KmsService {
242
254
  'X-Vault-Token': this.vaultToken,
243
255
  'Content-Type': 'application/json',
244
256
  },
245
- body: JSON.stringify({ data: { key } }),
257
+ body: JSON.stringify(body),
246
258
  timeoutMs: this.requestTimeoutMs,
247
259
  })
248
- this.healthy = res.ok
249
- if (!res.ok) {
250
- console.warn('⚠️ [encryption][kms] Vault write failed', { path, status: res.status })
260
+ if (res.ok) {
261
+ this.healthy = true
262
+ return 'ok'
251
263
  }
252
- return res.ok
264
+ // KV v2 returns 400 when a check-and-set write loses to a concurrent
265
+ // writer (path already at a newer version). That is a normal race outcome,
266
+ // not an unhealthy Vault — don't flip `healthy`.
267
+ if (typeof opts?.cas === 'number' && res.status === 400) {
268
+ console.warn('⚠️ [encryption][kms] Vault write CAS conflict (concurrent DEK create)', { path, status: res.status })
269
+ return 'conflict'
270
+ }
271
+ this.healthy = false
272
+ console.warn('⚠️ [encryption][kms] Vault write failed', { path, status: res.status })
273
+ return 'error'
253
274
  } catch (err) {
254
275
  this.healthy = false
255
276
  console.warn('⚠️ [encryption][kms] Vault write error', {
@@ -257,7 +278,7 @@ export class HashicorpVaultKmsService implements KmsService {
257
278
  error: (err as Error)?.message || String(err),
258
279
  timeoutMs: this.requestTimeoutMs,
259
280
  })
260
- return false
281
+ return 'error'
261
282
  }
262
283
  }
263
284
 
@@ -287,16 +308,40 @@ export class HashicorpVaultKmsService implements KmsService {
287
308
  }
288
309
 
289
310
  async createTenantDek(tenantId: string): Promise<TenantDek | null> {
290
- const key = generateDek()
291
311
  const path = this.buildKeyPath(tenantId)
292
- const ok = await this.writeVault(path, key)
293
- if (ok) {
312
+ // Read-before-write: if a DEK already exists for this tenant (another request
313
+ // or process created it first), adopt it instead of overwriting the active
314
+ // key — overwriting orphans every row already encrypted under it (#2746).
315
+ const existing = await this.readVault(path)
316
+ const existingKey = existing?.data?.data?.key
317
+ if (existingKey) {
318
+ return this.remember({ tenantId, key: existingKey, fetchedAt: this.now() })
319
+ }
320
+ // A read failure (timeout / 5xx) flips `healthy` off; don't blind-write a new
321
+ // key over a possibly-existing one we just couldn't read — let the caller fall back.
322
+ if (!this.healthy) return null
323
+ const key = generateDek()
324
+ const outcome = await this.writeVault(path, key, { cas: 0 })
325
+ if (outcome === 'ok') {
294
326
  console.info('🔑 [encryption][kms] Stored tenant DEK in Vault', { tenantId, path })
295
- } else {
296
- console.warn('⚠️ [encryption][kms] Failed to store tenant DEK in Vault', { tenantId, path })
327
+ return this.remember({ tenantId, key, fetchedAt: this.now() })
328
+ }
329
+ if (outcome === 'conflict') {
330
+ // A concurrent create won the CAS race — adopt the winner's key so both
331
+ // callers encrypt under the same DEK.
332
+ const winner = await this.readVault(path)
333
+ const winnerKey = winner?.data?.data?.key
334
+ if (winnerKey) {
335
+ console.info('🔑 [encryption][kms] Adopted concurrently-created tenant DEK', { tenantId, path })
336
+ return this.remember({ tenantId, key: winnerKey, fetchedAt: this.now() })
337
+ }
297
338
  }
298
- if (!ok) return null
299
- return this.remember({ tenantId, key, fetchedAt: this.now() })
339
+ console.warn('⚠️ [encryption][kms] Failed to store tenant DEK in Vault', { tenantId, path })
340
+ return null
341
+ }
342
+
343
+ invalidateDek(tenantId: string): void {
344
+ this.cache.delete(tenantId)
300
345
  }
301
346
  }
302
347
 
@@ -22,6 +22,10 @@ type MapCacheKey = {
22
22
  }
23
23
 
24
24
  const MAP_MISS_TTL_MS = 5 * 60 * 1000
25
+ // Mirror the Vault KMS default DEK TTL so a rotated/revoked tenant key is picked
26
+ // up by long-lived processes without a restart (#2746). The service-level cache
27
+ // previously had no TTL and shadowed the KMS's own 15-minute expiry.
28
+ const DEK_CACHE_TTL_MS = 15 * 60 * 1000
25
29
 
26
30
  function cacheKey(key: MapCacheKey): string {
27
31
  return [
@@ -106,11 +110,13 @@ export class TenantDataEncryptionService {
106
110
  private static globalMemoryCache = new Map<string, EncryptionMapRecord>()
107
111
  private static globalInflightMaps = new Map<string, Promise<EncryptionMapRecord | null>>()
108
112
  private static globalDekCache = new Map<string, TenantDek>()
113
+ private static globalInflightDeks = new Map<string, Promise<TenantDek | null>>()
109
114
  private static globalMissCache = new Map<string, number>()
110
115
  private readonly kms: KmsService
111
116
  private readonly cache?: CacheStrategy
112
117
  private readonly memoryCache = TenantDataEncryptionService.globalMemoryCache
113
118
  private readonly dekCache = TenantDataEncryptionService.globalDekCache
119
+ private readonly inflightDeks = TenantDataEncryptionService.globalInflightDeks
114
120
  private readonly inflightMaps = TenantDataEncryptionService.globalInflightMaps
115
121
  private readonly missCache = TenantDataEncryptionService.globalMissCache
116
122
 
@@ -126,10 +132,15 @@ export class TenantDataEncryptionService {
126
132
  return isTenantDataEncryptionEnabled() && this.kms.isHealthy()
127
133
  }
128
134
 
135
+ private isDekExpired(dek: TenantDek): boolean {
136
+ return Date.now() - dek.fetchedAt > DEK_CACHE_TTL_MS
137
+ }
138
+
129
139
  async getDek(tenantId: string | null | undefined): Promise<TenantDek | null> {
130
140
  if (!tenantId) return null
131
141
  const cached = this.dekCache.get(tenantId)
132
- if (cached) return cached
142
+ if (cached && !this.isDekExpired(cached)) return cached
143
+ if (cached) this.dekCache.delete(tenantId)
133
144
  const dek = await this.kms.getTenantDek(tenantId)
134
145
  if (!dek) {
135
146
  debug('🔎 dek.miss', { tenantId })
@@ -144,9 +155,22 @@ export class TenantDataEncryptionService {
144
155
  const existing = await this.getDek(tenantId)
145
156
  if (existing || !tenantId) return existing ?? null
146
157
  if (typeof this.kms.createTenantDek !== 'function') return existing ?? null
147
- const created = await this.kms.createTenantDek(tenantId)
148
- if (created) this.dekCache.set(tenantId, created)
149
- return created ?? null
158
+ // Dedupe concurrent first-time creation within this process so two callers
159
+ // can't each generate a distinct DEK and overwrite one another (#2746).
160
+ // Mirrors the encryption-map inflight dedupe (`globalInflightMaps`).
161
+ const pending = this.inflightDeks.get(tenantId)
162
+ if (pending) return pending
163
+ const creation = (async () => {
164
+ const created = await this.kms.createTenantDek(tenantId)
165
+ if (created) this.dekCache.set(tenantId, created)
166
+ return created ?? null
167
+ })()
168
+ this.inflightDeks.set(tenantId, creation)
169
+ try {
170
+ return await creation
171
+ } finally {
172
+ this.inflightDeks.delete(tenantId)
173
+ }
150
174
  }
151
175
 
152
176
  async createDek(tenantId: string): Promise<TenantDek | null> {
@@ -246,6 +270,15 @@ export class TenantDataEncryptionService {
246
270
  }
247
271
  }
248
272
 
273
+ // Force a flush of a tenant's cached DEK across the service-level cache and the
274
+ // underlying KMS cache so an operator can pick up a rotated/revoked key without
275
+ // a process restart (#2746).
276
+ invalidateDek(tenantId: string): void {
277
+ this.dekCache.delete(tenantId)
278
+ this.inflightDeks.delete(tenantId)
279
+ this.kms.invalidateDek?.(tenantId)
280
+ }
281
+
249
282
  async getEncryptedFieldNames(
250
283
  entityId: string,
251
284
  tenantId: string | null | undefined,
@@ -0,0 +1,83 @@
1
+ import {
2
+ resolveRegisteredEntityTableName,
3
+ resolveEntityTableName,
4
+ isValidEntityIdShape,
5
+ ENTITY_ID_PATTERN,
6
+ } from '../engine'
7
+
8
+ function makeEm(metaByClass: Record<string, string>) {
9
+ const all = Object.entries(metaByClass).map(([className, tableName]) => ({ className, tableName }))
10
+ return {
11
+ getMetadata: () => ({
12
+ find: (className: string) => {
13
+ const tableName = metaByClass[className]
14
+ return tableName ? { tableName } : undefined
15
+ },
16
+ getAll: () => all,
17
+ }),
18
+ } as any
19
+ }
20
+
21
+ describe('resolveRegisteredEntityTableName', () => {
22
+ it('resolves a registered entity via class-name metadata', () => {
23
+ const em = makeEm({ Todo: 'todos' })
24
+ expect(resolveRegisteredEntityTableName(em, 'example:todo')).toBe('todos')
25
+ })
26
+
27
+ it('resolves a registered entity via the secondary table-name lookup', () => {
28
+ const em = makeEm({ SomeOtherClass: 'directory_organizations' })
29
+ expect(resolveRegisteredEntityTableName(em, 'directory:organization')).toBe('directory_organizations')
30
+ })
31
+
32
+ it('returns null for an entity type that does not map to any registered metadata', () => {
33
+ const em = makeEm({ Todo: 'todos' })
34
+ expect(resolveRegisteredEntityTableName(em, 'foo:auth_user')).toBeNull()
35
+ expect(resolveRegisteredEntityTableName(em, 'foo:user')).toBeNull()
36
+ })
37
+
38
+ it('returns null when no metadata is available', () => {
39
+ expect(resolveRegisteredEntityTableName(undefined, 'example:todo')).toBeNull()
40
+ expect(resolveRegisteredEntityTableName({} as any, 'example:todo')).toBeNull()
41
+ })
42
+
43
+ it('never pluralizes attacker-chosen ids into a real table name', () => {
44
+ const em = makeEm({})
45
+ expect(resolveRegisteredEntityTableName(em, 'foo:auth_user')).toBeNull()
46
+ expect(resolveRegisteredEntityTableName(em, 'foo:user')).toBeNull()
47
+ })
48
+ })
49
+
50
+ describe('resolveEntityTableName fallback (broad query path)', () => {
51
+ it('still falls back to a pluralized guess for unregistered ids', () => {
52
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
53
+ try {
54
+ const em = makeEm({})
55
+ expect(resolveEntityTableName(em, 'foo:never_registered_widget')).toBe('never_registered_widgets')
56
+ } finally {
57
+ warnSpy.mockRestore()
58
+ }
59
+ })
60
+ })
61
+
62
+ describe('isValidEntityIdShape', () => {
63
+ it('accepts canonical module:entity ids', () => {
64
+ expect(isValidEntityIdShape('example:todo')).toBe(true)
65
+ expect(isValidEntityIdShape('directory:organization')).toBe(true)
66
+ expect(isValidEntityIdShape('query_index:search_token')).toBe(true)
67
+ })
68
+
69
+ it('rejects ids without exactly two snake_case segments', () => {
70
+ expect(isValidEntityIdShape('todos')).toBe(false)
71
+ expect(isValidEntityIdShape('auth_users')).toBe(false)
72
+ expect(isValidEntityIdShape('foo:bar:baz')).toBe(false)
73
+ expect(isValidEntityIdShape('Foo:Bar')).toBe(false)
74
+ expect(isValidEntityIdShape('1bad:entity')).toBe(false)
75
+ expect(isValidEntityIdShape('foo:')).toBe(false)
76
+ expect(isValidEntityIdShape(':bar')).toBe(false)
77
+ expect(isValidEntityIdShape('foo bar:baz')).toBe(false)
78
+ })
79
+
80
+ it('exposes the pattern for schema reuse', () => {
81
+ expect(ENTITY_ID_PATTERN.test('example:todo')).toBe(true)
82
+ })
83
+ })
@@ -42,6 +42,15 @@ type ResolvedCustomFieldSource = {
42
42
 
43
43
  type ResultRow = Record<string, unknown>
44
44
 
45
+ /**
46
+ * Canonical `module:entity` entity-id shape (both segments snake_case,
47
+ * starting with a lowercase letter). Used to validate caller-supplied entity
48
+ * ids at security-sensitive boundaries before they reach table resolution.
49
+ */
50
+ export const ENTITY_ID_PATTERN = /^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*$/
51
+
52
+ export const isValidEntityIdShape = (value: string): boolean => ENTITY_ID_PATTERN.test(value)
53
+
45
54
  const pluralizeBaseName = (name: string): string => {
46
55
  if (!name) return name
47
56
  if (name.endsWith('s')) return name
@@ -65,46 +74,66 @@ const candidateClassNames = (rawName: string): string[] => {
65
74
  return Array.from(candidates)
66
75
  }
67
76
 
68
- export function resolveEntityTableName(em: EntityManager | undefined, entity: EntityId): string {
69
- if (entityTableCache.has(entity)) {
70
- return entityTableCache.get(entity)!
71
- }
77
+ /**
78
+ * Resolve an entity id to a table name strictly via registered MikroORM metadata.
79
+ *
80
+ * Unlike {@link resolveEntityTableName}, this never falls back to a pluralized
81
+ * guess: it returns `null` when no registered entity matches. Use it for
82
+ * security-sensitive call sites (e.g. the reindexer) that must refuse to read
83
+ * arbitrary, attacker-chosen tables that happen to exist in the schema.
84
+ */
85
+ export function resolveRegisteredEntityTableName(
86
+ em: EntityManager | undefined,
87
+ entity: EntityId,
88
+ ): string | null {
72
89
  const parts = String(entity || '').split(':')
73
90
  const rawName = (parts[1] && parts[1].trim().length > 0) ? parts[1] : (parts[0] || '').trim()
74
91
  const metadata = (em as any)?.getMetadata?.()
75
92
 
76
- if (metadata && rawName) {
77
- const candidates = candidateClassNames(rawName)
78
- for (const candidate of candidates) {
79
- try {
80
- const meta = metadata.find?.(candidate)
81
- if (meta?.tableName) {
82
- const tableName = String(meta.tableName)
83
- entityTableCache.set(entity, tableName)
84
- return tableName
85
- }
86
- } catch {}
87
- }
93
+ if (!metadata || !rawName) return null
88
94
 
89
- // Secondary lookup: search ORM metadata by candidate table names
90
- const modulePrefix = parts[0] ?? ''
91
- const candidateTables = [
92
- `${modulePrefix}_${rawName}`,
93
- pluralizeBaseName(rawName),
94
- `${modulePrefix}_${pluralizeBaseName(rawName)}`,
95
- ]
95
+ const candidates = candidateClassNames(rawName)
96
+ for (const candidate of candidates) {
96
97
  try {
97
- const allMeta: any[] = metadata.getAll?.() ?? []
98
- for (const meta of allMeta) {
99
- if (meta?.tableName && candidateTables.includes(String(meta.tableName))) {
100
- const tableName = String(meta.tableName)
101
- entityTableCache.set(entity, tableName)
102
- return tableName
103
- }
98
+ const meta = metadata.find?.(candidate)
99
+ if (meta?.tableName) {
100
+ return String(meta.tableName)
104
101
  }
105
102
  } catch {}
106
103
  }
107
104
 
105
+ // Secondary lookup: search ORM metadata by candidate table names
106
+ const modulePrefix = parts[0] ?? ''
107
+ const candidateTables = [
108
+ `${modulePrefix}_${rawName}`,
109
+ pluralizeBaseName(rawName),
110
+ `${modulePrefix}_${pluralizeBaseName(rawName)}`,
111
+ ]
112
+ try {
113
+ const allMeta: any[] = metadata.getAll?.() ?? []
114
+ for (const meta of allMeta) {
115
+ if (meta?.tableName && candidateTables.includes(String(meta.tableName))) {
116
+ return String(meta.tableName)
117
+ }
118
+ }
119
+ } catch {}
120
+
121
+ return null
122
+ }
123
+
124
+ export function resolveEntityTableName(em: EntityManager | undefined, entity: EntityId): string {
125
+ if (entityTableCache.has(entity)) {
126
+ return entityTableCache.get(entity)!
127
+ }
128
+ const parts = String(entity || '').split(':')
129
+ const rawName = (parts[1] && parts[1].trim().length > 0) ? parts[1] : (parts[0] || '').trim()
130
+
131
+ const registered = resolveRegisteredEntityTableName(em, entity)
132
+ if (registered) {
133
+ entityTableCache.set(entity, registered)
134
+ return registered
135
+ }
136
+
108
137
  const fallback = pluralizeBaseName(rawName || '')
109
138
  console.warn(
110
139
  `[QueryEngine] Could not resolve entity "${entity}" via ORM metadata. ` +
@@ -1,5 +1,6 @@
1
1
  import type { EntityId } from './entities'
2
2
  import type { QueryEngine } from '../lib/query/types'
3
+ import type { SearchFieldPolicy } from './search'
3
4
 
4
5
  export type VectorDriverId = 'pgvector' | 'qdrant' | 'chromadb'
5
6
 
@@ -71,6 +72,12 @@ export type VectorEntityConfig = {
71
72
  * Provide extra deep links rendered next to the search result.
72
73
  */
73
74
  resolveLinks?: (ctx: VectorBuildContext) => Promise<VectorLinkDescriptor[] | null> | VectorLinkDescriptor[] | null
75
+ /**
76
+ * Controls which record/custom fields are eligible for the default embedding source builder.
77
+ * Applied only when `buildSource` is not provided. `excluded`/`hashOnly` fields are never embedded;
78
+ * when `searchable` is defined it acts as an allowlist for both record and custom fields.
79
+ */
80
+ fieldPolicy?: SearchFieldPolicy
74
81
  }
75
82
 
76
83
  export type VectorModuleConfig = {