@agent-native/dispatch 0.42.5-nightly-20261111212500 → 0.42.5

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +8 -46
  2. package/dist/actions/create-vault-secret.js +2 -2
  3. package/dist/actions/create-vault-secret.js.map +1 -1
  4. package/dist/actions/index.d.ts.map +1 -1
  5. package/dist/actions/index.js +0 -2
  6. package/dist/actions/index.js.map +1 -1
  7. package/dist/actions/list-vault-secrets.d.ts +1 -1
  8. package/dist/actions/list-vault-secrets.js +3 -4
  9. package/dist/actions/list-vault-secrets.js.map +1 -1
  10. package/dist/actions/provider-api-register.d.ts +12 -12
  11. package/dist/actions/update-vault-secret.js +2 -2
  12. package/dist/actions/update-vault-secret.js.map +1 -1
  13. package/dist/components/app-keys-popover.d.ts.map +1 -1
  14. package/dist/components/app-keys-popover.js +8 -19
  15. package/dist/components/app-keys-popover.js.map +1 -1
  16. package/dist/routes/pages/vault.d.ts.map +1 -1
  17. package/dist/routes/pages/vault.js +3 -9
  18. package/dist/routes/pages/vault.js.map +1 -1
  19. package/dist/server/lib/vault-store.d.ts +18 -68
  20. package/dist/server/lib/vault-store.d.ts.map +1 -1
  21. package/dist/server/lib/vault-store.js +98 -273
  22. package/dist/server/lib/vault-store.js.map +1 -1
  23. package/package.json +4 -4
  24. package/src/actions/create-vault-secret.ts +2 -2
  25. package/src/actions/index.spec.ts +1 -1
  26. package/src/actions/index.ts +0 -2
  27. package/src/actions/list-vault-secrets.ts +3 -4
  28. package/src/actions/update-vault-secret.ts +3 -2
  29. package/src/components/app-keys-popover.tsx +1 -39
  30. package/src/routes/pages/vault.tsx +21 -31
  31. package/src/server/lib/vault-store.spec.ts +377 -450
  32. package/src/server/lib/vault-store.ts +141 -340
  33. package/dist/actions/sync-vault-to-app.d.ts +0 -32
  34. package/dist/actions/sync-vault-to-app.d.ts.map +0 -1
  35. package/dist/actions/sync-vault-to-app.js +0 -13
  36. package/dist/actions/sync-vault-to-app.js.map +0 -1
  37. package/src/actions/sync-vault-to-app.ts +0 -15
@@ -1,4 +1,4 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
2
 
