@agent-native/dispatch 0.42.7-nightly-20261113032548 → 0.42.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +5 -12
  2. package/README.md +20 -18
  3. package/dist/actions/create-vault-grant.d.ts +2 -1
  4. package/dist/actions/create-vault-secret.d.ts +1 -1
  5. package/dist/actions/create-vault-secret.js +2 -2
  6. package/dist/actions/create-vault-secret.js.map +1 -1
  7. package/dist/actions/grant-vault-secrets-to-app.d.ts +1 -0
  8. package/dist/actions/list-vault-grants.d.ts +1 -0
  9. package/dist/actions/list-vault-secret-options.js +1 -1
  10. package/dist/actions/list-vault-secret-options.js.map +1 -1
  11. package/dist/actions/list-vault-secrets.js +3 -5
  12. package/dist/actions/list-vault-secrets.js.map +1 -1
  13. package/dist/actions/revoke-vault-grant.d.ts +2 -1
  14. package/dist/actions/update-vault-secret.d.ts +1 -1
  15. package/dist/actions/update-vault-secret.js +2 -2
  16. package/dist/actions/update-vault-secret.js.map +1 -1
  17. package/dist/db/migrations.d.ts.map +1 -1
  18. package/dist/db/migrations.js +19 -0
  19. package/dist/db/migrations.js.map +1 -1
  20. package/dist/db/schema.d.ts +8 -185
  21. package/dist/db/schema.d.ts.map +1 -1
  22. package/dist/db/schema.js +3 -13
  23. package/dist/db/schema.js.map +1 -1
  24. package/dist/routes/pages/vault.d.ts.map +1 -1
  25. package/dist/routes/pages/vault.js +1 -1
  26. package/dist/routes/pages/vault.js.map +1 -1
  27. package/dist/server/lib/vault-store.d.ts +67 -93
  28. package/dist/server/lib/vault-store.d.ts.map +1 -1
  29. package/dist/server/lib/vault-store.js +227 -280
  30. package/dist/server/lib/vault-store.js.map +1 -1
  31. package/dist/server/plugins/db.d.ts.map +1 -1
  32. package/dist/server/plugins/db.js +2 -0
  33. package/dist/server/plugins/db.js.map +1 -1
  34. package/package.json +4 -4
  35. package/src/actions/create-vault-secret.ts +2 -5
  36. package/src/actions/list-vault-secret-options.ts +1 -1
  37. package/src/actions/list-vault-secrets.ts +3 -8
  38. package/src/actions/update-vault-secret.ts +2 -6
  39. package/src/db/migrations.spec.ts +117 -1
  40. package/src/db/migrations.ts +19 -0
  41. package/src/db/schema.ts +3 -14
  42. package/src/routes/pages/vault.tsx +0 -4
  43. package/src/server/lib/vault-store.spec.ts +1188 -475
  44. package/src/server/lib/vault-store.ts +343 -405
  45. package/src/server/plugins/db.ts +2 -0
@@ -1,644 +1,1357 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import {
6
+ afterAll,
7
+ beforeAll,
8
+ beforeEach,
9
+ describe,
10
+ expect,
11
+ it,
12
+ vi,
13
+ } from "vitest";
14
+
15
+ // Every test here runs the store against a real database: the claims worth
16
+ // proving are about rows (which table holds a value, which scope a key lands
17
+ // in, which grant matches), and a mocked query cannot fail for them.
18
+ vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
2
19
 
3
20
  const mocks = vi.hoisted(() => ({
4
- currentOrgId: vi.fn(),
5
- currentOwnerEmail: vi.fn(),
6
- deleteAppSecret: vi.fn(),
7
- discoverAgents: vi.fn(),
8
- getDbExec: vi.fn(),
9
- getDb: vi.fn(),
10
- getOrgSetting: vi.fn(),
11
- getUserSetting: vi.fn(),
12
- listAppSecretsForScope: vi.fn(),
13
- readAppSecret: vi.fn(),
14
- recordAudit: vi.fn(),
15
- readOrgMemberRole: vi.fn(),
16
- writeAppSecret: vi.fn(),
21
+ discoverAgents: vi.fn(async () => [] as unknown[]),
22
+ ssrfSafeFetch: vi.fn(),
17
23
  }));
18
24
 
