-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathagent-vault.spec.ts
More file actions
834 lines (705 loc) · 39.2 KB
/
Copy pathagent-vault.spec.ts
File metadata and controls
834 lines (705 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
import crypto from "node:crypto";
import { AccessScope, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
import { agentVaultAccessBundleDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal";
import { agentVaultAccessBundleMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-access-bundle-member-dal";
import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";
import { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";
import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";
import { agentVaultSessionAccessBundleDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal";
import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";
import { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { UnauthorizedError } from "@app/lib/errors";
import { orgDALFactory } from "@app/services/org/org-dal";
import { initLogger } from "@app/lib/logger";
declare const testKeyStore: TKeyStoreFactory;
// The test file has its own module graph, so the logger the environment initialised is not this one.
initLogger();
const authHeader = { authorization: `Bearer ${jwtAuthToken}` };
const inject = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
testServer.inject({ method, url, headers: authHeader, ...(body ? { body } : {}) });
// identityService.create writes the org membership alongside the identity row, and an identity without
// one cannot authenticate at all, so a fixture that inserts only the identity is not a shape production
// can produce - and the membership endpoint now checks for it.
const createOrgIdentity = async (name: string) => {
const [identity] = (await testDb("identities")
.insert({ name, orgId: seedData1.organization.id })
.returning("*")) as { id: string }[];
await testDb("memberships").insert({
scope: AccessScope.Organization,
scopeOrgId: seedData1.organization.id,
actorIdentityId: identity.id
});
return identity;
};
const deleteOrgIdentity = async (identityId: string) => {
await testDb("memberships").where({ actorIdentityId: identityId }).del();
await testDb("identities").where({ id: identityId }).delete();
};
const createAccessBundle = async (name: string) => {
const res = await inject("POST", "/api/v1/agent-vault/access-bundles", { name });
expect(res.statusCode).toBe(200);
return (JSON.parse(res.payload) as { accessBundle: { id: string; name: string } }).accessBundle;
};
describe("Agent Vault V1 Router", async () => {
test("resolving the project bootstraps it and seeds org admins", async () => {
const res = await inject("GET", "/api/v1/agent-vault/project");
expect(res.statusCode).toBe(200);
const { projectId } = JSON.parse(res.payload) as { projectId: string };
expect(projectId).toBeTruthy();
const project = await testDb("projects").where({ id: projectId }).first();
expect(project.type).toBe(ProjectType.AgentVault);
expect(project.orgId).toBe(seedData1.organization.id);
// The bootstrap seeds the org's admins as project admins; without that nobody could reach the product.
const membership = await testDb("memberships")
.where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: seedData1.id })
.first();
expect(membership).toBeTruthy();
const role = await testDb("membership_roles").where({ membershipId: membership.id }).first();
expect(role.role).toBe(ProjectMembershipRole.Admin);
// A second call resolves the same project rather than creating another.
const again = await inject("GET", "/api/v1/agent-vault/project");
expect((JSON.parse(again.payload) as { projectId: string }).projectId).toBe(projectId);
});
test("the Agent Vault project cannot be created or deleted through the generic project routes", async () => {
const create = await testServer.inject({
method: "POST",
url: "/api/v1/projects",
headers: authHeader,
body: { projectName: "second agent vault", type: ProjectType.AgentVault }
});
expect(create.statusCode).toBe(400);
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const remove = await testServer.inject({
method: "DELETE",
url: `/api/v1/projects/${projectId}`,
headers: authHeader
});
expect(remove.statusCode).toBe(400);
});
test("an Agent Vault project does not count against the workspace limit", async () => {
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const billable = (await testDb("projects")
.whereNotIn("type", ["cert-manager", "pam", "agent-vault", "ssh", "ai"])
.whereNull("deleteAfter")
.where({ orgId: seedData1.organization.id })
.select("id")) as { id: string }[];
expect(billable.map((row) => row.id)).not.toContain(projectId);
});
describe("access bundles", async () => {
test("the creator is granted the access bundle they just made", async () => {
const bundle = await createAccessBundle("creator-grant");
const res = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
const { accessBundle } = JSON.parse(res.payload) as {
accessBundle: { members: { userId: string | null; identityId: string | null }[] };
};
expect(accessBundle.members).toHaveLength(1);
expect(accessBundle.members[0].userId).toBe(seedData1.id);
});
test("a connection is rejected when it shares a host with another in the same bundle", async () => {
const bundle = await createAccessBundle("overlap-check");
const first = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "datadog-us5",
hostPattern: "api.us5.datadoghq.com, api.datadoghq.eu",
credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }
});
expect(first.statusCode).toBe(200);
// An intersection, not set equality: the candidate names one host the first connection already
// covers, plus one it does not.
const overlapping = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "datadog-eu",
hostPattern: "api.datadoghq.eu, api.datadoghq.com",
credential: { type: "bearer", value: "def456" }
});
expect(overlapping.statusCode).toBe(400);
expect(JSON.parse(overlapping.payload).message).toContain("api.datadoghq.eu:443");
// Containment is allowed: an exact host beats a wildcard deterministically, which is an override.
const contained = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "datadog-wildcard",
hostPattern: "*.datadoghq.com",
credential: { type: "passthrough" }
});
expect(contained.statusCode).toBe(200);
});
test("a connection never echoes its secret, and its host pattern is kept as typed", async () => {
const bundle = await createAccessBundle("secret-handling");
const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "github",
hostPattern: " API.GitHub.com ",
credential: { type: "bearer", value: "ghp_secret_value" }
});
expect(res.statusCode).toBe(200);
const { connection } = JSON.parse(res.payload) as {
connection: { id: string; hostPattern: string; credential: Record<string, unknown> };
};
// Stored as typed, only trimmed. The canonical form is derived per comparison instead, so a
// pattern cannot grow past the column between the length check and the insert.
expect(connection.hostPattern).toBe("API.GitHub.com");
expect(connection.credential).toEqual({ type: "bearer", headerName: "Authorization", headerPrefix: "Bearer" });
expect(res.payload).not.toContain("ghp_secret_value");
const detail = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
expect(detail.payload).not.toContain("ghp_secret_value");
// The secret is sealed, not stored in the plaintext config column.
const row = await testDb("agent_vault_connections").where({ id: connection.id }).first();
expect(row.encryptedCredential).toBeTruthy();
expect(row.encryptedCredential.toString("utf-8")).not.toContain("ghp_secret_value");
expect(JSON.stringify(row.credentialConfig)).not.toContain("ghp_secret_value");
});
test("updating a connection patches the credential instead of replacing it", async () => {
const bundle = await createAccessBundle("credential-patch");
const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "datadog",
hostPattern: "api.datadoghq.com",
credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }
});
expect(created.statusCode).toBe(200);
const { connection } = JSON.parse(created.payload) as { connection: { id: string } };
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/connections/${connection.id}`;
const sealed = async () => (await testDb("agent_vault_connections").where({ id: connection.id }).first()).encryptedCredential;
// Rotating the secret must not disturb the header the credential rides on. Reusing the create
// schema here would reset DD-API-KEY to Authorization: Bearer and every request would 401.
const before = await sealed();
const rotated = await inject("PATCH", url, { credential: { type: "bearer", value: "rotated456" } });
expect(rotated.statusCode).toBe(200);
expect(JSON.parse(rotated.payload).connection.credential).toEqual({
type: "bearer",
headerName: "DD-API-KEY",
headerPrefix: ""
});
expect((await sealed()).equals(before)).toBe(false);
// And the mirror image: renaming the header leaves the sealed secret untouched.
const afterRotate = await sealed();
const renamed = await inject("PATCH", url, { credential: { type: "bearer", headerName: "X-Api-Key" } });
expect(renamed.statusCode).toBe(200);
expect(JSON.parse(renamed.payload).connection.credential.headerName).toBe("X-Api-Key");
expect((await sealed()).equals(afterRotate)).toBe(true);
});
test("a basic credential keeps one half while the other changes, and refuses to lose both", async () => {
const bundle = await createAccessBundle("basic-halves");
const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "stripe",
hostPattern: "api.stripe.com",
credential: { type: "basic", username: "sk_live_key", password: "" }
});
expect(created.statusCode).toBe(200);
const { connection } = JSON.parse(created.payload) as { connection: { id: string; credential: Record<string, unknown> } };
expect(connection.credential).toEqual({ type: "basic", username: "sk_live_key", hasPassword: false });
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/connections/${connection.id}`;
// The username-only credential has nothing else to authenticate with, so clearing it is refused.
const emptied = await inject("PATCH", url, { credential: { type: "basic", username: "" } });
expect(emptied.statusCode).toBe(400);
// Supplying a password first makes the same edit legal: the flip to password-only.
const flipped = await inject("PATCH", url, { credential: { type: "basic", username: "", password: "hunter2" } });
expect(flipped.statusCode).toBe(200);
expect(JSON.parse(flipped.payload).connection.credential).toEqual({ type: "basic", username: "", hasPassword: true });
// An empty string removes the password, where an omission would have kept it.
const named = await inject("PATCH", url, { credential: { type: "basic", username: "sk_live_key" } });
expect(JSON.parse(named.payload).connection.credential.hasPassword).toBe(true);
const cleared = await inject("PATCH", url, { credential: { type: "basic", password: "" } });
expect(cleared.statusCode).toBe(200);
expect(JSON.parse(cleared.payload).connection.credential.hasPassword).toBe(false);
});
test("changing the credential type requires whatever the new type needs", async () => {
const bundle = await createAccessBundle("type-change");
const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "github",
hostPattern: "api.github.com",
credential: { type: "bearer", value: "ghp_one" }
});
const { connection } = JSON.parse(created.payload) as { connection: { id: string } };
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/connections/${connection.id}`;
// The sealed secret belongs to the old type, so there is nothing to carry over.
const noSecret = await inject("PATCH", url, { credential: { type: "basic", username: "bot" } });
expect(noSecret.statusCode).toBe(200);
const bearerNoValue = await inject("PATCH", url, { credential: { type: "bearer" } });
expect(bearerNoValue.statusCode).toBe(400);
});
test("a path in a host pattern is rejected", async () => {
const bundle = await createAccessBundle("no-paths");
const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "with-path",
hostPattern: "gitlab.com/api/v4",
credential: { type: "passthrough" }
});
expect(res.statusCode).toBe(422);
});
});
describe("product membership", async () => {
const memberships = "/api/v1/agent-vault/memberships";
test("a machine identity can be given Agent Vault, have its role changed, and lose it again", async () => {
const identity = await createOrgIdentity(`av-membership-${Date.now()}`);
const added = await inject("POST", memberships, { identityId: identity.id, role: "member" });
expect(added.statusCode).toBe(200);
const listed = await inject("GET", `${memberships}/identity-members`);
const { members } = JSON.parse(listed.payload) as {
members: { identityId: string; role: string; name: string }[];
};
const row = members.find((m) => m.identityId === identity.id);
expect(row?.role).toBe("member");
// The name is joined on so the page never has to reach for the org identity list.
expect(row?.name).toBeTruthy();
const promoted = await inject("PATCH", memberships, { identityId: identity.id, role: "admin" });
expect(promoted.statusCode).toBe(200);
expect(JSON.parse(promoted.payload).role).toBe("admin");
const removed = await inject("DELETE", memberships, { identityId: identity.id });
expect(removed.statusCode).toBe(200);
const after = JSON.parse((await inject("GET", `${memberships}/identity-members`)).payload) as {
members: { identityId: string }[];
};
expect(after.members.some((m) => m.identityId === identity.id)).toBe(false);
await deleteOrgIdentity(identity.id);
});
test("removing a member takes their access bundle grants with them", async () => {
const bundle = await createAccessBundle("membership-reap");
const identity = await createOrgIdentity(`av-reap-${Date.now()}`);
expect((await inject("POST", memberships, { identityId: identity.id, role: "member" })).statusCode).toBe(200);
expect(
(await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, { identityId: identity.id }))
.statusCode
).toBe(200);
const granted = await testDb("agent_vault_access_bundle_members").where({ identityId: identity.id });
expect(granted).toHaveLength(1);
expect((await inject("DELETE", memberships, { identityId: identity.id })).statusCode).toBe(200);
// Bundle grants live outside the membership table, so nothing reaps them unless this path does.
const afterRemoval = await testDb("agent_vault_access_bundle_members").where({ identityId: identity.id });
expect(afterRemoval).toHaveLength(0);
await deleteOrgIdentity(identity.id);
});
test("the guards that keep the product administrable hold", async () => {
// Removing yourself would need another admin to undo, and the seed user is one.
const self = await inject("DELETE", memberships, { userId: seedData1.id });
expect(self.statusCode).toBe(403);
const unknown = await inject("POST", memberships, {
identityId: "00000000-0000-0000-0000-000000000000",
role: "member"
});
expect(unknown.statusCode).toBe(404);
const badRole = await inject("POST", memberships, { userId: seedData1.id, role: "viewer" });
expect(badRole.statusCode).toBe(422);
const noActor = await inject("POST", memberships, { role: "member" });
expect(noActor.statusCode).toBe(400);
});
});
describe("cross-org ids and foreign resources", async () => {
test("an access bundle in another organization is 404, never 403", async () => {
// A different org, not just a different project: an Agent Vault project is a per-org singleton, so
// a second one in this org would be what the caller's own routes resolve to.
const [foreignOrg] = (await testDb("organizations")
.insert({ name: "foreign org", slug: `foreign-org-${Date.now()}`, customerId: null })
.returning("*")) as { id: string }[];
const [foreignProject] = (await testDb("projects")
.insert({
name: "foreign agent vault",
slug: `foreign-agent-vault-${Date.now()}`,
type: ProjectType.AgentVault,
orgId: foreignOrg.id,
version: 3
})
.returning("*")) as { id: string }[];
const [foreignBundle] = (await testDb("agent_vault_access_bundles")
.insert({ projectId: foreignProject.id, name: "foreign-bundle" })
.returning("*")) as { id: string }[];
// Never 403: a 403 would confirm that another tenant's bundle id exists.
const res = await inject("GET", `/api/v1/agent-vault/access-bundles/${foreignBundle.id}`);
expect(res.statusCode).toBe(404);
await testDb("organizations").where({ id: foreignOrg.id }).delete();
});
test("an unknown access bundle id is 404 across every sub-route", async () => {
const unknown = "11111111-2222-3333-4444-555555555555";
const routes: ["GET" | "POST" | "PATCH" | "DELETE", string, Record<string, unknown> | undefined][] = [
["GET", `/api/v1/agent-vault/access-bundles/${unknown}`, undefined],
["PATCH", `/api/v1/agent-vault/access-bundles/${unknown}`, { name: "renamed" }],
["DELETE", `/api/v1/agent-vault/access-bundles/${unknown}`, undefined],
["GET", `/api/v1/agent-vault/access-bundles/${unknown}/members`, undefined],
[
"POST",
`/api/v1/agent-vault/access-bundles/${unknown}/connections`,
{ name: "c", hostPattern: "api.foo.com", credential: { type: "passthrough" } }
]
];
for await (const [method, url, body] of routes) {
const res = await inject(method, url, body);
expect([method, url, res.statusCode]).toEqual([method, url, 404]);
}
});
});
describe("sessions", async () => {
test("the bundle set comes only from the session row", async () => {
const granted = await createAccessBundle("session-granted");
const notNamed = await createAccessBundle("session-not-named");
const mint = await inject("POST", "/api/v1/agent-vault/sessions", {
accessBundleIds: [granted.id],
ttl: "24h"
});
expect(mint.statusCode).toBe(200);
const { session } = JSON.parse(mint.payload) as {
session: { id: string; token: string; accessBundles: { id: string; position: number }[] };
};
expect(session.token.startsWith("agv_")).toBe(true);
expect(session.accessBundles).toEqual([expect.objectContaining({ id: granted.id, position: 0 })]);
// The ceiling is the session row, and nothing adds to it after mint.
const rows = (await testDb("agent_vault_session_access_bundles")
.where({ sessionId: session.id })
.select("accessBundleId")) as { accessBundleId: string }[];
expect(rows.map((row) => row.accessBundleId)).toEqual([granted.id]);
expect(rows.map((row) => row.accessBundleId)).not.toContain(notNamed.id);
});
test("the token is stored only as a hash and is returned exactly once", async () => {
const bundle = await createAccessBundle("session-token-hash");
const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundleIds: [bundle.id], ttl: "1h" });
const { session } = JSON.parse(mint.payload) as { session: { id: string; token: string } };
const row = await testDb("agent_vault_sessions").where({ id: session.id }).first();
expect(row.tokenHash).toHaveLength(64);
expect(row.tokenHash).not.toBe(session.token);
expect(JSON.stringify(row)).not.toContain(session.token);
const list = await inject("GET", "/api/v1/agent-vault/sessions");
expect(list.payload).not.toContain(session.token);
});
test("naming a bundle you cannot reach fails with that bundle named", async () => {
const res = await inject("POST", "/api/v1/agent-vault/sessions", {
accessBundleIds: ["99999999-8888-7777-6666-555555555555"],
ttl: "1h"
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.payload).message).toContain("99999999-8888-7777-6666-555555555555");
});
test("a duplicated bundle is rejected rather than deduped", async () => {
const bundle = await createAccessBundle("session-duplicates");
const res = await inject("POST", "/api/v1/agent-vault/sessions", {
accessBundleIds: [bundle.id, bundle.id],
ttl: "1h"
});
expect(res.statusCode).toBe(400);
});
test("ttl never stores a null expiry, and revoke is idempotent", async () => {
const bundle = await createAccessBundle("session-never");
const mint = await inject("POST", "/api/v1/agent-vault/sessions", {
accessBundleIds: [bundle.id],
ttl: "never"
});
const { session } = JSON.parse(mint.payload) as { session: { id: string; expiresAt: string | null } };
expect(session.expiresAt).toBeNull();
const first = await inject("POST", `/api/v1/agent-vault/sessions/${session.id}/revoke`);
expect(first.statusCode).toBe(200);
const firstRevokedAt = JSON.parse(first.payload).session.revokedAt as string;
const second = await inject("POST", `/api/v1/agent-vault/sessions/${session.id}/revoke`);
expect(second.statusCode).toBe(200);
expect(JSON.parse(second.payload).session.revokedAt).toBe(firstRevokedAt);
const list = await inject("GET", "/api/v1/agent-vault/sessions?status=revoked");
const { sessions } = JSON.parse(list.payload) as { sessions: { id: string; status: string }[] };
expect(sessions.find((row) => row.id === session.id)?.status).toBe("revoked");
});
});
describe("session resolve", async () => {
// The resolve endpoint authenticates as an enrolled proxy, which needs a CA and a CSR, so the service
// is built from the real DALs against the test database instead. Only the two collaborators resolve
// never reaches on this path are stubbed, and getProjectPermission deliberately succeeds: it does
// succeed for a deactivated actor, which is the whole point of the check under test.
const buildResolver = () =>
agentVaultProxyServiceFactory({
agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),
agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultAccessBundleMemberDAL: agentVaultAccessBundleMemberDALFactory(testDb),
orgDAL: orgDALFactory(testDb),
permissionService: {
getProjectPermission: () => Promise.resolve({ hasRole: () => true })
} as never,
kmsService: {
createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })
} as never,
resourceAuthMethodService: {} as never
});
test("a deactivated actor stops resolving, and resolves again once reactivated", async () => {
const bundle = await createAccessBundle("resolve-deactivation");
const connection = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/connections`, {
name: "echo",
hostPattern: "echo.example.com",
credential: { type: "passthrough" }
});
expect(connection.statusCode).toBe(200);
const mint = await inject("POST", "/api/v1/agent-vault/sessions", {
accessBundleIds: [bundle.id],
ttl: "never"
});
const { session } = JSON.parse(mint.payload) as { session: { id: string; token: string } };
const proxyRes = await inject("POST", "/api/v1/agent-vault/proxies", { name: "resolve-deactivation" });
expect(proxyRes.statusCode).toBe(200);
const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };
const resolver = buildResolver();
const resolve = () =>
resolver.resolveSession({
proxyId: proxy.id,
orgId: seedData1.organization.id,
sessionToken: session.token
});
const membership = await testDb("memberships")
.where({ scope: AccessScope.Organization, scopeOrgId: seedData1.organization.id, actorUserId: seedData1.id })
.first();
const before = await resolve();
expect(before.connections).toHaveLength(1);
try {
await testDb("memberships").where({ id: membership.id }).update({ isActive: false });
await expect(resolve()).rejects.toThrow(UnauthorizedError);
} finally {
await testDb("memberships").where({ id: membership.id }).update({ isActive: true });
}
// Reversible on purpose: deactivation is not a revoke, so the agent comes back with the person.
const after = await resolve();
expect(after.connections).toHaveLength(1);
});
});
describe("retention sweep", async () => {
test("reaps sessions a month after they stopped working and leaves live ones alone", async () => {
const bundle = await createAccessBundle("sweep-bundle");
const mintOne = async (ttl: string) => {
const res = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundleIds: [bundle.id], ttl });
expect(res.statusCode).toBe(200);
return (JSON.parse(res.payload) as { session: { id: string } }).session.id;
};
const longExpired = await mintOne("1h");
const longRevoked = await mintOne("never");
const recentlyExpired = await mintOne("1h");
const live = await mintOne("7d");
const neverEnding = await mintOne("never");
const daysAgo = (days: number) => new Date(Date.now() - days * 24 * 60 * 60 * 1000);
await testDb("agent_vault_sessions")
.where({ id: longExpired })
.update({ expiresAt: daysAgo(31) });
await testDb("agent_vault_sessions")
.where({ id: longRevoked })
.update({ revokedAt: daysAgo(31) });
await testDb("agent_vault_sessions")
.where({ id: recentlyExpired })
.update({ expiresAt: new Date(Date.now() - 60 * 60 * 1000) });
// Start from a clean watermark so a previous run against the same Redis cannot narrow the window.
await testKeyStore.deleteItem("agent-vault-session-expire-sweep");
// The services decorator lives inside the routes plugin, out of reach here, so the sweep is built
// from the real DALs against the test database. Audit rows are dropped by the e2e license mock anyway.
const auditEvents: string[] = [];
const sweeper = agentVaultSessionServiceFactory({
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultSessionAccessBundleDAL: agentVaultSessionAccessBundleDALFactory(testDb),
agentVaultAccessBundleDAL: agentVaultAccessBundleDALFactory(testDb),
agentVaultAccessBundleMemberDAL: agentVaultAccessBundleMemberDALFactory(testDb),
permissionService: { getProjectPermission: () => Promise.reject(new Error("not used by the sweep")) },
auditLogService: {
createAuditLog: async (data) => {
auditEvents.push((data.event.metadata as { sessionId: string }).sessionId);
}
},
keyStore: testKeyStore
});
await sweeper.sweepRetiredSessions();
// Only the session that expired inside the look-back window gets an expire event; the one reaped
// today expired a month ago, and a revoked session is not an expiry.
expect(auditEvents).toEqual([recentlyExpired]);
const remaining = (await testDb("agent_vault_sessions")
.whereIn("id", [longExpired, longRevoked, recentlyExpired, live, neverEnding])
.select("id")) as { id: string }[];
expect(remaining.map((row) => row.id).sort()).toEqual([recentlyExpired, live, neverEnding].sort());
// The child rows go with the parent, and the watermark moves so the next sweep starts here.
const orphans = await testDb("agent_vault_session_access_bundles").whereIn("sessionId", [
longExpired,
longRevoked
]);
expect(orphans).toHaveLength(0);
expect(await testKeyStore.getItem("agent-vault-session-expire-sweep")).toBeTruthy();
});
});
describe("roles", async () => {
test("the predefined roles are admin and member only", async () => {
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const res = await inject("GET", `/api/v1/projects/${projectId}/roles`);
expect(res.statusCode).toBe(200);
const { roles } = JSON.parse(res.payload) as { roles: { slug: string }[] };
expect(roles.map((role) => role.slug).sort()).toEqual([
ProjectMembershipRole.Admin,
ProjectMembershipRole.Member
]);
});
});
describe("org invite", async () => {
test("grantAgentVaultAccess makes the invitee a member of the implicit project", async () => {
const inviteeEmail = `agent-vault-invite-${crypto.randomUUID()}@localhost.local`;
const res = await inject("POST", "/api/v1/invite-org/signup", {
inviteeEmails: [inviteeEmail],
organizationId: seedData1.organization.id,
grantAgentVaultAccess: true
});
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload).grantFailures).toBeUndefined();
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const user = await testDb("users").where({ username: inviteeEmail }).first();
expect(user).toBeTruthy();
const membership = await testDb("memberships")
.where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: user.id })
.first();
expect(membership).toBeTruthy();
const role = await testDb("membership_roles").where({ membershipId: membership.id }).first();
expect(role.role).toBe(ProjectMembershipRole.Member);
});
});
describe("membership", async () => {
test("a grant to someone outside the Agent Vault project is refused", async () => {
const bundle = await createAccessBundle("member-outside-project");
// The seeded machine identity is an org admin, so the bootstrap already made it a project member.
// A grant only does something for someone the project can see, so use one it cannot.
const outsider = await createOrgIdentity(`av-outsider-${Date.now()}`);
const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
identityId: outsider.id
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.payload).message).toContain("not a member of Agent Vault");
await deleteOrgIdentity(outsider.id);
});
test("exactly one actor id is required", async () => {
const bundle = await createAccessBundle("member-one-actor");
const none = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {});
expect(none.statusCode).toBe(400);
const both = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
userId: seedData1.id,
identityId: seedData1.machineIdentity.id
});
expect(both.statusCode).toBe(400);
});
test("an actor from outside the organization is refused, and an unknown id does not 500", async () => {
// The UI adds people through the email path, which checks org membership. This is the direct-API
// route to the same table, and it let any userId through to the foreign key.
const stranger = await inject("POST", "/api/v1/agent-vault/memberships", {
userId: "99999999-8888-7777-6666-555555555555",
role: ProjectMembershipRole.Member
});
expect(stranger.statusCode).toBe(400);
expect(JSON.parse(stranger.payload).message).toContain("not an active member of this organization");
const rows = await testDb("memberships").where({ actorUserId: "99999999-8888-7777-6666-555555555555" });
expect(rows).toHaveLength(0);
});
test("a deactivated machine identity cannot be added", async () => {
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const identityId = seedData1.machineIdentity.id;
const orgMembership = await testDb("memberships")
.where({ scope: AccessScope.Organization, scopeOrgId: seedData1.organization.id, actorIdentityId: identityId })
.first();
// Left in place by an earlier test in this file, and the check under test runs before the
// already-a-member one, so remove it rather than depending on the order.
await testDb("memberships")
.where({ scope: AccessScope.Project, scopeProjectId: projectId, actorIdentityId: identityId })
.del();
try {
await testDb("memberships").where({ id: orgMembership.id }).update({ isActive: false });
const res = await inject("POST", "/api/v1/agent-vault/memberships", {
identityId,
role: ProjectMembershipRole.Member
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.payload).message).toContain("not an active member of this organization");
} finally {
await testDb("memberships").where({ id: orgMembership.id }).update({ isActive: true });
}
});
test("a machine identity inherits a group's access bundles", async () => {
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const bundle = await createAccessBundle("group-inheritance");
const [group] = (await testDb("groups")
.insert({ orgId: seedData1.organization.id, name: "av-agents", slug: `av-agents-${Date.now()}` })
.returning("*")) as { id: string }[];
// The group, not the identity, is the project member and the bundle's grantee.
const [groupMembership] = (await testDb("memberships")
.insert({
scope: AccessScope.Project,
scopeOrgId: seedData1.organization.id,
scopeProjectId: projectId,
actorGroupId: group.id,
isActive: true
})
.returning("*")) as { id: string }[];
await testDb("membership_roles").insert({
membershipId: groupMembership.id,
role: ProjectMembershipRole.Member
});
const grant = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
groupId: group.id
});
expect(grant.statusCode).toBe(200);
await testDb("identity_group_membership").insert({
groupId: group.id,
identityId: seedData1.machineIdentity.id
});
// The reachability query branches on actor type: a user goes through user_group_membership and a
// machine identity through identity_group_membership. Getting that wrong denies every machine
// identity's group grants silently, which is the product's primary actor.
const reachable = await testDb("agent_vault_access_bundle_members")
.join(
"agent_vault_access_bundles",
"agent_vault_access_bundle_members.accessBundleId",
"agent_vault_access_bundles.id"
)
.where("agent_vault_access_bundles.projectId", projectId)
.whereIn(
"agent_vault_access_bundle_members.groupId",
testDb("identity_group_membership").where("identityId", seedData1.machineIdentity.id).select("groupId")
)
.select("agent_vault_access_bundle_members.accessBundleId");
expect(reachable.map((row: { accessBundleId: string }) => row.accessBundleId)).toContain(bundle.id);
await testDb("identity_group_membership").where({ groupId: group.id }).delete();
await testDb("memberships").where({ id: groupMembership.id }).delete();
await testDb("groups").where({ id: group.id }).delete();
});
test("removing an actor from the project reaps their access bundle grants", async () => {
const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
projectId: string;
};
const bundle = await createAccessBundle("grant-reaping");
const [user] = (await testDb("users")
.insert({
username: `av-reap-${Date.now()}@localhost.local`,
email: `av-reap-${Date.now()}@localhost.local`,
isAccepted: true,
authMethods: ["email"]
})
.returning("*")) as { id: string }[];
const [membership] = (await testDb("memberships")
.insert({
scope: AccessScope.Project,
scopeOrgId: seedData1.organization.id,
scopeProjectId: projectId,
actorUserId: user.id,
isActive: true
})
.returning("*")) as { id: string }[];
await testDb("membership_roles").insert({ membershipId: membership.id, role: ProjectMembershipRole.Member });
const grant = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
userId: user.id
});
expect(grant.statusCode).toBe(200);
// Removing the actor from the project must take the grant with it, in the same transaction. Skip
// that and a user with no membership keeps a bundle the mint path still honours.
const remove = await testServer.inject({
method: "DELETE",
url: `/api/v1/projects/${projectId}/memberships/${membership.id}`,
headers: authHeader
});
expect(remove.statusCode).toBe(200);
const remaining = await testDb("agent_vault_access_bundle_members")
.where({ accessBundleId: bundle.id, userId: user.id })
.first();
expect(remaining).toBeUndefined();
await testDb("memberships").where({ actorUserId: user.id }).delete();
await testDb("users").where({ id: user.id }).delete();
});
});
});