3
3
  const mocks = vi.hoisted(() => ({
4
4
  currentOrgId: vi.fn(),
@@ -59,21 +59,28 @@ vi.mock("../../db/index.js", async (importOriginal) => {
59
59
  };
60
60
  });
61
61
 
62
- import { readAppSecret } from "@agent-native/core/secrets";
63
-
62
+ import { schema } from "../../db/index.js";
64
63
  import {
65
64
  assertCanManageVault,
66
65
  cleanupSyncedCredentialKeysIfUnused,
66
+ createSecret,
67
67
  credentialStoreScopeForVaultCtx,
68
- isTrustedEnvVarSyncAgentUrl,
69
68
  getGrant,
69
+ getVaultSecretMetadata,
70
70
  listGrants,
71
- resyncVaultSecretsToCredentialStorePage,
72
- syncGrantsToApp,
73
- syncSecretsToCredentialStore,
74
- toVaultSecretMetadata,
71
+ listVaultSecretMetadata,
72
+ updateSecret,
75
73
  } from "./vault-store.js";
76
74
 
75
+ beforeEach(() => {
76
+ // clearAllMocks keeps implementations, so a rejection set by one test would
77
+ // leak into the next.
78
+ mocks.deleteAppSecret.mockReset();
79
+ mocks.writeAppSecret.mockReset();
80
+ mocks.readAppSecret.mockReset();
81
+ mocks.listAppSecretsForScope.mockReset();
82
+ });
83
+
77
84
  afterEach(() => {
78
85
  vi.clearAllMocks();
79
86
  vi.unstubAllEnvs();
@@ -164,78 +171,394 @@ describe("vault authorization", () => {
164
171
  });
165
172
  });
166
173
 
167
- describe("toVaultSecretMetadata", () => {
168
- it("returns only masked metadata", () => {
169
- const metadata = toVaultSecretMetadata({
174
+ describe("vault secret metadata", () => {
175
+ const row = (overrides: Record<string, unknown> = {}) =>
176
+ ({
170
177
  id: "secret-1",
178
+ ownerEmail: "admin@example.test",
179
+ orgId: "org_123",
171
180
  name: "Test key",
172
181
  credentialKey: "TEST_KEY",
173
- value: "sk-test-example",
182
+ value: "",
174
183
  provider: "other",
175
184
  description: "Fake test credential",
176
- createdBy: "owner@example.test",
185
+ createdBy: "admin@example.test",
177
186
  createdAt: 1,
178
187
  updatedAt: 2,
179
- } as any);
188
+ ...overrides,
189
+ }) as any;
190
+ const ctx = { ownerEmail: "admin@example.test", orgId: "org_123" };
180
191
 
181
- expect(metadata).toMatchObject({
182
- id: "secret-1",
183
- credentialKey: "TEST_KEY",
184
- last4: "••••mple",
185
- });
186
- expect(metadata).not.toHaveProperty("value");
187
- expect(JSON.stringify(metadata)).not.toContain("sk-test-example");
192
+ // oracle-change: the vault no longer pushes to apps or re-syncs plaintext, so the tests for syncGrantsToApp, the env-var URL check and the resync page are replaced by single-copy write tests.
193
+ it("takes the masked preview from the encrypted copy, one read per scope", async () => {
194
+ mocks.listAppSecretsForScope.mockResolvedValue([
195
+ { key: "TEST_KEY", last4: "••••mple" },
196
+ { key: "OTHER_KEY", last4: "••••9999" },
197
+ ]);
198
+
199
+ const metadata = await listVaultSecretMetadata(
200
+ [row(), row({ id: "secret-2", credentialKey: "OTHER_KEY" })],
201
+ ctx,
202
+ );
203
+
204
+ expect(mocks.listAppSecretsForScope).toHaveBeenCalledTimes(1);
205
+ expect(mocks.listAppSecretsForScope).toHaveBeenCalledWith("org", "org_123");
206
+ expect(metadata.map((m) => m.last4)).toEqual(["••••mple", "••••9999"]);
207
+ expect(metadata.map((m) => m.valueStatus)).toEqual(["stored", "stored"]);
208
+ expect(metadata[0]).not.toHaveProperty("value");
188
209
  });
189
- });
190
210
 
191
- describe("isTrustedEnvVarSyncAgentUrl", () => {
192
- it("allows localhost development app URLs", () => {
193
- expect(isTrustedEnvVarSyncAgentUrl("http://localhost:9201")).toBe(true);
194
- expect(isTrustedEnvVarSyncAgentUrl("http://127.0.0.1:9201")).toBe(true);
211
+ it("reads each scope separately and leaves a missing copy blank", async () => {
212
+ mocks.listAppSecretsForScope.mockImplementation(async (scope: string) =>
213
+ scope === "org" ? [{ key: "TEST_KEY", last4: "••••mple" }] : [],
214
+ );
215
+
216
+ const metadata = await listVaultSecretMetadata(
217
+ [row(), row({ id: "solo-1", orgId: null, credentialKey: "SOLO_KEY" })],
218
+ ctx,
219
+ );
220
+
221
+ expect(mocks.listAppSecretsForScope).toHaveBeenCalledTimes(2);
222
+ expect(metadata.map((m) => m.last4)).toEqual(["••••mple", ""]);
223
+ expect(metadata.map((m) => m.valueStatus)).toEqual(["stored", "missing"]);
195
224
  });
196
225
 
197
- it("allows same-origin workspace app URLs from deploy metadata", () => {
198
- vi.stubEnv("WORKSPACE_GATEWAY_URL", "https://workspace.example.test");
226
+ it("tells a copy this deployment cannot decrypt apart from one that is missing", async () => {
227
+ // listAppSecretsForScope reports an undecryptable copy as an empty preview.
228
+ mocks.listAppSecretsForScope.mockResolvedValue([
229
+ { key: "TEST_KEY", last4: "" },
230
+ ]);
199
231
 
200
- expect(
201
- isTrustedEnvVarSyncAgentUrl("https://workspace.example.test/slides"),
202
- ).toBe(true);
232
+ const [unreadable, missing] = await listVaultSecretMetadata(
233
+ [row(), row({ id: "secret-2", credentialKey: "ABSENT_KEY" })],
234
+ ctx,
235
+ );
236
+
237
+ expect(unreadable).toMatchObject({ last4: "", valueStatus: "unreadable" });
238
+ expect(missing).toMatchObject({ last4: "", valueStatus: "missing" });
203
239
  });
204
240
 
205
- it("rejects remote custom agent origins", () => {
206
- vi.stubEnv("WORKSPACE_GATEWAY_URL", "https://workspace.example.test");
241
+ it("reads a single preview straight from the credential store", async () => {
242
+ mocks.readAppSecret.mockResolvedValue({
243
+ value: "sk-live",
244
+ last4: "••••live",
245
+ });
246
+
247
+ const metadata = await getVaultSecretMetadata(row(), ctx);
248
+
249
+ expect(mocks.readAppSecret).toHaveBeenCalledWith({
250
+ key: "TEST_KEY",
251
+ scope: "org",
252
+ scopeId: "org_123",
253
+ });
254
+ expect(metadata).toMatchObject({
255
+ last4: "••••live",
256
+ valueStatus: "stored",
257
+ });
258
+ expect(JSON.stringify(metadata)).not.toContain("sk-live");
259
+ expect(await getVaultSecretMetadata(null, ctx)).toBeNull();
260
+ });
261
+
262
+ it("reports a single key with no copy as missing", async () => {
263
+ mocks.readAppSecret.mockResolvedValue(null);
264
+
265
+ expect(await getVaultSecretMetadata(row(), ctx)).toMatchObject({
266
+ last4: "",
267
+ valueStatus: "missing",
268
+ });
269
+ });
207
270
 
208
- expect(isTrustedEnvVarSyncAgentUrl("https://attacker.example.test")).toBe(
209
- false,
271
+ it("reports a single key whose copy cannot be decrypted as unreadable, and rethrows anything else", async () => {
272
+ mocks.readAppSecret.mockRejectedValueOnce(
273
+ Object.assign(new Error("cannot decrypt"), {
274
+ errorCode: "app_secret_unreadable",
275
+ }),
276
+ );
277
+ expect(await getVaultSecretMetadata(row(), ctx)).toMatchObject({
278
+ last4: "",
279
+ valueStatus: "unreadable",
280
+ });
281
+
282
+ mocks.readAppSecret.mockRejectedValueOnce(new Error("database down"));
283
+ await expect(getVaultSecretMetadata(row(), ctx)).rejects.toThrow(
284
+ "database down",
210
285
  );
211
286
  });
212
287
  });
213
288
 
214
- describe("syncSecretsToCredentialStore", () => {
215
- it("writes vault secrets into app_secrets without returning values", async () => {
216
- const result = await syncSecretsToCredentialStore(
217
- [
218
- {
219
- name: "OpenAI API Key",
220
- credentialKey: "OPENAI_API_KEY",
221
- value: "sk-test-key",
222
- } as any,
223
- ],
224
- { ownerEmail: "admin@example.test", orgId: "org_123" },
225
- );
289
+ describe("vault writes keep the value out of vault_secrets", () => {
290
+ const admin = "admin@example.test";
291
+ const existingRow = (overrides: Record<string, unknown> = {}) => ({
292
+ id: "secret-1",
293
+ ownerEmail: admin,
294
+ orgId: "org_123",
295
+ name: "OpenAI API Key",
296
+ credentialKey: "OPENAI_API_KEY",
297
+ value: "",
298
+ provider: null,
299
+ description: null,
300
+ createdBy: admin,
301
+ createdAt: 1,
302
+ updatedAt: 2,
303
+ ...overrides,
304
+ });
305
+
306
+ function fakeVaultDb(
307
+ rows: Array<Record<string, unknown>>,
308
+ options: {
309
+ // Results for the first selects, in order; later ones return `rows`.
310
+ selects?: Array<Array<Record<string, unknown>>>;
311
+ failInsert?: Error;
312
+ failUpdate?: Error;
313
+ } = {},
314
+ ) {
315
+ const writes = {
316
+ inserted: [] as Array<Record<string, unknown>>,
317
+ updated: [] as Array<Record<string, unknown>>,
318
+ };
319
+ const queued = [...(options.selects ?? [])];
320
+ const select: any = {
321
+ from: () => select,
322
+ where: () => select,
323
+ orderBy: () => select,
324
+ limit: async () => queued.shift() ?? rows,
325
+ };
326
+ mocks.getDb.mockReturnValue({
327
+ select: () => select,
328
+ insert: (table: unknown) => ({
329
+ values: async (values: Record<string, unknown>) => {
330
+ if (table !== schema.vaultSecrets) return;
331
+ if (options.failInsert) throw options.failInsert;
332
+ writes.inserted.push(values);
333
+ },
334
+ }),
335
+ update: (table: unknown) => ({
336
+ set: (values: Record<string, unknown>) => ({
337
+ where: async () => {
338
+ if (table !== schema.vaultSecrets) return;
339
+ if (options.failUpdate) throw options.failUpdate;
340
+ writes.updated.push(values);
341
+ },
342
+ }),
343
+ }),
344
+ });
345
+ return writes;
346
+ }
347
+
348
+ function actAsOrgAdmin() {
349
+ mocks.currentOwnerEmail.mockReturnValue(admin);
350
+ mocks.currentOrgId.mockReturnValue("org_123");
351
+ mocks.readOrgMemberRole.mockResolvedValue("admin");
352
+ }
353
+
354
+ const orgStore = (key: string) => ({
355
+ key,
356
+ scope: "org",
357
+ scopeId: "org_123",
358
+ });
359
+
360
+ it("encrypts a new secret into the credential store and saves an empty vault value", async () => {
361
+ actAsOrgAdmin();
362
+ const writes = fakeVaultDb([]);
363
+
364
+ await createSecret({
365
+ credentialKey: "OPENAI_API_KEY",
366
+ value: "sk-test-key",
367
+ name: "OpenAI API Key",
368
+ });
226
369
 
227
370
  expect(mocks.writeAppSecret).toHaveBeenCalledWith({
228
- key: "OPENAI_API_KEY",
371
+ ...orgStore("OPENAI_API_KEY"),
229
372
  value: "sk-test-key",
230
- scope: "org",
231
- scopeId: "org_123",
232
373
  description: "Synced from Dispatch vault: OpenAI API Key",
233
374
  });
234
- expect(result).toEqual({
235
- scope: "org",
236
- scopeId: "org_123",
237
- keys: ["OPENAI_API_KEY"],
375
+ expect(writes.inserted).toHaveLength(1);
376
+ expect(writes.inserted[0]).toMatchObject({
377
+ credentialKey: "OPENAI_API_KEY",
378
+ value: "",
379
+ });
380
+ expect(JSON.stringify(writes)).not.toContain("sk-test-key");
381
+ });
382
+
383
+ it("stores nothing when the vault row cannot be written", async () => {
384
+ actAsOrgAdmin();
385
+ fakeVaultDb([], { failInsert: new Error("row insert failed") });
386
+
387
+ await expect(
388
+ createSecret({
389
+ credentialKey: "OPENAI_API_KEY",
390
+ value: "sk-test-key",
391
+ name: "OpenAI API Key",
392
+ }),
393
+ ).rejects.toThrow("row insert failed");
394
+
395
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
396
+ });
397
+
398
+ it("leaves an existing key's stored value alone when its row cannot be updated", async () => {
399
+ actAsOrgAdmin();
400
+ fakeVaultDb([existingRow()], {
401
+ failUpdate: new Error("row update failed"),
402
+ });
403
+
404
+ await expect(
405
+ createSecret({
406
+ credentialKey: "OPENAI_API_KEY",
407
+ value: "sk-rotated",
408
+ name: "OpenAI API Key",
409
+ }),
410
+ ).rejects.toThrow("row update failed");
411
+
412
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
413
+ });
414
+
415
+ it("reports the encrypted write's failure after the row is saved", async () => {
416
+ actAsOrgAdmin();
417
+ const writes = fakeVaultDb([]);
418
+ mocks.writeAppSecret.mockRejectedValue(new Error("store unavailable"));
419
+
420
+ await expect(
421
+ createSecret({
422
+ credentialKey: "OPENAI_API_KEY",
423
+ value: "sk-test-key",
424
+ name: "OpenAI API Key",
425
+ }),
426
+ ).rejects.toThrow("store unavailable");
427
+
428
+ expect(writes.inserted).toHaveLength(1);
429
+ expect(JSON.stringify(writes)).not.toContain("sk-test-key");
430
+ });
431
+
432
+ it("rejects an empty value instead of saving a secret with nothing behind it", async () => {
433
+ actAsOrgAdmin();
434
+ const writes = fakeVaultDb([]);
435
+
436
+ await expect(
437
+ createSecret({
438
+ credentialKey: "OPENAI_API_KEY",
439
+ value: "",
440
+ name: "OpenAI API Key",
441
+ }),
442
+ ).rejects.toThrow("Secret value is required");
443
+
444
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
445
+ expect(writes.inserted).toEqual([]);
446
+ });
447
+
448
+ it("overwrites an existing key's copy and keeps the row's value empty", async () => {
449
+ actAsOrgAdmin();
450
+ const writes = fakeVaultDb([existingRow()]);
451
+
452
+ await createSecret({
453
+ credentialKey: "OPENAI_API_KEY",
454
+ value: "sk-rotated",
455
+ name: "OpenAI API Key",
456
+ });
457
+
458
+ expect(mocks.writeAppSecret).toHaveBeenCalledWith(
459
+ expect.objectContaining({
460
+ ...orgStore("OPENAI_API_KEY"),
461
+ value: "sk-rotated",
462
+ }),
463
+ );
464
+ expect(writes.updated[0]).toMatchObject({ value: "" });
465
+ });
466
+
467
+ it("lets metadata-only edits through without touching the value", async () => {
468
+ actAsOrgAdmin();
469
+ const writes = fakeVaultDb([existingRow()]);
470
+
471
+ await updateSecret("secret-1", { name: "Renamed", description: "note" });
472
+
473
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
474
+ expect(writes.updated[0]).toMatchObject({
475
+ name: "Renamed",
476
+ description: "note",
238
477
  });
478
+ expect(writes.updated[0]).not.toHaveProperty("value");
479
+ });
480
+
481
+ it("stores a new value from an edit", async () => {
482
+ actAsOrgAdmin();
483
+ const writes = fakeVaultDb([existingRow()]);
484
+
485
+ await updateSecret("secret-1", { value: "sk-rotated" });
486
+
487
+ expect(mocks.writeAppSecret).toHaveBeenCalledWith(
488
+ expect.objectContaining({
489
+ ...orgStore("OPENAI_API_KEY"),
490
+ value: "sk-rotated",
491
+ }),
492
+ );
493
+ expect(writes.updated[0]).toMatchObject({ value: "" });
494
+ });
495
+
496
+ it("rejects an explicit empty value on edit", async () => {
497
+ actAsOrgAdmin();
498
+ fakeVaultDb([existingRow()]);
499
+
500
+ await expect(updateSecret("secret-1", { value: "" })).rejects.toThrow(
501
+ "Secret value is required",
502
+ );
503
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
504
+ });
505
+
506
+ it("leaves a legacy row's value and the stored copy alone on a label edit", async () => {
507
+ actAsOrgAdmin();
508
+ const writes = fakeVaultDb([existingRow({ value: "sk-legacy" })]);
509
+
510
+ await updateSecret("secret-1", { name: "Renamed" });
511
+
512
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
513
+ expect(writes.updated[0]).toMatchObject({ name: "Renamed" });
514
+ expect(writes.updated[0]).not.toHaveProperty("value");
515
+ });
516
+
517
+ it("carries the stored value to the new key on a rename", async () => {
518
+ actAsOrgAdmin();
519
+ const writes = fakeVaultDb([existingRow()]);
520
+ mocks.readAppSecret.mockResolvedValue({
521
+ value: "sk-stored",
522
+ last4: "••••ored",
523
+ });
524
+
525
+ await updateSecret("secret-1", { credentialKey: "OPENAI_KEY_V2" });
526
+
527
+ expect(mocks.readAppSecret).toHaveBeenCalledWith(
528
+ orgStore("OPENAI_API_KEY"),
529
+ );
530
+ expect(mocks.writeAppSecret).toHaveBeenCalledWith(
531
+ expect.objectContaining({
532
+ ...orgStore("OPENAI_KEY_V2"),
533
+ value: "sk-stored",
534
+ }),
535
+ );
536
+ expect(writes.updated[0]).toMatchObject({
537
+ credentialKey: "OPENAI_KEY_V2",
538
+ });
539
+ expect(writes.updated[0]).not.toHaveProperty("value");
540
+ });
541
+
542
+ it("renames a row with no stored copy without inventing a value", async () => {
543
+ actAsOrgAdmin();
544
+ fakeVaultDb([existingRow()]);
545
+ mocks.readAppSecret.mockResolvedValue(null);
546
+
547
+ await updateSecret("secret-1", { credentialKey: "OPENAI_KEY_V2" });
548
+
549
+ expect(mocks.writeAppSecret).not.toHaveBeenCalled();
550
+ });
551
+
552
+ it("fails the rename when the stored copy cannot be read", async () => {
553
+ actAsOrgAdmin();
554
+ const writes = fakeVaultDb([existingRow()]);
555
+ mocks.readAppSecret.mockRejectedValue(new Error("cannot decrypt"));
556
+
557
+ await expect(
558
+ updateSecret("secret-1", { credentialKey: "OPENAI_KEY_V2" }),
559
+ ).rejects.toThrow("cannot decrypt");
560
+
561
+ expect(writes.updated).toEqual([]);
239
562
  });
240
563
  });
241
564
 
@@ -319,399 +642,3 @@ describe("cleanupSyncedCredentialKeysIfUnused", () => {
319
642
  });
320
643
  });
321
644
  });
322
-
323
- describe("resyncVaultSecretsToCredentialStorePage", () => {
324
- function mockVaultSecretsRows(rows: Array<Record<string, unknown>>) {
325
- const query = {
326
- where: vi.fn(() => query),
327
- orderBy: vi.fn(() => query),
328
- limit: vi.fn(async (limit: number) => rows.slice(0, limit)),
329
- };
330
- mocks.getDb.mockReturnValue({ select: () => ({ from: () => query }) });
331
- return query;
332
- }
333
-
334
- function fakeCredentialStore() {
335
- const store = new Map<string, string>();
336
- mocks.writeAppSecret.mockImplementation(async (args: any) => {
337
- store.set(`${args.scope}:${args.scopeId}:${args.key}`, args.value);
338
- return "app-secret-id";
339
- });
340
- mocks.readAppSecret.mockImplementation(async (ref: any) => {
341
- const value = store.get(`${ref.scope}:${ref.scopeId}:${ref.key}`);
342
- return value === undefined ? null : { value, updatedAt: Date.now() };
343
- });
344
- return store;
345
- }
346
-
347
- afterEach(() => {
348
- mocks.writeAppSecret.mockReset();
349
- mocks.readAppSecret.mockReset();
350
- });
351
-
352
- it("syncs vault secrets from different tenants into their own credential-store scopes", async () => {
353
- fakeCredentialStore();
354
- mockVaultSecretsRows([
355
- {
356
- id: "secret_org",
357
- ownerEmail: "admin@example.test",
358
- orgId: "org_123",
359
- name: "OpenAI API Key",
360
- credentialKey: "OPENAI_API_KEY",
361
- value: "sk-org-key",
362
- },
363
- {
364
- id: "secret_solo",
365
- ownerEmail: "owner@example.test",
366
- orgId: null,
367
- name: "Personal API Key",
368
- credentialKey: "PERSONAL_API_KEY",
369
- value: "sk-personal-key",
370
- },
371
- ]);
372
-
373
- const result = await resyncVaultSecretsToCredentialStorePage();
374
-
375
- expect(result).toEqual({
376
- groups: 2,
377
- failedGroups: 0,
378
- syncedKeys: 2,
379
- nextCursor: null,
380
- });
381
-
382
- const orgScope = credentialStoreScopeForVaultCtx({
383
- ownerEmail: "admin@example.test",
384
- orgId: "org_123",
385
- });
386
- const soloScope = credentialStoreScopeForVaultCtx({
387
- ownerEmail: "owner@example.test",
388
- orgId: null,
389
- });
390
-
391
- await expect(
392
- readAppSecret({ key: "OPENAI_API_KEY", ...orgScope }),
393
- ).resolves.toMatchObject({ value: "sk-org-key" });
394
- await expect(
395
- readAppSecret({ key: "PERSONAL_API_KEY", ...soloScope }),
396
- ).resolves.toMatchObject({ value: "sk-personal-key" });
397
- });
398
-
399
- it("logs and skips a group that fails without blocking the other groups", async () => {
400
- const store = fakeCredentialStore();
401
- const writeImpl = mocks.writeAppSecret.getMockImplementation();
402
- mocks.writeAppSecret.mockImplementation(async (args: any) => {
403
- if (args.key === "BROKEN_KEY") {
404
- throw new Error("simulated credential-store write failure");
405
- }
406
- return writeImpl!(args);
407
- });
408
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
409
-
410
- mockVaultSecretsRows([
411
- {
412
- id: "secret_broken",
413
- ownerEmail: "admin@broken.test",
414
- orgId: "org_broken",
415
- name: "Broken Key",
416
- credentialKey: "BROKEN_KEY",
417
- value: "sk-broken-value",
418
- },
419
- {
420
- id: "secret_solo",
421
- ownerEmail: "owner@example.test",
422
- orgId: null,
423
- name: "Personal API Key",
424
- credentialKey: "PERSONAL_API_KEY",
425
- value: "sk-personal-key",
426
- },
427
- ]);
428
-
429
- const result = await resyncVaultSecretsToCredentialStorePage();
430
-
431
- expect(result).toEqual({
432
- groups: 2,
433
- failedGroups: 1,
434
- syncedKeys: 1,
435
- nextCursor: null,
436
- });
437
-
438
- // The failed org's key never landed in the credential store.
439
- expect(store.get("org:org_broken:BROKEN_KEY")).toBeUndefined();
440
-
441
- const soloScope = credentialStoreScopeForVaultCtx({
442
- ownerEmail: "owner@example.test",
443
- orgId: null,
444
- });
445
- await expect(
446
- readAppSecret({ key: "PERSONAL_API_KEY", ...soloScope }),
447
- ).resolves.toMatchObject({ value: "sk-personal-key" });
448
-
449
- expect(warnSpy).toHaveBeenCalledTimes(1);
450
- const [warnMessage] = warnSpy.mock.calls[0]!;
451
- expect(String(warnMessage)).toContain("BROKEN_KEY");
452
- expect(String(warnMessage)).not.toContain("sk-broken-value");
453
-
454
- warnSpy.mockRestore();
455
- });
456
-
457
- it("rewinds the page cursor before a failed tenant group for retry", async () => {
458
- const store = fakeCredentialStore();
459
- const writeImpl = mocks.writeAppSecret.getMockImplementation();
460
- mocks.writeAppSecret.mockImplementation(async (args: any) => {
461
- if (args.key === "BROKEN_KEY") {
462
- throw new Error("simulated credential-store write failure");
463
- }
464
- return writeImpl!(args);
465
- });
466
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
467
-
468
- const firstQuery = mockVaultSecretsRows([
469
- {
470
- id: "secret_a",
471
- ownerEmail: "owner@example.test",
472
- orgId: null,
473
- name: "Working key",
474
- credentialKey: "WORKING_KEY",
475
- value: "working-value",
476
- },
477
- {
478
- id: "secret_b",
479
- ownerEmail: "broken@example.test",
480
- orgId: "org_broken",
481
- name: "Broken key",
482
- credentialKey: "BROKEN_KEY",
483
- value: "broken-value",
484
- },
485
- {
486
- id: "secret_c",
487
- ownerEmail: "other@example.test",
488
- orgId: null,
489
- name: "Later key",
490
- credentialKey: "LATER_KEY",
491
- value: "later-value",
492
- },
493
- ]);
494
-
495
- const first = await resyncVaultSecretsToCredentialStorePage({ limit: 2 });
496
-
497
- expect(first).toEqual({
498
- groups: 2,
499
- failedGroups: 1,
500
- syncedKeys: 1,
501
- nextCursor: "secret_a",
502
- });
503
- expect(firstQuery.limit).toHaveBeenCalledWith(3);
504
- const ownerScope = credentialStoreScopeForVaultCtx({
505
- ownerEmail: "owner@example.test",
506
- orgId: null,
507
- });
508
- expect(
509
- store.get(`${ownerScope.scope}:${ownerScope.scopeId}:WORKING_KEY`),
510
- ).toBe("working-value");
511
-
512
- mocks.writeAppSecret.mockImplementation(writeImpl!);
513
- const retryQuery = mockVaultSecretsRows([
514
- {
515
- id: "secret_b",
516
- ownerEmail: "broken@example.test",
517
- orgId: "org_broken",
518
- name: "Broken key",
519
- credentialKey: "BROKEN_KEY",
520
- value: "broken-value",
521
- },
522
- {
523
- id: "secret_c",
524
- ownerEmail: "other@example.test",
525
- orgId: null,
526
- name: "Later key",
527
- credentialKey: "LATER_KEY",
528
- value: "later-value",
529
- },
530
- ]);
531
- const retry = await resyncVaultSecretsToCredentialStorePage({
532
- limit: 2,
533
- afterId: first.nextCursor!,
534
- });
535
-
536
- expect(retry.failedGroups).toBe(0);
537
- expect(retry.syncedKeys).toBe(2);
538
- expect(retry.nextCursor).toBeNull();
539
- expect(retryQuery.where).toHaveBeenCalledOnce();
540
- expect(store.get("org:org_broken:BROKEN_KEY")).toBe("broken-value");
541
-
542
- warnSpy.mockRestore();
543
- });
544
-
545
- it("limits each tenant-wide pass and resumes after the returned keyset cursor", async () => {
546
- fakeCredentialStore();
547
- const firstQuery = mockVaultSecretsRows([
548
- {
549
- id: "secret_a",
550
- ownerEmail: "owner@example.test",
551
- orgId: null,
552
- name: "First key",
553
- credentialKey: "FIRST_KEY",
554
- value: "first-value",
555
- },
556
- {
557
- id: "secret_b",
558
- ownerEmail: "owner@example.test",
559
- orgId: null,
560
- name: "Second key",
561
- credentialKey: "SECOND_KEY",
562
- value: "second-value",
563
- },
564
- ]);
565
-
566
- const first = await resyncVaultSecretsToCredentialStorePage({ limit: 1 });
567
- expect(first).toMatchObject({ syncedKeys: 1, nextCursor: "secret_a" });
568
- expect(firstQuery.limit).toHaveBeenCalledWith(2);
569
-
570
- const secondQuery = mockVaultSecretsRows([
571
- {
572
- id: "secret_b",
573
- ownerEmail: "owner@example.test",
574
- orgId: null,
575
- name: "Second key",
576
- credentialKey: "SECOND_KEY",
577
- value: "second-value",
578
- },
579
- ]);
580
- const second = await resyncVaultSecretsToCredentialStorePage({
581
- limit: 1,
582
- afterId: first.nextCursor!,
583
- });
584
- expect(second).toMatchObject({ syncedKeys: 1, nextCursor: null });
585
- expect(secondQuery.where).toHaveBeenCalledOnce();
586
- expect(secondQuery.limit).toHaveBeenCalledWith(2);
587
- });
588
- });
589
-
590
- describe("syncGrantsToApp", () => {
591
- function fakeCredentialStore() {
592
- const store = new Map<string, string>();
593
- mocks.writeAppSecret.mockImplementation(async (args: any) => {
594
- store.set(`${args.scope}:${args.scopeId}:${args.key}`, args.value);
595
- return "app-secret-id";
596
- });
597
- return store;
598
- }
599
-
600
- function mockWorkspace(
601
- caller: { ownerEmail: string; orgId: string | null },
602
- secretRows: Array<Record<string, unknown>>,
603
- ) {
604
- mocks.currentOwnerEmail.mockReturnValue(caller.ownerEmail);
605
- mocks.currentOrgId.mockReturnValue(caller.orgId);
606
- mocks.readOrgMemberRole.mockResolvedValue("owner");
607
- mocks.getOrgSetting.mockResolvedValue(null);
608
- mocks.getUserSetting.mockResolvedValue(null);
609
- mocks.discoverAgents.mockResolvedValue([
610
- { id: "coach", url: "https://coach.example.test" },
611
- ]);
612
- mocks.getDb.mockReturnValue({
613
- select: () => ({
614
- from: () => ({
615
- where: () => ({ orderBy: async () => secretRows }),
616
- }),
617
- }),
618
- insert: () => ({ values: async () => undefined }),
619
- });
620
- }
621
-
622
- afterEach(() => {
623
- mocks.writeAppSecret.mockReset();
624
- });
625
-
626
- // The regression: `all-apps` mode lists secrets across orgs, and syncing them
627
- // under the caller's ctx upserts copies of another org's credentials into
628
- // whichever org the person clicking Sync happened to be in. Because
629
- // writeAppSecret upserts, that copies rather than moves, so credential
630
- // material accumulates permanently in the wrong org.
631
- it("writes each secret under its own org, not the caller's active org", async () => {
632
- const store = fakeCredentialStore();
633
- mockWorkspace({ ownerEmail: "clicker@example.test", orgId: "org_caller" }, [
634
- {
635
- id: "secret_builder",
636
- ownerEmail: "admin@example.test",
637
- orgId: "org_owner",
638
- name: "Academy Site URL",
639
- credentialKey: "ACADEMY_CONVEX_SITE_URL",
640
- value: "https://academy.example.test",
641
- },
642
- {
643
- id: "secret_solo",
644
- ownerEmail: "owner@example.test",
645
- orgId: null,
646
- name: "Personal API Key",
647
- credentialKey: "PERSONAL_API_KEY",
648
- value: "sk-test-personal",
649
- },
650
- ]);
651
-
652
- const result = await syncGrantsToApp("coach");
653
-
654
- expect(store.get("org:org_owner:ACADEMY_CONVEX_SITE_URL")).toBe(
655
- "https://academy.example.test",
656
- );
657
- expect(
658
- store.get("workspace:solo:owner@example.test:PERSONAL_API_KEY"),
659
- ).toBe("sk-test-personal");
660
-
661
- const callerScoped = [...store.keys()].filter((key) =>
662
- key.startsWith("org:org_caller:"),
663
- );
664
- expect(callerScoped).toEqual([]);
665
-
666
- expect(result.credentialStores).toEqual([
667
- { scope: "org", scopeId: "org_owner", synced: 1 },
668
- {
669
- scope: "workspace",
670
- scopeId: "solo:owner@example.test",
671
- synced: 1,
672
- },
673
- ]);
674
- expect(result.synced).toBe(2);
675
- });
676
-
677
- it("still syncs the caller's own org secrets into that org", async () => {
678
- const store = fakeCredentialStore();
679
- mockWorkspace({ ownerEmail: "clicker@example.test", orgId: "org_caller" }, [
680
- {
681
- id: "secret_own",
682
- ownerEmail: "clicker@example.test",
683
- orgId: "org_caller",
684
- name: "Shared API Key",
685
- credentialKey: "SHARED_API_KEY",
686
- value: "sk-test-shared",
687
- },
688
- ]);
689
-
690
- const result = await syncGrantsToApp("coach");
691
-
692
- expect(store.get("org:org_caller:SHARED_API_KEY")).toBe("sk-test-shared");
693
- expect(result.credentialStores).toEqual([
694
- { scope: "org", scopeId: "org_caller", synced: 1 },
695
- ]);
696
- });
697
-
698
- // A row with no ownerEmail cannot name its own tenant, so the caller's ctx is
699
- // the only scope available — the pre-existing ctxForSecretRow fallback.
700
- it("falls back to the caller ctx for a secret row with no owner", async () => {
701
- const store = fakeCredentialStore();
702
- mockWorkspace({ ownerEmail: "clicker@example.test", orgId: "org_caller" }, [
703
- {
704
- id: "secret_ownerless",
705
- ownerEmail: "",
706
- orgId: null,
707
- name: "Legacy Key",
708
- credentialKey: "LEGACY_KEY",
709
- value: "sk-test-legacy",
710
- },
711
- ]);
712
-
713
- await syncGrantsToApp("coach");
714
-
715
- expect(store.get("org:org_caller:LEGACY_KEY")).toBe("sk-test-legacy");
716
- });
717
- });