19
- vi.mock("@agent-native/core/secrets", async (importOriginal) => ({
20
- ...(await importOriginal<typeof import("@agent-native/core/secrets")>()),
21
- deleteAppSecret: mocks.deleteAppSecret,
22
- listAppSecretsForScope: mocks.listAppSecretsForScope,
23
- readAppSecret: mocks.readAppSecret,
24
- writeAppSecret: mocks.writeAppSecret,
25
+ vi.mock("@agent-native/core/server/agent-discovery", () => ({
26
+ discoverAgents: mocks.discoverAgents,
25
27
  }));
26
28
 
27
- vi.mock("@agent-native/core/db", async (importOriginal) => ({
28
- ...(await importOriginal<typeof import("@agent-native/core/db")>()),
29
- getDbExec: mocks.getDbExec,
29
+ vi.mock("@agent-native/core/extensions/url-safety", async (importOriginal) => ({
30
+ ...(await importOriginal<
31
+ typeof import("@agent-native/core/extensions/url-safety")
32
+ >()),
33
+ ssrfSafeFetch: mocks.ssrfSafeFetch,
30
34
  }));
31
35
 
32
- vi.mock("@agent-native/core/server", async (importOriginal) => ({
33
- ...(await importOriginal<typeof import("@agent-native/core/server")>()),
34
- readOrgMemberRole: (...args: unknown[]) => mocks.readOrgMemberRole(...args),
35
- }));
36
+ const admin = "admin+vault@example.test";
37
+ const member = "member+vault@example.test";
38
+ const orgId = "org_vault";
39
+ const otherOrgId = "org_vault_other";
40
+ const PLAINTEXT = "fake-secret-value-1111";
36
41
 
37
- vi.mock("@agent-native/core/server/agent-discovery", () => ({
38
- discoverAgents: mocks.discoverAgents,
39
- }));
42
+ const originalEnv = {
43
+ APP_NAME: process.env.APP_NAME,
44
+ DATABASE_URL: process.env.DATABASE_URL,
45
+ DISPATCH_DATABASE_URL: process.env.DISPATCH_DATABASE_URL,
46
+ };
40
47
 
41
- vi.mock("@agent-native/core/settings", () => ({
42
- getOrgSetting: mocks.getOrgSetting,
43
- getUserSetting: mocks.getUserSetting,
44
- putOrgSetting: vi.fn(),
45
- putUserSetting: vi.fn(),
46
- }));
48
+ let tempDir: string | null = null;
47
49
 
48
- vi.mock("./dispatch-store.js", () => ({
49
- currentOrgId: mocks.currentOrgId,
50
- currentOwnerEmail: mocks.currentOwnerEmail,
51
- recordAudit: mocks.recordAudit,
52
- }));
50
+ function restoreEnv() {
51
+ for (const [key, value] of Object.entries(originalEnv)) {
52
+ if (value === undefined) delete process.env[key];
53
+ else process.env[key] = value;
54
+ }
55
+ }
56
+
57
+ async function boot() {
58
+ const [{ runWithRequestContext }, db, secrets, settings, vault] =
59
+ await Promise.all([
60
+ import("@agent-native/core/server"),
61
+ import("@agent-native/core/db"),
62
+ import("@agent-native/core/secrets"),
63
+ import("@agent-native/core/settings"),
64
+ import("./vault-store.js"),
65
+ ]);
66
+ const exec = db.getDbExec();
67
+ await exec.execute({
68
+ sql: `CREATE TABLE IF NOT EXISTS org_members (
69
+ id TEXT PRIMARY KEY,
70
+ org_id TEXT NOT NULL,
71
+ email TEXT NOT NULL,
72
+ role TEXT NOT NULL,
73
+ joined_at BIGINT NOT NULL,
74
+ federation_removal_pending_at INTEGER
75
+ )`,
76
+ args: [],
77
+ });
78
+ for (const [id, org, email, role] of [
79
+ ["vault-admin", orgId, admin, "admin"],
80
+ ["vault-member", orgId, member, "member"],
81
+ ["vault-other-owner", otherOrgId, admin, "owner"],
82
+ ]) {
83
+ await exec.execute({
84
+ sql: "INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, ?, ?)",
85
+ args: [id, org, email, role, Date.now()],
86
+ });
87
+ }
88
+ // The credential and settings stores create their tables on first use.
89
+ await secrets.listAppSecretSummaries("org", orgId);
90
+ await settings.getOrgSetting(orgId, "dispatch-vault-access-settings");
91
+
92
+ const as = <T>(
93
+ userEmail: string,
94
+ run: () => Promise<T>,
95
+ org: string | null = orgId,
96
+ ): Promise<T> =>
97
+ runWithRequestContext({ userEmail, orgId: org ?? undefined }, run);
98
+ // raw-sql-ok: a test helper; every caller passes a literal statement.
99
+ const rows = async (sql: string, args: unknown[] = []) =>
100
+ (await exec.execute({ sql, args })).rows;
101
+ const orgRef = (key: string) => ({
102
+ key,
103
+ scope: "org" as const,
104
+ scopeId: orgId,
105
+ });
106
+ // One statement per table: no interpolated identifiers.
107
+ const everythingStored = async () =>
108
+ JSON.stringify(
109
+ await Promise.all([
110
+ rows("SELECT to_jsonb(t) AS row FROM app_secrets t"),
111
+ rows("SELECT to_jsonb(t) AS row FROM vault_secrets t"),
112
+ rows("SELECT to_jsonb(t) AS row FROM vault_grants t"),
113
+ rows("SELECT to_jsonb(t) AS row FROM vault_requests t"),
114
+ rows("SELECT to_jsonb(t) AS row FROM vault_audit_log t"),
115
+ rows("SELECT to_jsonb(t) AS row FROM dispatch_audit_events t"),
116
+ ]),
117
+ );
118
+ return { as, exec, rows, orgRef, secrets, vault, everythingStored };
119
+ }
120
+
121
+ let current: Awaited<ReturnType<typeof boot>>;
53
122
 
54
- vi.mock("../../db/index.js", async (importOriginal) => {
55
- const actual = await importOriginal<typeof import("../../db/index.js")>();
56
- return {
57
- ...actual,
58
- getDb: mocks.getDb,
59
- };
123
+ beforeAll(async () => {
124
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "dispatch-vault-store-"));
125
+ process.env.DATABASE_URL = `pglite:${tempDir}`;
126
+ delete process.env.APP_NAME;
127
+ delete process.env.DISPATCH_DATABASE_URL;
128
+
129
+ const [{ runMigrations, closeDbExec }, { dispatchMigrations }] =
130
+ await Promise.all([
131
+ import("@agent-native/core/db"),
132
+ import("../../db/migrations.js"),
133
+ ]);
134
+ await runMigrations(dispatchMigrations, {
135
+ table: "dispatch_migrations",
136
+ })({});
137
+ await closeDbExec();
138
+ current = await boot();
60
139
  });
61
140
 
62
- import { schema } from "../../db/index.js";
63
- import {
64
- assertCanManageVault,
65
- cleanupSyncedCredentialKeysIfUnused,
66
- createSecret,
67
- credentialStoreScopeForVaultCtx,
68
- getGrant,
69
- getVaultSecretMetadata,
70
- listGrants,
71
- listVaultSecretMetadata,
72
- updateSecret,
73
- } from "./vault-store.js";
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();
141
+ afterAll(async () => {
142
+ try {
143
+ const { closeDbExec } = await import("@agent-native/core/db");
144
+ await closeDbExec();
145
+ } catch {
146
+ // The database may never have opened if setup failed first.
147
+ }
148
+ restoreEnv();
149
+ if (tempDir) {
150
+ fs.rmSync(tempDir, { recursive: true, force: true });
151
+ tempDir = null;
152
+ }
82
153
  });
83
154
 
84
- afterEach(() => {
85
- vi.clearAllMocks();
86
- vi.unstubAllEnvs();
155
+ beforeEach(async () => {
156
+ // Each test starts from an empty vault, in the same database.
157
+ for (const statement of [
158
+ "DELETE FROM app_secrets",
159
+ "DELETE FROM vault_secrets",
160
+ "DELETE FROM vault_grants",
161
+ "DELETE FROM vault_requests",
162
+ "DELETE FROM vault_audit_log",
163
+ "DELETE FROM dispatch_audit_events",
164
+ "DELETE FROM settings",
165
+ ]) {
166
+ await current.exec.execute({ sql: statement, args: [] });
167
+ }
168
+ mocks.discoverAgents.mockReset();
169
+ mocks.discoverAgents.mockResolvedValue([]);
170
+ mocks.ssrfSafeFetch.mockReset();
87
171
  });
88
172
 
173
+ /** The vault under test, a request-context runner, and direct row access. */
174
+ async function load() {
175
+ return current;
176
+ }
177
+
89
178
  describe("credentialStoreScopeForVaultCtx", () => {
90
- it("uses org scope when vault sync runs inside an org", () => {
179
+ it("uses org scope when the caller has an organization", async () => {
180
+ const { vault } = await load();
91
181
  expect(
92
- credentialStoreScopeForVaultCtx({
93
- ownerEmail: "admin@example.test",
182
+ vault.credentialStoreScopeForVaultCtx({
183
+ ownerEmail: admin,
94
184
  orgId: "org_123",
95
185
  }),
96
186
  ).toEqual({ scope: "org", scopeId: "org_123" });
97
187
  });
98
188
 
99
- it("uses workspace solo scope when no org is active", () => {
189
+ it("uses the caller's own workspace scope when no organization is active", async () => {
190
+ const { vault } = await load();
100
191
  expect(
101
- credentialStoreScopeForVaultCtx({
102
- ownerEmail: "owner@example.test",
103
- orgId: null,
104
- }),
105
- ).toEqual({
106
- scope: "workspace",
107
- scopeId: "solo:owner@example.test",
108
- });
192
+ vault.credentialStoreScopeForVaultCtx({ ownerEmail: admin, orgId: null }),
193
+ ).toEqual({ scope: "workspace", scopeId: `solo:${admin}` });
109
194
  });
110
195
  });
111
196
 
112
197
  describe("vault authorization", () => {
113
- it("rejects an organization member before reading shared vault values", async () => {
114
- mocks.currentOrgId.mockReturnValue("org_123");
115
- mocks.currentOwnerEmail.mockReturnValue("member@example.test");
116
- mocks.readOrgMemberRole.mockResolvedValue("member");
117
-
118
- await expect(assertCanManageVault()).rejects.toMatchObject({
119
- message:
120
- "Only organization owners and admins can manage the workspace vault.",
121
- statusCode: 403,
198
+ it.each([
199
+ ["owner", "vault-owner-role"],
200
+ ["admin", "vault-admin-role"],
201
+ ])("lets an organization %s manage the vault", async (role, id) => {
202
+ const { as, exec, vault } = await load();
203
+ await exec.execute({
204
+ sql: "INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, ?, ?)",
205
+ args: [id, orgId, `${role}+vault@example.test`, role, Date.now()],
122
206
  });
207
+
208
+ await expect(
209
+ as(`${role}+vault@example.test`, () => vault.assertCanManageVault()),
210
+ ).resolves.toBeUndefined();
123
211
  });
124
212
 
125
- it("rejects organization members before listing or reading grants", async () => {
126
- mocks.currentOrgId.mockReturnValue("org_123");
127
- mocks.currentOwnerEmail.mockReturnValue("member@example.test");
128
- mocks.readOrgMemberRole.mockResolvedValue("member");
213
+ it("rejects an organization member before anything is read or written", async () => {
214
+ const { as, rows, vault } = await load();
215
+ const message =
216
+ "Only organization owners and admins can manage the workspace vault.";
129
217
 
130
- await expect(listGrants()).rejects.toThrow(
131
- "Only organization owners and admins can manage the workspace vault.",
218
+ await as(admin, () =>
219
+ vault.createSecret({
220
+ credentialKey: "FAKE_API_KEY",
221
+ value: PLAINTEXT,
222
+ name: "Fake API key",
223
+ }),
132
224
  );
133
- await expect(getGrant("grant-1")).rejects.toThrow(
134
- "Only organization owners and admins can manage the workspace vault.",
225
+ const [{ id }] = (await rows("SELECT id FROM app_secrets")) as [
226
+ { id: string },
227
+ ];
228
+
229
+ await expect(as(member, () => vault.listSecrets())).rejects.toThrow(
230
+ message,
135
231
  );
136
- expect(mocks.getDb).not.toHaveBeenCalled();
232
+ await expect(
233
+ as(member, () =>
234
+ vault.createSecret({
235
+ credentialKey: "OTHER_KEY",
236
+ value: PLAINTEXT,
237
+ name: "Other",
238
+ }),
239
+ ),
240
+ ).rejects.toMatchObject({ message, statusCode: 403 });
241
+ await expect(
242
+ as(member, () => vault.updateSecret(id, { name: "Renamed" })),
243
+ ).rejects.toThrow(message);
244
+ await expect(as(member, () => vault.deleteSecret(id))).rejects.toThrow(
245
+ message,
246
+ );
247
+ await expect(as(member, () => vault.listGrants())).rejects.toThrow(message);
248
+ await expect(as(member, () => vault.getGrant("grant-1"))).rejects.toThrow(
249
+ message,
250
+ );
251
+
252
+ expect(await rows("SELECT key, label FROM app_secrets")).toEqual([
253
+ { key: "FAKE_API_KEY", label: "Fake API key" },
254
+ ]);
137
255
  });
138
256
 
139
- it.each(["owner", "admin"])(
140
- "allows an organization %s to manage shared vault values",
141
- async (role) => {
142
- mocks.currentOrgId.mockReturnValue("org_123");
143
- mocks.currentOwnerEmail.mockReturnValue(`${role}@example.test`);
144
- mocks.readOrgMemberRole.mockResolvedValue(role);
257
+ it("lets a solo workspace owner manage their own vault", async () => {
258
+ const { as, rows, vault } = await load();
145
259
 
146
- await expect(assertCanManageVault()).resolves.toBeUndefined();
147
- },
148
- );
260
+ const created = await as(
261
+ admin,
262
+ () =>
263
+ vault.createSecret({
264
+ credentialKey: "SOLO_KEY",
265
+ value: PLAINTEXT,
266
+ name: "Solo key",
267
+ }),
268
+ null,
269
+ );
270
+
271
+ expect(created.credentialKey).toBe("SOLO_KEY");
272
+ expect(await rows("SELECT scope, scope_id FROM app_secrets")).toEqual([
273
+ { scope: "workspace", scope_id: `solo:${admin}` },
274
+ ]);
275
+ });
276
+ });
149
277
 
150
- it("caps a delegated owner before vault management", async () => {
151
- mocks.currentOrgId.mockReturnValue("org_123");
152
- mocks.currentOwnerEmail.mockReturnValue("owner@example.test");
153
- mocks.readOrgMemberRole.mockResolvedValue("member");
278
+ describe("a vault key is one app_secrets row", () => {
279
+ it("stores the value only in the encrypted column and leaves vault_secrets alone", async () => {
280
+ const { as, rows, secrets, vault, everythingStored } = await load();
281
+ const legacy = [
282
+ "legacy-vault-id",
283
+ admin,
284
+ orgId,
285
+ "Legacy key",
286
+ "LEGACY_KEY",
287
+ "legacy-plaintext-value",
288
+ admin,
289
+ 1,
290
+ 2,
291
+ ];
292
+ await rows(
293
+ `INSERT INTO vault_secrets (id, owner_email, org_id, name, credential_key, value, created_by, created_at, updated_at)
294
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
295
+ legacy,
296
+ );
297
+ const legacyBefore = await rows("SELECT * FROM vault_secrets");
298
+
299
+ const created = await as(admin, () =>
300
+ vault.createSecret({
301
+ credentialKey: "FAKE_API_KEY",
302
+ value: PLAINTEXT,
303
+ name: "Fake API key",
304
+ provider: "other",
305
+ description: "Used by the tests",
306
+ }),
307
+ );
308
+ await as(admin, () =>
309
+ vault.updateSecret(created.id, { value: "fake-rotated-value-2222" }),
310
+ );
311
+ await as(admin, () =>
312
+ vault.updateSecret(created.id, { credentialKey: "FAKE_API_KEY_V2" }),
313
+ );
154
314
 
155
- await expect(assertCanManageVault()).rejects.toMatchObject({
156
- statusCode: 403,
157
- message:
158
- "Only organization owners and admins can manage the workspace vault.",
315
+ expect(created).toMatchObject({
316
+ name: "Fake API key",
317
+ credentialKey: "FAKE_API_KEY",
318
+ last4: "••••1111",
319
+ valueStatus: "stored",
320
+ provider: "other",
321
+ description: "Used by the tests",
322
+ createdBy: admin,
323
+ });
324
+ const [stored] = await rows("SELECT * FROM app_secrets WHERE id = ?", [
325
+ created.id,
326
+ ]);
327
+ expect(stored).toMatchObject({
328
+ scope: "org",
329
+ scope_id: orgId,
330
+ key: "FAKE_API_KEY_V2",
331
+ label: "Fake API key",
332
+ provider: "other",
333
+ description: "Used by the tests",
334
+ created_by: admin,
159
335
  });
160
- expect(mocks.readOrgMemberRole).toHaveBeenCalledWith(
161
- "org_123",
162
- "owner@example.test",
336
+ expect(String(stored.encrypted_value)).toMatch(/^v1:/);
337
+ expect(
338
+ (
339
+ await secrets.readAppSecret({
340
+ key: "FAKE_API_KEY_V2",
341
+ scope: "org",
342
+ scopeId: orgId,
343
+ })
344
+ )?.value,
345
+ ).toBe("fake-rotated-value-2222");
346
+
347
+ const everything = await everythingStored();
348
+ expect(everything).not.toContain(PLAINTEXT);
349
+ expect(everything).not.toContain("fake-rotated-value-2222");
350
+ expect(await rows("SELECT * FROM vault_secrets")).toEqual(legacyBefore);
351
+ });
352
+
353
+ it("uses the app_secrets row id as the secret id everywhere", async () => {
354
+ const { as, rows, vault } = await load();
355
+
356
+ const created = await as(admin, () =>
357
+ vault.createSecret({
358
+ credentialKey: "FAKE_API_KEY",
359
+ value: PLAINTEXT,
360
+ name: "Fake API key",
361
+ }),
163
362
  );
363
+
364
+ const [row] = await rows("SELECT id FROM app_secrets");
365
+ expect(created.id).toBe(row.id);
366
+ expect(await as(admin, () => vault.getSecret(created.id))).toMatchObject({
367
+ id: row.id,
368
+ credentialKey: "FAKE_API_KEY",
369
+ });
370
+ expect(
371
+ (await as(admin, () => vault.listSecretOptions())).map((s) => s.id),
372
+ ).toEqual([row.id]);
373
+ expect(
374
+ (await as(admin, () => vault.listSecrets())).map((s) => s.id),
375
+ ).toEqual([row.id]);
164
376
  });
165
377
 
166
- it("allows a solo workspace owner to manage their own vault", async () => {
167
- mocks.currentOrgId.mockReturnValue(null);
378
+ it("rejects an empty key or value instead of saving a key with nothing behind it", async () => {
379
+ const { as, rows, vault } = await load();
168
380
 
169
- await expect(assertCanManageVault()).resolves.toBeUndefined();
170
- expect(mocks.getDbExec).not.toHaveBeenCalled();
381
+ await expect(
382
+ as(admin, () =>
383
+ vault.createSecret({ credentialKey: " ", value: PLAINTEXT, name: "x" }),
384
+ ),
385
+ ).rejects.toThrow("Credential key is required");
386
+ await expect(
387
+ as(admin, () =>
388
+ vault.createSecret({
389
+ credentialKey: "FAKE_API_KEY",
390
+ value: "",
391
+ name: "x",
392
+ }),
393
+ ),
394
+ ).rejects.toThrow("Secret value is required");
395
+
396
+ expect(await rows("SELECT * FROM app_secrets")).toEqual([]);
171
397
  });
172
- });
173
398
 
174
- describe("vault secret metadata", () => {
175
- const row = (overrides: Record<string, unknown> = {}) =>
176
- ({
177
- id: "secret-1",
178
- ownerEmail: "admin@example.test",
179
- orgId: "org_123",
180
- name: "Test key",
181
- credentialKey: "TEST_KEY",
182
- value: "",
183
- provider: "other",
184
- description: "Fake test credential",
185
- createdBy: "admin@example.test",
186
- createdAt: 1,
187
- updatedAt: 2,
188
- ...overrides,
189
- }) as any;
190
- const ctx = { ownerEmail: "admin@example.test", orgId: "org_123" };
191
-
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
- ]);
399
+ it("updates a key that already exists when it is created again, and keeps its creator", async () => {
400
+ const { as, exec, rows, secrets, vault, orgRef } = await load();
401
+ const secondAdmin = "second-admin+vault@example.test";
402
+ await exec.execute({
403
+ sql: "INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, ?, ?)",
404
+ args: ["vault-second-admin", orgId, secondAdmin, "admin", Date.now()],
405
+ });
406
+ const first = await as(admin, () =>
407
+ vault.createSecret({
408
+ credentialKey: "FAKE_API_KEY",
409
+ value: PLAINTEXT,
410
+ name: "First label",
411
+ provider: "other",
412
+ }),
413
+ );
198
414
 
199
- const metadata = await listVaultSecretMetadata(
200
- [row(), row({ id: "secret-2", credentialKey: "OTHER_KEY" })],
201
- ctx,
415
+ const second = await as(secondAdmin, () =>
416
+ vault.createSecret({
417
+ credentialKey: "FAKE_API_KEY",
418
+ value: "fake-rotated-value-2222",
419
+ name: "Second label",
420
+ }),
202
421
  );
203
422
 
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");
423
+ expect(second.id).toBe(first.id);
424
+ expect(second).toMatchObject({
425
+ name: "Second label",
426
+ provider: null,
427
+ createdBy: admin,
428
+ last4: "••••2222",
429
+ });
430
+ expect(await rows("SELECT id FROM app_secrets")).toHaveLength(1);
431
+ expect((await secrets.readAppSecret(orgRef("FAKE_API_KEY")))?.value).toBe(
432
+ "fake-rotated-value-2222",
433
+ );
209
434
  });
435
+ });
210
436
 
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" }] : [],
437
+ describe("editing a key", () => {
438
+ async function seeded() {
439
+ const loaded = await load();
440
+ const created = await loaded.as(admin, () =>
441
+ loaded.vault.createSecret({
442
+ credentialKey: "FAKE_API_KEY",
443
+ value: PLAINTEXT,
444
+ name: "Fake API key",
445
+ provider: "other",
446
+ description: "Used by the tests",
447
+ }),
214
448
  );
449
+ const ciphertext = async () =>
450
+ loaded.rows(
451
+ "SELECT encrypted_value, shared_encrypted_value FROM app_secrets WHERE id = ?",
452
+ [created.id],
453
+ );
454
+ return { ...loaded, created, ciphertext };
455
+ }
456
+
457
+ it("changes the label, provider and description without touching the stored value", async () => {
458
+ const { as, vault, created, ciphertext, secrets, orgRef } = await seeded();
459
+ const before = await ciphertext();
215
460
 
216
- const metadata = await listVaultSecretMetadata(
217
- [row(), row({ id: "solo-1", orgId: null, credentialKey: "SOLO_KEY" })],
218
- ctx,
461
+ const updated = await as(admin, () =>
462
+ vault.updateSecret(created.id, {
463
+ name: "Renamed label",
464
+ provider: null,
465
+ description: "New note",
466
+ }),
219
467
  );
220
468
 
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"]);
469
+ expect(updated).toMatchObject({
470
+ name: "Renamed label",
471
+ provider: null,
472
+ description: "New note",
473
+ credentialKey: "FAKE_API_KEY",
474
+ last4: "••••1111",
475
+ });
476
+ expect(await ciphertext()).toEqual(before);
477
+ expect((await secrets.readAppSecret(orgRef("FAKE_API_KEY")))?.value).toBe(
478
+ PLAINTEXT,
479
+ );
224
480
  });
225
481
 
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
- ]);
482
+ it("rotates the value and keeps every label field", async () => {
483
+ const { as, vault, created, ciphertext } = await seeded();
484
+ const before = await ciphertext();
231
485
 
232
- const [unreadable, missing] = await listVaultSecretMetadata(
233
- [row(), row({ id: "secret-2", credentialKey: "ABSENT_KEY" })],
234
- ctx,
486
+ const updated = await as(admin, () =>
487
+ vault.updateSecret(created.id, { value: "fake-rotated-value-2222" }),
235
488
  );
236
489
 
237
- expect(unreadable).toMatchObject({ last4: "", valueStatus: "unreadable" });
238
- expect(missing).toMatchObject({ last4: "", valueStatus: "missing" });
490
+ expect(updated).toMatchObject({
491
+ name: "Fake API key",
492
+ provider: "other",
493
+ description: "Used by the tests",
494
+ last4: "••••2222",
495
+ });
496
+ expect(await ciphertext()).not.toEqual(before);
239
497
  });
240
498
 
241
- it("reads a single preview straight from the credential store", async () => {
242
- mocks.readAppSecret.mockResolvedValue({
243
- value: "sk-live",
244
- last4: "••••live",
245
- });
499
+ it("accepts a bare value, as the older call form did", async () => {
500
+ const { as, vault, created } = await seeded();
246
501
 
247
- const metadata = await getVaultSecretMetadata(row(), ctx);
502
+ const updated = await as(admin, () =>
503
+ vault.updateSecret(created.id, "fake-rotated-value-2222"),
504
+ );
248
505
 
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();
506
+ expect(updated.last4).toBe("••••2222");
507
+ });
508
+
509
+ it("rejects an empty value or name and changes nothing", async () => {
510
+ const { as, vault, created, ciphertext } = await seeded();
511
+ const before = await ciphertext();
512
+
513
+ await expect(
514
+ as(admin, () => vault.updateSecret(created.id, { value: "" })),
515
+ ).rejects.toThrow("Secret value is required");
516
+ await expect(
517
+ as(admin, () => vault.updateSecret(created.id, { name: " " })),
518
+ ).rejects.toThrow("Secret name is required");
519
+
520
+ expect(await ciphertext()).toEqual(before);
260
521
  });
261
522
 
262
- it("reports a single key with no copy as missing", async () => {
263
- mocks.readAppSecret.mockResolvedValue(null);
523
+ it("renames a key in place: the value, the id and the creator come along", async () => {
524
+ const { as, vault, created, ciphertext, secrets, orgRef } = await seeded();
525
+ const before = await ciphertext();
526
+
527
+ const renamed = await as(admin, () =>
528
+ vault.updateSecret(created.id, { credentialKey: "FAKE_API_KEY_V2" }),
529
+ );
264
530
 
265
- expect(await getVaultSecretMetadata(row(), ctx)).toMatchObject({
266
- last4: "",
267
- valueStatus: "missing",
531
+ expect(renamed).toMatchObject({
532
+ id: created.id,
533
+ credentialKey: "FAKE_API_KEY_V2",
534
+ name: "Fake API key",
535
+ createdBy: admin,
536
+ last4: "••••1111",
268
537
  });
538
+ expect(await ciphertext()).toEqual(before);
539
+ expect(await secrets.readAppSecret(orgRef("FAKE_API_KEY"))).toBeNull();
540
+ expect(
541
+ (await secrets.readAppSecret(orgRef("FAKE_API_KEY_V2")))?.value,
542
+ ).toBe(PLAINTEXT);
269
543
  });
270
544
 
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
- }),
545
+ it("refuses to rename onto a key that exists in the scope, whoever created it", async () => {
546
+ const { as, rows, vault, created, secrets, orgRef, ciphertext } =
547
+ await seeded();
548
+ await secrets.writeAppSecret({
549
+ ...orgRef("APP_OWNED_KEY"),
550
+ value: "fake-app-owned-value",
551
+ });
552
+ const before = await ciphertext();
553
+
554
+ await expect(
555
+ as(admin, () =>
556
+ vault.updateSecret(created.id, { credentialKey: "APP_OWNED_KEY" }),
557
+ ),
558
+ ).rejects.toThrow('Credential key "APP_OWNED_KEY" is already in use');
559
+
560
+ expect(await ciphertext()).toEqual(before);
561
+ expect((await secrets.readAppSecret(orgRef("APP_OWNED_KEY")))?.value).toBe(
562
+ "fake-app-owned-value",
276
563
  );
277
- expect(await getVaultSecretMetadata(row(), ctx)).toMatchObject({
278
- last4: "",
279
- valueStatus: "unreadable",
564
+ expect(
565
+ (await rows("SELECT key FROM app_secrets ORDER BY key")).map(
566
+ (row) => row.key,
567
+ ),
568
+ ).toEqual(["APP_OWNED_KEY", "FAKE_API_KEY"]);
569
+ });
570
+
571
+ it("says a key is missing instead of editing another scope's row", async () => {
572
+ const { as, vault, created } = await seeded();
573
+
574
+ await expect(
575
+ as(
576
+ admin,
577
+ () => vault.updateSecret(created.id, { name: "Hijacked" }),
578
+ otherOrgId,
579
+ ),
580
+ ).rejects.toThrow("Secret not found");
581
+ await expect(
582
+ as(admin, () => vault.updateSecret("missing-id", { name: "x" })),
583
+ ).rejects.toThrow("Secret not found");
584
+ expect((await as(admin, () => vault.getSecret(created.id)))?.name).toBe(
585
+ "Fake API key",
586
+ );
587
+ });
588
+
589
+ it("marks a key an app registered as Vault-managed once the Vault edits it", async () => {
590
+ const { as, rows, secrets, vault, orgRef } = await load();
591
+ const appRegisteredId = await secrets.writeAppSecret({
592
+ ...orgRef("APP_OWNED_KEY"),
593
+ value: "fake-app-owned-value",
280
594
  });
281
595
 
282
- mocks.readAppSecret.mockRejectedValueOnce(new Error("database down"));
283
- await expect(getVaultSecretMetadata(row(), ctx)).rejects.toThrow(
284
- "database down",
596
+ await as(admin, () =>
597
+ vault.updateSecret(appRegisteredId, { name: "Adopted label" }),
285
598
  );
599
+
600
+ expect(
601
+ await rows("SELECT label, created_by FROM app_secrets WHERE id = ?", [
602
+ appRegisteredId,
603
+ ]),
604
+ ).toEqual([{ label: "Adopted label", created_by: admin }]);
286
605
  });
287
606
  });
288
607
 
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
- },
608
+ describe("deleting a key", () => {
609
+ it("removes the row and revokes the key's grants, leaving other keys alone", async () => {
610
+ const { as, rows, secrets, vault, orgRef } = await load();
611
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "manual" }));
612
+ const doomed = await as(admin, () =>
613
+ vault.createSecret({
614
+ credentialKey: "DOOMED_KEY",
615
+ value: PLAINTEXT,
616
+ name: "Doomed",
334
617
  }),
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
- }),
618
+ );
619
+ const kept = await as(admin, () =>
620
+ vault.createSecret({
621
+ credentialKey: "KEPT_KEY",
622
+ value: "fake-kept-value",
623
+ name: "Kept",
343
624
  }),
625
+ );
626
+ await secrets.writeAppSecret({
627
+ ...orgRef("APP_OWNED_KEY"),
628
+ value: "fake-app-owned-value",
344
629
  });
345
- return writes;
346
- }
630
+ await as(admin, () => vault.createGrant(doomed.id, "mail"));
631
+ await as(admin, () => vault.createGrant(kept.id, "mail"));
347
632
 
348
- function actAsOrgAdmin() {
349
- mocks.currentOwnerEmail.mockReturnValue(admin);
350
- mocks.currentOrgId.mockReturnValue("org_123");
351
- mocks.readOrgMemberRole.mockResolvedValue("admin");
352
- }
633
+ await as(admin, () => vault.deleteSecret(doomed.id));
353
634
 
354
- const orgStore = (key: string) => ({
355
- key,
356
- scope: "org",
357
- scopeId: "org_123",
635
+ expect(
636
+ (await rows("SELECT key FROM app_secrets ORDER BY key")).map(
637
+ (row) => row.key,
638
+ ),
639
+ ).toEqual(["APP_OWNED_KEY", "KEPT_KEY"]);
640
+ expect(
641
+ await rows(
642
+ "SELECT credential_key, status FROM vault_grants ORDER BY credential_key",
643
+ ),
644
+ ).toEqual([
645
+ { credential_key: "DOOMED_KEY", status: "revoked" },
646
+ { credential_key: "KEPT_KEY", status: "active" },
647
+ ]);
648
+ expect(await as(admin, () => vault.getSecret(doomed.id))).toBeNull();
358
649
  });
359
650
 
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",
651
+ it("says a key is missing when the id belongs to another scope", async () => {
652
+ const { as, vault, secrets, orgRef } = await load();
653
+ const id = await secrets.writeAppSecret({
654
+ ...orgRef("APP_OWNED_KEY"),
655
+ value: "fake-app-owned-value",
368
656
  });
369
657
 
370
- expect(mocks.writeAppSecret).toHaveBeenCalledWith({
371
- ...orgStore("OPENAI_API_KEY"),
372
- value: "sk-test-key",
373
- description: "Synced from Dispatch vault: OpenAI API Key",
374
- });
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");
658
+ await expect(
659
+ as(admin, () => vault.deleteSecret(id), otherOrgId),
660
+ ).rejects.toThrow("Secret not found");
661
+ expect(await secrets.readAppSecret(orgRef("APP_OWNED_KEY"))).not.toBeNull();
381
662
  });
382
663
 
383
- it("stores nothing when the vault row cannot be written", async () => {
384
- actAsOrgAdmin();
385
- fakeVaultDb([], { failInsert: new Error("row insert failed") });
664
+ // Runs `body` with a trigger that fires when a grant is revoked, the last
665
+ // write before the store's delete, so whatever the trigger does to
666
+ // app_secrets lands between the store's lookup and its delete.
667
+ // raw-sql-ok: a test helper; each caller passes a literal CREATE FUNCTION.
668
+ async function whileRevokeRaces(
669
+ exec: Awaited<ReturnType<typeof load>>["exec"],
670
+ functionSql: string,
671
+ body: () => Promise<void>,
672
+ ) {
673
+ await exec.execute({ sql: functionSql, args: [] });
674
+ await exec.execute({
675
+ sql: `CREATE TRIGGER race_on_revoke AFTER UPDATE ON vault_grants
676
+ FOR EACH ROW EXECUTE FUNCTION race_on_revoke()`,
677
+ args: [],
678
+ });
679
+ try {
680
+ await body();
681
+ } finally {
682
+ await exec.execute({
683
+ sql: "DROP TRIGGER race_on_revoke ON vault_grants",
684
+ args: [],
685
+ });
686
+ await exec.execute({ sql: "DROP FUNCTION race_on_revoke()", args: [] });
687
+ }
688
+ }
386
689
 
387
- await expect(
388
- createSecret({
389
- credentialKey: "OPENAI_API_KEY",
390
- value: "sk-test-key",
391
- name: "OpenAI API Key",
690
+ it("removes the key it looked up, not another that took over its old name mid-delete", async () => {
691
+ const { as, exec, rows, vault } = await load();
692
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "manual" }));
693
+ const raced = await as(admin, () =>
694
+ vault.createSecret({
695
+ credentialKey: "RACED_KEY",
696
+ value: PLAINTEXT,
697
+ name: "Raced",
392
698
  }),
393
- ).rejects.toThrow("row insert failed");
699
+ );
700
+ await as(admin, () => vault.createGrant(raced.id, "mail"));
701
+
702
+ await whileRevokeRaces(
703
+ exec,
704
+ `CREATE FUNCTION race_on_revoke() RETURNS trigger AS $$
705
+ BEGIN
706
+ UPDATE app_secrets SET key = 'RACED_KEY_RENAMED' WHERE id = NEW.secret_id;
707
+ INSERT INTO app_secrets (id, scope, scope_id, key, encrypted_value, created_at, updated_at)
708
+ SELECT 'replacement-id', scope, scope_id, 'RACED_KEY', encrypted_value, created_at, updated_at
709
+ FROM app_secrets WHERE id = NEW.secret_id;
710
+ RETURN NEW;
711
+ END $$ LANGUAGE plpgsql`,
712
+ async () => {
713
+ await as(admin, () => vault.deleteSecret(raced.id));
714
+ },
715
+ );
394
716
 
395
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
717
+ // Only the row that was looked up is gone; the replacement keeps the name.
718
+ expect(await rows("SELECT id, key FROM app_secrets")).toEqual([
719
+ { id: "replacement-id", key: "RACED_KEY" },
720
+ ]);
721
+ expect(
722
+ await rows(
723
+ "SELECT secret_id FROM vault_audit_log WHERE action = 'secret.deleted'",
724
+ ),
725
+ ).toEqual([{ secret_id: raced.id }]);
396
726
  });
397
727
 
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",
728
+ it("fails, and records no delete, when another admin deleted the key mid-delete", async () => {
729
+ const { as, exec, rows, vault } = await load();
730
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "manual" }));
731
+ const raced = await as(admin, () =>
732
+ vault.createSecret({
733
+ credentialKey: "RACED_KEY",
734
+ value: PLAINTEXT,
735
+ name: "Raced",
409
736
  }),
410
- ).rejects.toThrow("row update failed");
737
+ );
738
+ await as(admin, () => vault.createGrant(raced.id, "mail"));
739
+
740
+ await whileRevokeRaces(
741
+ exec,
742
+ `CREATE FUNCTION race_on_revoke() RETURNS trigger AS $$
743
+ BEGIN
744
+ DELETE FROM app_secrets WHERE id = NEW.secret_id;
745
+ RETURN NEW;
746
+ END $$ LANGUAGE plpgsql`,
747
+ async () => {
748
+ await expect(
749
+ as(admin, () => vault.deleteSecret(raced.id)),
750
+ ).rejects.toThrow("Secret not found");
751
+ },
752
+ );
411
753
 
412
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
754
+ expect(
755
+ await rows(
756
+ "SELECT action FROM vault_audit_log WHERE action = 'secret.deleted'",
757
+ ),
758
+ ).toEqual([]);
413
759
  });
760
+ });
414
761
 
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",
762
+ describe("what the vault lists", () => {
763
+ it("lists every key in the organization scope and nothing from any other scope", async () => {
764
+ const { as, secrets, vault, orgRef } = await load();
765
+ const created = await as(admin, () =>
766
+ vault.createSecret({
767
+ credentialKey: "VAULT_CREATED_KEY",
768
+ value: PLAINTEXT,
769
+ name: "Vault created",
425
770
  }),
426
- ).rejects.toThrow("store unavailable");
771
+ );
772
+ await secrets.writeAppSecret({
773
+ ...orgRef("APP_OWNED_KEY"),
774
+ value: "fake-app-owned-value",
775
+ });
776
+ await secrets.writeAppSecret({
777
+ ...orgRef("LEGACY_VAULT_KEY"),
778
+ value: "fake-legacy-value",
779
+ description: "Synced from Dispatch vault: Legacy label",
780
+ });
781
+ await secrets.writeAppSecret({
782
+ key: "PERSONAL_KEY",
783
+ scope: "user",
784
+ scopeId: admin,
785
+ value: "fake-personal-value",
786
+ });
787
+ await secrets.writeAppSecret({
788
+ key: "SOLO_KEY",
789
+ scope: "workspace",
790
+ scopeId: `solo:${admin}`,
791
+ value: "fake-solo-value",
792
+ });
793
+ await secrets.writeAppSecret({
794
+ key: "OTHER_ORG_KEY",
795
+ scope: "org",
796
+ scopeId: otherOrgId,
797
+ value: "fake-other-org-value",
798
+ });
799
+
800
+ const listed = await as(admin, () => vault.listSecrets());
427
801
 
428
- expect(writes.inserted).toHaveLength(1);
429
- expect(JSON.stringify(writes)).not.toContain("sk-test-key");
802
+ expect(listed.map((row) => row.credentialKey).sort()).toEqual([
803
+ "APP_OWNED_KEY",
804
+ "LEGACY_VAULT_KEY",
805
+ "VAULT_CREATED_KEY",
806
+ ]);
807
+ expect(listed.find((row) => row.id === created.id)).toMatchObject({
808
+ name: "Vault created",
809
+ createdBy: admin,
810
+ });
811
+ // No label yet: the key stands in for it. A release's description marker
812
+ // is not the user's text, and an app's key has no creator.
813
+ expect(
814
+ listed.find((row) => row.credentialKey === "LEGACY_VAULT_KEY"),
815
+ ).toMatchObject({
816
+ name: "LEGACY_VAULT_KEY",
817
+ description: null,
818
+ valueStatus: "stored",
819
+ });
820
+ expect(
821
+ listed.find((row) => row.credentialKey === "APP_OWNED_KEY"),
822
+ ).toMatchObject({ name: "APP_OWNED_KEY", createdBy: null });
823
+ expect(JSON.stringify(listed)).not.toContain("fake-");
430
824
  });
431
825
 
432
- it("rejects an empty value instead of saving a secret with nothing behind it", async () => {
433
- actAsOrgAdmin();
434
- const writes = fakeVaultDb([]);
826
+ it("lists only the caller's own solo scope when no organization is active", async () => {
827
+ const { as, secrets, vault, orgRef } = await load();
828
+ await secrets.writeAppSecret({
829
+ ...orgRef("ORG_KEY"),
830
+ value: "fake-org-value",
831
+ });
832
+ await secrets.writeAppSecret({
833
+ key: "MY_SOLO_KEY",
834
+ scope: "workspace",
835
+ scopeId: `solo:${admin}`,
836
+ value: "fake-solo-value",
837
+ });
838
+ await secrets.writeAppSecret({
839
+ key: "THEIR_SOLO_KEY",
840
+ scope: "workspace",
841
+ scopeId: `solo:${member}`,
842
+ value: "fake-their-value",
843
+ });
435
844
 
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");
845
+ const listed = await as(admin, () => vault.listSecrets(), null);
443
846
 
444
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
445
- expect(writes.inserted).toEqual([]);
847
+ expect(listed.map((row) => row.credentialKey)).toEqual(["MY_SOLO_KEY"]);
446
848
  });
447
849
 
448
- it("overwrites an existing key's copy and keeps the row's value empty", async () => {
449
- actAsOrgAdmin();
450
- const writes = fakeVaultDb([existingRow()]);
850
+ it("reports a value this deployment cannot decrypt as unreadable, never as empty or missing", async () => {
851
+ const { as, rows, vault } = await load();
852
+ const created = await as(admin, () =>
853
+ vault.createSecret({
854
+ credentialKey: "FAKE_API_KEY",
855
+ value: PLAINTEXT,
856
+ name: "Fake API key",
857
+ }),
858
+ );
859
+ await rows(
860
+ "UPDATE app_secrets SET encrypted_value = 'not-a-ciphertext', shared_encrypted_value = NULL WHERE id = ?",
861
+ [created.id],
862
+ );
451
863
 
452
- await createSecret({
453
- credentialKey: "OPENAI_API_KEY",
454
- value: "sk-rotated",
455
- name: "OpenAI API Key",
456
- });
864
+ const [listed] = await as(admin, () => vault.listSecrets());
865
+ const single = await as(admin, () => vault.getSecret(created.id));
457
866
 
458
- expect(mocks.writeAppSecret).toHaveBeenCalledWith(
459
- expect.objectContaining({
460
- ...orgStore("OPENAI_API_KEY"),
461
- value: "sk-rotated",
867
+ expect(listed).toMatchObject({ last4: "", valueStatus: "unreadable" });
868
+ expect(single).toMatchObject({ last4: "", valueStatus: "unreadable" });
869
+ });
870
+
871
+ it("offers an admin everything in the scope and a member only keys the Vault manages", async () => {
872
+ const { as, secrets, vault, orgRef } = await load();
873
+ await as(admin, () =>
874
+ vault.createSecret({
875
+ credentialKey: "VAULT_CREATED_KEY",
876
+ value: PLAINTEXT,
877
+ name: "Vault created",
462
878
  }),
463
879
  );
464
- expect(writes.updated[0]).toMatchObject({ value: "" });
880
+ await secrets.writeAppSecret({
881
+ ...orgRef("LEGACY_VAULT_KEY"),
882
+ value: "fake-legacy-value",
883
+ description: "Synced from Dispatch vault: Legacy label",
884
+ });
885
+ await secrets.writeAppSecret({
886
+ ...orgRef("APP_OWNED_KEY"),
887
+ value: "fake-app-owned-value",
888
+ });
889
+
890
+ const keys = async (email: string) =>
891
+ (await as(email, () => vault.listSecretOptions()))
892
+ .map((option) => option.credentialKey)
893
+ .sort();
894
+
895
+ expect(await keys(admin)).toEqual([
896
+ "APP_OWNED_KEY",
897
+ "LEGACY_VAULT_KEY",
898
+ "VAULT_CREATED_KEY",
899
+ ]);
900
+ expect(await keys(member)).toEqual([
901
+ "LEGACY_VAULT_KEY",
902
+ "VAULT_CREATED_KEY",
903
+ ]);
904
+ expect(
905
+ Object.keys(
906
+ (await as(member, () => vault.listSecretOptions()))[0],
907
+ ).sort(),
908
+ ).toEqual(["credentialKey", "description", "id", "name", "provider"]);
465
909
  });
910
+ });
466
911
 
467
- it("lets metadata-only edits through without touching the value", async () => {
468
- actAsOrgAdmin();
469
- const writes = fakeVaultDb([existingRow()]);
912
+ describe("grants", () => {
913
+ async function seededManual() {
914
+ const loaded = await load();
915
+ await loaded.as(admin, () =>
916
+ loaded.vault.setVaultAccessSettings({ mode: "manual" }),
917
+ );
918
+ const created = await loaded.as(admin, () =>
919
+ loaded.vault.createSecret({
920
+ credentialKey: "FAKE_API_KEY",
921
+ value: PLAINTEXT,
922
+ name: "Fake API key",
923
+ }),
924
+ );
925
+ return { ...loaded, created };
926
+ }
470
927
 
471
- await updateSecret("secret-1", { name: "Renamed", description: "note" });
928
+ it("records the grant against the key, with the app_secrets id beside it", async () => {
929
+ const { as, rows, vault, created } = await seededManual();
472
930
 
473
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
474
- expect(writes.updated[0]).toMatchObject({
475
- name: "Renamed",
476
- description: "note",
931
+ const grant = await as(admin, () => vault.createGrant(created.id, "mail"));
932
+
933
+ expect(grant).toMatchObject({
934
+ secretId: created.id,
935
+ credentialKey: "FAKE_API_KEY",
936
+ appId: "mail",
937
+ status: "active",
938
+ orgId,
477
939
  });
478
- expect(writes.updated[0]).not.toHaveProperty("value");
940
+ // The row core's manual-mode check reads.
941
+ expect(
942
+ await rows(
943
+ `SELECT 1 FROM vault_grants WHERE org_id = ? AND app_id = ? AND status = 'active' AND credential_key = ? LIMIT 1`,
944
+ [orgId, "mail", "FAKE_API_KEY"],
945
+ ),
946
+ ).toHaveLength(1);
947
+ expect(
948
+ await rows(
949
+ `SELECT 1 FROM vault_grants WHERE org_id = ? AND app_id = ? AND status = 'active' AND credential_key = ? LIMIT 1`,
950
+ [orgId, "calendar", "FAKE_API_KEY"],
951
+ ),
952
+ ).toHaveLength(0);
479
953
  });
480
954
 
481
- it("stores a new value from an edit", async () => {
482
- actAsOrgAdmin();
483
- const writes = fakeVaultDb([existingRow()]);
955
+ it("does not duplicate a grant, and reinstates a revoked one in place", async () => {
956
+ const { as, rows, vault, created } = await seededManual();
957
+
958
+ const first = await as(admin, () => vault.createGrant(created.id, "mail"));
959
+ const retry = await as(admin, () => vault.createGrant(created.id, "mail"));
960
+ expect(retry?.id).toBe(first?.id);
484
961
 
485
- await updateSecret("secret-1", { value: "sk-rotated" });
962
+ const revoked = await as(admin, () => vault.revokeGrant(first!.id));
963
+ expect(revoked?.status).toBe("revoked");
964
+ expect(
965
+ await rows(
966
+ "SELECT 1 FROM vault_grants WHERE status = 'active' AND credential_key = ?",
967
+ ["FAKE_API_KEY"],
968
+ ),
969
+ ).toHaveLength(0);
970
+
971
+ const again = await as(admin, () => vault.createGrant(created.id, "mail"));
972
+ expect(again).toMatchObject({ id: first!.id, status: "active" });
973
+ expect(await rows("SELECT id FROM vault_grants")).toHaveLength(1);
974
+ });
486
975
 
487
- expect(mocks.writeAppSecret).toHaveBeenCalledWith(
488
- expect.objectContaining({
489
- ...orgStore("OPENAI_API_KEY"),
490
- value: "sk-rotated",
976
+ it("lists a key's grants by the key's id, and by app", async () => {
977
+ const { as, vault, created } = await seededManual();
978
+ const other = await as(admin, () =>
979
+ vault.createSecret({
980
+ credentialKey: "OTHER_KEY",
981
+ value: "fake-other-value",
982
+ name: "Other",
491
983
  }),
492
984
  );
493
- expect(writes.updated[0]).toMatchObject({ value: "" });
985
+ await as(admin, () => vault.createGrant(created.id, "mail"));
986
+ await as(admin, () => vault.createGrant(created.id, "calendar"));
987
+ await as(admin, () => vault.createGrant(other.id, "mail"));
988
+
989
+ const forKey = await as(admin, () =>
990
+ vault.listGrants({ secretId: created.id }),
991
+ );
992
+ const forApp = await as(admin, () => vault.listGrants({ appId: "mail" }));
993
+
994
+ expect(forKey.map((grant) => grant.appId).sort()).toEqual([
995
+ "calendar",
996
+ "mail",
997
+ ]);
998
+ expect(forApp.map((grant) => grant.credentialKey).sort()).toEqual([
999
+ "FAKE_API_KEY",
1000
+ "OTHER_KEY",
1001
+ ]);
494
1002
  });
495
1003
 
496
- it("rejects an explicit empty value on edit", async () => {
497
- actAsOrgAdmin();
498
- fakeVaultDb([existingRow()]);
1004
+ it("grants several keys to an app and skips the ones it already has", async () => {
1005
+ const { as, vault, created } = await seededManual();
1006
+ const other = await as(admin, () =>
1007
+ vault.createSecret({
1008
+ credentialKey: "OTHER_KEY",
1009
+ value: "fake-other-value",
1010
+ name: "Other",
1011
+ }),
1012
+ );
1013
+ await as(admin, () => vault.createGrant(created.id, "mail"));
499
1014
 
500
- await expect(updateSecret("secret-1", { value: "" })).rejects.toThrow(
501
- "Secret value is required",
1015
+ const result = await as(admin, () =>
1016
+ vault.grantSecretsToApp([created.id, other.id, created.id], "mail"),
502
1017
  );
503
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
1018
+
1019
+ expect(result.accessMode).toBe("manual");
1020
+ expect(result.skipped).toEqual([created.id]);
1021
+ expect(result.created.map((grant) => grant.credentialKey)).toEqual([
1022
+ "OTHER_KEY",
1023
+ ]);
504
1024
  });
505
1025
 
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" })]);
1026
+ it("writes no grants in all-apps mode", async () => {
1027
+ const { as, rows, vault } = await load();
1028
+ const created = await as(admin, () =>
1029
+ vault.createSecret({
1030
+ credentialKey: "FAKE_API_KEY",
1031
+ value: PLAINTEXT,
1032
+ name: "Fake API key",
1033
+ }),
1034
+ );
509
1035
 
510
- await updateSecret("secret-1", { name: "Renamed" });
1036
+ const result = await as(admin, () =>
1037
+ vault.grantSecretsToApp([created.id], "mail"),
1038
+ );
511
1039
 
512
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
513
- expect(writes.updated[0]).toMatchObject({ name: "Renamed" });
514
- expect(writes.updated[0]).not.toHaveProperty("value");
1040
+ expect(result).toMatchObject({
1041
+ accessMode: "all-apps",
1042
+ created: [],
1043
+ skipped: [created.id],
1044
+ });
1045
+ expect(await rows("SELECT id FROM vault_grants")).toEqual([]);
515
1046
  });
516
1047
 
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
- });
1048
+ it("moves a key's grants with it when the key is renamed", async () => {
1049
+ const { as, rows, vault, created } = await seededManual();
1050
+ await as(admin, () => vault.createGrant(created.id, "mail"));
524
1051
 
525
- await updateSecret("secret-1", { credentialKey: "OPENAI_KEY_V2" });
1052
+ await as(admin, () =>
1053
+ vault.updateSecret(created.id, { credentialKey: "FAKE_API_KEY_V2" }),
1054
+ );
526
1055
 
527
- expect(mocks.readAppSecret).toHaveBeenCalledWith(
528
- orgStore("OPENAI_API_KEY"),
1056
+ expect(
1057
+ await rows("SELECT credential_key, secret_id, status FROM vault_grants"),
1058
+ ).toEqual([
1059
+ {
1060
+ credential_key: "FAKE_API_KEY_V2",
1061
+ secret_id: created.id,
1062
+ status: "active",
1063
+ },
1064
+ ]);
1065
+ });
1066
+
1067
+ it("does not move another scope's grant of the same key name on a rename", async () => {
1068
+ const { as, rows, vault, created } = await seededManual();
1069
+ await as(admin, () => vault.createGrant(created.id, "mail"));
1070
+ await rows(
1071
+ `INSERT INTO vault_grants (id, owner_email, org_id, secret_id, credential_key, app_id, granted_by, status, created_at, updated_at)
1072
+ VALUES ('foreign-grant', ?, ?, 'foreign-secret', 'FAKE_API_KEY', 'mail', ?, 'active', 1, 2)`,
1073
+ [admin, otherOrgId, admin],
529
1074
  );
530
- expect(mocks.writeAppSecret).toHaveBeenCalledWith(
531
- expect.objectContaining({
532
- ...orgStore("OPENAI_KEY_V2"),
533
- value: "sk-stored",
534
- }),
1075
+
1076
+ await as(admin, () =>
1077
+ vault.updateSecret(created.id, { credentialKey: "FAKE_API_KEY_V2" }),
1078
+ );
1079
+
1080
+ expect(
1081
+ await rows(
1082
+ "SELECT credential_key FROM vault_grants WHERE id = 'foreign-grant'",
1083
+ ),
1084
+ ).toEqual([{ credential_key: "FAKE_API_KEY" }]);
1085
+ });
1086
+
1087
+ it("counts and shows a grant from before grants named their key only once it is backfilled", async () => {
1088
+ const { as, rows, vault, created } = await seededManual();
1089
+ await rows(
1090
+ `INSERT INTO vault_grants (id, owner_email, org_id, secret_id, app_id, granted_by, status, created_at, updated_at)
1091
+ VALUES ('legacy-grant', ?, ?, 'old-vault-secret-id', 'mail', ?, 'active', 1, 2)`,
1092
+ [admin, orgId, admin],
535
1093
  );
536
- expect(writes.updated[0]).toMatchObject({
537
- credentialKey: "OPENAI_KEY_V2",
1094
+
1095
+ // Core's manual-mode check needs the key, so this row grants nothing.
1096
+ expect(await as(admin, () => vault.listVaultOverview())).toMatchObject({
1097
+ manualGrantCount: 0,
1098
+ activeGrantCount: 0,
538
1099
  });
539
- expect(writes.updated[0]).not.toHaveProperty("value");
1100
+ expect(
1101
+ await as(admin, () => vault.listGrants({ secretId: created.id })),
1102
+ ).toEqual([]);
1103
+
1104
+ // The same key granted again gets its own row; the inert one stays inert.
1105
+ const fresh = await as(admin, () => vault.createGrant(created.id, "mail"));
1106
+ expect(await rows("SELECT id FROM vault_grants")).toHaveLength(2);
1107
+
1108
+ await rows(
1109
+ "UPDATE vault_grants SET credential_key = 'FAKE_API_KEY' WHERE id = 'legacy-grant'",
1110
+ );
1111
+ const shown = await as(admin, () =>
1112
+ vault.listGrants({ secretId: created.id }),
1113
+ );
1114
+ expect(shown.map((grant) => grant.id).sort()).toEqual(
1115
+ [fresh!.id, "legacy-grant"].sort(),
1116
+ );
1117
+ // Reported against the key's current id, so the Vault page can match it.
1118
+ expect(shown.map((grant) => grant.secretId)).toEqual([
1119
+ created.id,
1120
+ created.id,
1121
+ ]);
540
1122
  });
541
1123
 
542
- it("renames a row with no stored copy without inventing a value", async () => {
543
- actAsOrgAdmin();
544
- fakeVaultDb([existingRow()]);
545
- mocks.readAppSecret.mockResolvedValue(null);
1124
+ it("revokes the grants of a key that is deleted, including a backfilled one", async () => {
1125
+ const { as, rows, vault, created } = await seededManual();
1126
+ await as(admin, () => vault.createGrant(created.id, "mail"));
1127
+ await rows(
1128
+ `INSERT INTO vault_grants (id, owner_email, org_id, secret_id, credential_key, app_id, granted_by, status, created_at, updated_at)
1129
+ VALUES ('backfilled-grant', ?, ?, 'old-vault-secret-id', 'FAKE_API_KEY', 'calendar', ?, 'active', 1, 2)`,
1130
+ [admin, orgId, admin],
1131
+ );
546
1132
 
547
- await updateSecret("secret-1", { credentialKey: "OPENAI_KEY_V2" });
1133
+ await as(admin, () => vault.deleteSecret(created.id));
548
1134
 
549
- expect(mocks.writeAppSecret).not.toHaveBeenCalled();
1135
+ expect(
1136
+ await rows("SELECT status FROM vault_grants WHERE status = 'active'"),
1137
+ ).toEqual([]);
550
1138
  });
551
1139
 
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"));
1140
+ it("counts effective grants in manual mode and every key in all-apps mode", async () => {
1141
+ const { as, vault, created } = await seededManual();
1142
+ await as(admin, () => vault.createGrant(created.id, "mail"));
1143
+ await as(admin, () => vault.createGrant(created.id, "calendar"));
1144
+
1145
+ expect(await as(admin, () => vault.listVaultOverview())).toMatchObject({
1146
+ accessMode: "manual",
1147
+ secretCount: 1,
1148
+ manualGrantCount: 2,
1149
+ activeGrantCount: 2,
1150
+ pendingRequestCount: 0,
1151
+ });
556
1152
 
557
- await expect(
558
- updateSecret("secret-1", { credentialKey: "OPENAI_KEY_V2" }),
559
- ).rejects.toThrow("cannot decrypt");
1153
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "all-apps" }));
1154
+ expect(await as(admin, () => vault.listVaultOverview())).toMatchObject({
1155
+ accessMode: "all-apps",
1156
+ secretCount: 1,
1157
+ activeGrantCount: 1,
1158
+ manualGrantCount: 2,
1159
+ });
1160
+ });
1161
+
1162
+ it("shows an app which keys it can use, by grant in manual mode and by default otherwise", async () => {
1163
+ mocks.discoverAgents.mockResolvedValue([
1164
+ {
1165
+ id: "mail",
1166
+ name: "Mail",
1167
+ url: "https://mail.example.test",
1168
+ color: "#000000",
1169
+ },
1170
+ ]);
1171
+ mocks.ssrfSafeFetch.mockResolvedValue({
1172
+ ok: true,
1173
+ json: async () => [
1174
+ {
1175
+ key: "FAKE_API_KEY",
1176
+ label: "Fake",
1177
+ required: true,
1178
+ configured: false,
1179
+ },
1180
+ {
1181
+ key: "OTHER_KEY",
1182
+ label: "Other",
1183
+ required: false,
1184
+ configured: false,
1185
+ },
1186
+ ],
1187
+ });
1188
+ const { as, vault, created } = await seededManual();
1189
+ await as(admin, () =>
1190
+ vault.createSecret({
1191
+ credentialKey: "OTHER_KEY",
1192
+ value: "fake-other-value",
1193
+ name: "Other",
1194
+ }),
1195
+ );
1196
+ await as(admin, () => vault.createGrant(created.id, "mail"));
1197
+
1198
+ const manual = await as(admin, () => vault.listIntegrationsCatalog());
1199
+ expect(
1200
+ manual[0].integrations.map((entry) => [entry.key, entry.vaultGranted]),
1201
+ ).toEqual([
1202
+ ["FAKE_API_KEY", true],
1203
+ ["OTHER_KEY", false],
1204
+ ]);
1205
+ expect(manual[0].integrations[0].vaultSecretId).toBe(created.id);
560
1206
 
561
- expect(writes.updated).toEqual([]);
1207
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "all-apps" }));
1208
+ const open = await as(admin, () => vault.listIntegrationsCatalog());
1209
+ expect(open[0].integrations.map((entry) => entry.vaultGranted)).toEqual([
1210
+ true,
1211
+ true,
1212
+ ]);
562
1213
  });
563
1214
  });
564
1215
 
565
- describe("cleanupSyncedCredentialKeysIfUnused", () => {
566
- function mockVaultSecretLookup(rows: Array<{ id: string }> = []) {
567
- const query = {
568
- select: vi.fn(() => query),
569
- from: vi.fn(() => query),
570
- where: vi.fn(() => query),
571
- limit: vi.fn(async () => rows),
572
- };
573
- mocks.getDb.mockReturnValue(query);
574
- return query;
575
- }
576
-
577
- it("deletes a candidate synced credential when no vault secret still uses it", async () => {
578
- mockVaultSecretLookup([]);
1216
+ describe("key requests", () => {
1217
+ it("approving one stores the key in the vault scope, grants it, and keeps the value out of every other table", async () => {
1218
+ const { as, rows, secrets, vault, orgRef, everythingStored } = await load();
1219
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "manual" }));
1220
+ const request = await as(member, () =>
1221
+ vault.createRequest({
1222
+ credentialKey: "REQUESTED_KEY",
1223
+ appId: "mail",
1224
+ reason: "needed for tests",
1225
+ }),
1226
+ );
579
1227
 
580
- await cleanupSyncedCredentialKeysIfUnused(
581
- { ownerEmail: "admin@example.test", orgId: "org_123" },
582
- ["OLD_API_KEY"],
1228
+ const approved = await as(admin, () =>
1229
+ vault.approveRequest(request!.id, PLAINTEXT, "Requested key"),
583
1230
  );
584
1231
 
585
- expect(mocks.deleteAppSecret).toHaveBeenCalledWith({
586
- key: "OLD_API_KEY",
1232
+ expect(approved).toMatchObject({ status: "approved", reviewedBy: admin });
1233
+ expect((await secrets.readAppSecret(orgRef("REQUESTED_KEY")))?.value).toBe(
1234
+ PLAINTEXT,
1235
+ );
1236
+ const [stored] = await rows(
1237
+ "SELECT scope, scope_id, label, created_by FROM app_secrets WHERE key = 'REQUESTED_KEY'",
1238
+ );
1239
+ expect(stored).toMatchObject({
587
1240
  scope: "org",
588
- scopeId: "org_123",
1241
+ scope_id: orgId,
1242
+ label: "Requested key",
589
1243
  });
1244
+ expect(stored.created_by).toBeTruthy();
1245
+ expect(
1246
+ await rows(
1247
+ "SELECT credential_key, app_id, status FROM vault_grants WHERE org_id = ?",
1248
+ [orgId],
1249
+ ),
1250
+ ).toEqual([
1251
+ { credential_key: "REQUESTED_KEY", app_id: "mail", status: "active" },
1252
+ ]);
1253
+ expect(await everythingStored()).not.toContain(PLAINTEXT);
590
1254
  });
591
1255
 
592
- it("uses the secret row scope for personal vault cleanup", async () => {
593
- mockVaultSecretLookup([]);
1256
+ it("grants a key that already exists in the scope without overwriting it", async () => {
1257
+ const { as, rows, secrets, vault, orgRef } = await load();
1258
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "manual" }));
1259
+ await secrets.writeAppSecret({
1260
+ ...orgRef("APP_OWNED_KEY"),
1261
+ value: "fake-app-owned-value",
1262
+ });
1263
+ const request = await as(member, () =>
1264
+ vault.createRequest({ credentialKey: "APP_OWNED_KEY", appId: "mail" }),
1265
+ );
594
1266
 
595
- await cleanupSyncedCredentialKeysIfUnused(
596
- { ownerEmail: "owner@example.test", orgId: null },
597
- ["PERSONAL_API_KEY"],
1267
+ await as(admin, () =>
1268
+ vault.approveRequest(request!.id, "fake-approver-value"),
598
1269
  );
599
1270
 
600
- expect(mocks.deleteAppSecret).toHaveBeenCalledWith({
601
- key: "PERSONAL_API_KEY",
602
- scope: "workspace",
603
- scopeId: "solo:owner@example.test",
604
- });
1271
+ expect((await secrets.readAppSecret(orgRef("APP_OWNED_KEY")))?.value).toBe(
1272
+ "fake-app-owned-value",
1273
+ );
1274
+ expect(
1275
+ await rows(
1276
+ "SELECT label, created_by FROM app_secrets WHERE key = 'APP_OWNED_KEY'",
1277
+ ),
1278
+ ).toEqual([{ label: null, created_by: null }]);
1279
+ expect(
1280
+ await rows("SELECT credential_key, status FROM vault_grants"),
1281
+ ).toEqual([{ credential_key: "APP_OWNED_KEY", status: "active" }]);
605
1282
  });
606
1283
 
607
- it("keeps a candidate synced credential when another vault secret still uses it", async () => {
608
- mockVaultSecretLookup([{ id: "secret_1" }]);
1284
+ it("denying one stores nothing and grants nothing", async () => {
1285
+ const { as, rows, vault } = await load();
1286
+ const request = await as(member, () =>
1287
+ vault.createRequest({ credentialKey: "REQUESTED_KEY", appId: "mail" }),
1288
+ );
609
1289
 
610
- await cleanupSyncedCredentialKeysIfUnused(
611
- { ownerEmail: "admin@example.test", orgId: "org_123" },
612
- ["SHARED_API_KEY"],
1290
+ const denied = await as(admin, () =>
1291
+ vault.denyRequest(request!.id, "not needed"),
613
1292
  );
614
1293
 
615
- expect(mocks.deleteAppSecret).not.toHaveBeenCalled();
1294
+ expect(denied).toMatchObject({ status: "denied", reviewedBy: admin });
1295
+ expect(await rows("SELECT * FROM app_secrets")).toEqual([]);
1296
+ expect(await rows("SELECT * FROM vault_grants")).toEqual([]);
616
1297
  });
617
1298
 
618
- it("can scan synced app secrets to recover stale keys after a retry", async () => {
619
- mockVaultSecretLookup([]);
620
- mocks.listAppSecretsForScope.mockResolvedValue([
621
- {
622
- key: "STALE_KEY",
623
- description: "Synced from Dispatch vault: Old key",
624
- },
625
- {
626
- key: "HAND_WRITTEN_KEY",
627
- description: "Created manually",
628
- },
629
- ]);
1299
+ it("lets admins see every request and members only their own", async () => {
1300
+ const { as, vault } = await load();
1301
+ await as(member, () =>
1302
+ vault.createRequest({ credentialKey: "MEMBER_KEY", appId: "mail" }),
1303
+ );
1304
+ await as(admin, () =>
1305
+ vault.createRequest({ credentialKey: "ADMIN_KEY", appId: "mail" }),
1306
+ );
630
1307
 
631
- await cleanupSyncedCredentialKeysIfUnused({
632
- ownerEmail: "admin@example.test",
633
- orgId: "org_123",
634
- });
1308
+ const keys = async (email: string) =>
1309
+ (await as(email, () => vault.listRequests()))
1310
+ .map((request) => request.credentialKey)
1311
+ .sort();
635
1312
 
636
- expect(mocks.listAppSecretsForScope).toHaveBeenCalledWith("org", "org_123");
637
- expect(mocks.deleteAppSecret).toHaveBeenCalledTimes(1);
638
- expect(mocks.deleteAppSecret).toHaveBeenCalledWith({
639
- key: "STALE_KEY",
640
- scope: "org",
641
- scopeId: "org_123",
642
- });
1313
+ expect(await keys(admin)).toEqual(["ADMIN_KEY", "MEMBER_KEY"]);
1314
+ expect(await keys(member)).toEqual(["MEMBER_KEY"]);
1315
+ });
1316
+ });
1317
+
1318
+ describe("the audit log", () => {
1319
+ it("names the key in every entry, and still does after the key is gone", async () => {
1320
+ const { as, vault } = await load();
1321
+ await as(admin, () => vault.setVaultAccessSettings({ mode: "manual" }));
1322
+ const created = await as(admin, () =>
1323
+ vault.createSecret({
1324
+ credentialKey: "FAKE_API_KEY",
1325
+ value: PLAINTEXT,
1326
+ name: "Fake API key",
1327
+ }),
1328
+ );
1329
+ const grant = await as(admin, () => vault.createGrant(created.id, "mail"));
1330
+ await as(admin, () =>
1331
+ vault.updateSecret(created.id, { credentialKey: "FAKE_API_KEY_V2" }),
1332
+ );
1333
+ await as(admin, () => vault.revokeGrant(grant!.id));
1334
+ await as(admin, () => vault.deleteSecret(created.id));
1335
+ const request = await as(member, () =>
1336
+ vault.createRequest({ credentialKey: "REQUESTED_KEY", appId: "mail" }),
1337
+ );
1338
+ await as(admin, () => vault.denyRequest(request!.id));
1339
+
1340
+ const audit = await as(admin, () => vault.listVaultAudit(50));
1341
+ const entry = (action: string) =>
1342
+ audit.find((row) => row.action === action);
1343
+ const keyOf = (action: string) =>
1344
+ JSON.parse(entry(action)?.metadata ?? "{}").credentialKey;
1345
+
1346
+ expect(entry("secret.created")).toMatchObject({ secretId: created.id });
1347
+ expect(keyOf("secret.created")).toBe("FAKE_API_KEY");
1348
+ expect(keyOf("secret.updated")).toBe("FAKE_API_KEY_V2");
1349
+ expect(keyOf("grant.created")).toBe("FAKE_API_KEY");
1350
+ expect(keyOf("grant.revoked")).toBe("FAKE_API_KEY_V2");
1351
+ expect(entry("secret.deleted")).toMatchObject({ secretId: created.id });
1352
+ expect(keyOf("secret.deleted")).toBe("FAKE_API_KEY_V2");
1353
+ expect(keyOf("request.created")).toBe("REQUESTED_KEY");
1354
+ expect(keyOf("request.denied")).toBe("REQUESTED_KEY");
1355
+ expect(JSON.stringify(audit)).not.toContain(PLAINTEXT);
643
1356
  });
644
1357
  });