Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(agent-vault): agents that run without credentials (#8000)

Saif Ur Rahmane482f27070ac
diff --git a/CLAUDE.md b/CLAUDE.md
index b80a8f639e..fd0b4fc09b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -98,6 +98,10 @@ Run `make lint-docs-branch` after any change under `docs/`. It runs [Vale](https
Auth modes (JWT, IDENTITY_ACCESS_TOKEN, SCIM_TOKEN) are extracted in `backend/src/server/plugins/auth/`. Authorization uses CASL (`@casl/ability`) with project-level and org-level permission checks — see `backend/CLAUDE.md` for backend details and `frontend/CLAUDE.md` for frontend permission hooks/HOCs. Note: `API_KEY` and `SERVICE_TOKEN` auth modes are deprecated — do not use them in new code.
+### Org-Scoped Products
+
+PAM and Agent Vault are products over one implicit project per organization, not projects a user creates. Their URLs are `/organizations/$orgId/<product>/…` with no `$projectId`, the frontend resolves the project from the org (`useImplicitProjectId`), the backend bootstraps it lazily and blocks generic create and delete, their roles are admin or member only, and each has its own metered identities dimension (`pam_identities`, `agent_vault_identities`). When you add a `ProjectType.PAM` arm anywhere, add the Agent Vault arm beside it. See `backend/src/ee/services/pam/CLAUDE.md` and `backend/src/ee/services/agent-vault/CLAUDE.md`.
+
### Service Factory + Manual DI (Backend)
No IoC container in either backend. Every service is a factory function with explicit dependencies.
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 19e113f3b8..cdf3592400 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -535,7 +535,7 @@ Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives in
**Project permission actions** include standard CRUD plus specialized ones like `DescribeSecret` (see metadata without value), `ReadValue`, `GrantPrivileges`, `AssumePrivileges`, `Lease` (for dynamic secrets). See `ProjectPermissionActions`, `ProjectPermissionSecretActions`, `ProjectPermissionDynamicSecretActions`, and `ProjectPermissionIdentityActions` enums in `project-permission.ts`.
-Built-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. Custom roles use unpacked CASL rules stored in the database. Rules can include conditions with operators `$IN`, `$EQ`, `$NEQ`, `$GLOB` (for pattern matching like `prod-*`). See `PermissionConditionSchema` in `permission-types.ts`.
+Built-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. For PAM and Agent Vault `getPredefinedRoles` (`project-role-fns.ts`) returns only `Admin` and `Member`, because their permission dispatch resolves every other slug to the member set; the role factory delegates to that one function, so every role picker follows. Custom roles use unpacked CASL rules stored in the database. Rules can include conditions with operators `$IN`, `$EQ`, `$NEQ`, `$GLOB` (for pattern matching like `prod-*`). See `PermissionConditionSchema` in `permission-types.ts`.
**Project permission caching** uses a fingerprint-based two-tier cache (`withCacheFingerprint` in `src/lib/cache/with-cache.ts`):
- **Short-lived marker** (10s TTL) in Redis — while present, cached data is served with 0 DB reads.
@@ -737,6 +737,8 @@ EE routes register before community routes so they can override/extend endpoints
**PAM**: Before working on any `pam-*` service or router, read [`src/ee/services/pam/CLAUDE.md`](src/ee/services/pam/CLAUDE.md) for a high-level map of the PAM backend — module layout, permission model, and non-obvious invariants. It is intentionally a concept map, not a spec: read the referenced code for implementation detail. If you add a feature, keep any addition there brief (a concept or invariant, not code mechanics).
+**Agent Vault**: the same applies to the `agent-vault-*` services and routers; the concept map is [`src/ee/services/agent-vault/CLAUDE.md`](src/ee/services/agent-vault/CLAUDE.md). PAM and Agent Vault are the two **org-scoped products**: one implicit project per org, resolved lazily, whose roles collapse to admin or member. Anything that branches on `ProjectType.PAM` (metering emits, predefined roles, the billable-project count, invite grants) almost always needs an Agent Vault arm too.
+
### Server Plugins
Key plugins in `src/server/plugins/`:
diff --git a/backend/bdd/features/environment.py b/backend/bdd/features/environment.py
index 38aa071cd4..4e7541ede7 100644
--- a/backend/bdd/features/environment.py
+++ b/backend/bdd/features/environment.py
@@ -79,11 +79,16 @@ def bootstrap_infisical(context: Context):
)
resp.raise_for_status()
workspaces = resp.json()["workspaces"]
- if not workspaces:
+ # The org bootstrap creates one project per org-scoped product, and this endpoint
+ # sorts them by name, so the first one is not the Cert Manager project.
+ project = next(
+ (w for w in workspaces if w["slug"].startswith("cert-manager-")),
+ None,
+ )
+ if project is None:
raise RuntimeError(
"Expected an auto-provisioned Cert Manager project after admin signup"
)
- project = workspaces[0]
ca_slug = faker.slug()
resp = client.post(
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
new file mode 100644
index 0000000000..1a4137eea9
--- /dev/null
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -0,0 +1,1895 @@
+import crypto from "node:crypto";
+
+import { AccessScope, ActionProjectType, OrgMembershipRole, 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 { 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 { groupDALFactory } from "@app/ee/services/group/group-dal";
+import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";
+import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { UnauthorizedError } from "@app/lib/errors";
+import { initLogger } from "@app/lib/logger";
+import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
+import { ActorType } from "@app/services/auth/auth-type";
+import { identityDALFactory } from "@app/services/identity/identity-dal";
+import { usageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
+import { membershipDALFactory } from "@app/services/membership/membership-dal";
+import { orgDALFactory } from "@app/services/org/org-dal";
+import { projectDALFactory } from "@app/services/project/project-dal";
+import { roleDALFactory } from "@app/services/role/role-dal";
+import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
+import { serviceTokenDALFactory } from "@app/services/service-token/service-token-dal";
+import { userDALFactory } from "@app/services/user/user-dal";
+
+declare const testKeyStore: TKeyStoreFactory;
+
+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 } : {}) });
+
+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 buildPermissionService = () =>
+ permissionServiceFactory({
+ permissionDAL: permissionDALFactory(testDb),
+ serviceTokenDAL: serviceTokenDALFactory(testDb),
+ projectDAL: projectDALFactory(testDb),
+ keyStore: testKeyStore,
+ roleDAL: roleDALFactory(testDb),
+ userDAL: userDALFactory(testDb),
+ identityDAL: identityDALFactory(testDb),
+ additionalPrivilegeDAL: additionalPrivilegeDALFactory(testDb),
+ groupDAL: groupDALFactory(testDb),
+ secretFolderDAL: secretFolderDALFactory(testDb)
+ });
+
+const grantRows = (
+ accessBundleId: string,
+ actor: { actorUserId?: string; actorIdentityId?: string; actorGroupId?: string } = {}
+) =>
+ testDb("memberships").where({
+ scope: "resource",
+ scopeResourceType: "agent-vault-access-bundle",
+ scopeResourceId: accessBundleId,
+ ...actor
+ });
+
+const createUaIdentity = async (name: string) => {
+ const created = await inject("POST", "/api/v1/identities", {
+ name,
+ role: OrgMembershipRole.Member,
+ organizationId: seedData1.organization.id
+ });
+ expect(created.statusCode).toBe(200);
+ const identity = created.json().identity as { id: string };
+
+ const attached = await inject("POST", `/api/v1/auth/universal-auth/identities/${identity.id}`, {
+ accessTokenTTL: 3600,
+ accessTokenMaxTTL: 3600,
+ accessTokenNumUsesLimit: 0
+ });
+ expect(attached.statusCode).toBe(200);
+ const clientId = attached.json().identityUniversalAuth.clientId as string;
+
+ const secret = await inject("POST", `/api/v1/auth/universal-auth/identities/${identity.id}/client-secrets`, {});
+ expect(secret.statusCode).toBe(200);
+ const { clientSecret } = secret.json();
+
+ const login = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/auth/universal-auth/login",
+ body: { clientId, clientSecret }
+ });
+ expect(login.statusCode).toBe(200);
+ const token = login.json().accessToken as string;
+
+ const asIdentity = (method: "GET" | "POST" | "DELETE", url: string, body?: Record<string, unknown>) =>
+ testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) });
+
+ return { id: identity.id, asIdentity };
+};
+
+const deleteUaIdentity = async (identityId: string) => {
+ expect((await inject("DELETE", `/api/v1/identities/${identityId}`)).statusCode).toBe(200);
+};
+
+const createProjectGroup = async (projectId: string, name: string, role: ProjectMembershipRole) => {
+ const [group] = (await testDb("groups")
+ .insert({ orgId: seedData1.organization.id, name, slug: `${name}-${Date.now()}` })
+ .returning("*")) as { id: string }[];
+ const [membership] = (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: membership.id, role });
+ return {
+ id: group.id,
+ cleanup: async () => {
+ await testDb("identity_group_membership").where({ groupId: group.id }).delete();
+ await testDb("memberships").where({ id: membership.id }).delete();
+ await testDb("groups").where({ id: group.id }).delete();
+ }
+ };
+};
+
+const getProjectId = async () =>
+ (JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as { projectId: string }).projectId;
+
+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 empty, and an org admin joins through grant-admin-access", 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);
+
+ const seeded = await testDb("memberships").where({ scope: AccessScope.Project, scopeProjectId: projectId });
+ expect(seeded).toHaveLength(0);
+
+ const denied = await inject("GET", `/api/v1/projects/${projectId}/permissions`);
+ expect(denied.statusCode).toBe(403);
+
+ const join = await inject("POST", `/api/v1/organization-admin/projects/${projectId}/grant-admin-access`);
+ expect(join.statusCode).toBe(200);
+
+ 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);
+
+ 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("two concurrent creates for the same host do not both get in", async () => {
+ const bundle = await createAccessBundle("race-hosts");
+ const attempts = await Promise.all(
+ [1, 2].map((n) =>
+ inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: `race-${n}`,
+ hostPattern: "api.raced.example.com",
+ credential: { type: "passthrough" }
+ })
+ )
+ );
+
+ // One wins, the other is refused for the overlap rather than both landing.
+ expect(attempts.filter((res) => res.statusCode === 200)).toHaveLength(1);
+ const refused = attempts.find((res) => res.statusCode !== 200)!;
+ expect(refused.statusCode).toBe(400);
+ expect(JSON.parse(refused.payload).message).toContain("api.raced.example.com");
+
+ const rows = await testDb("agent_vault_services").where({ accessBundleId: bundle.id });
+ expect(rows).toHaveLength(1);
+ });
+
+ test("a service 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}/services`, {
+ 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);
+
+ const overlapping = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ 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");
+
+ const contained = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "datadog-wildcard",
+ hostPattern: "*.datadoghq.com",
+ credential: { type: "passthrough" }
+ });
+ expect(contained.statusCode).toBe(200);
+ });
+
+ test("a service 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}/services`, {
+ name: "github",
+ hostPattern: " API.GitHub.com ",
+ credential: { type: "bearer", value: "ghp_secret_value" }
+ });
+ expect(res.statusCode).toBe(200);
+
+ const { service } = JSON.parse(res.payload) as {
+ service: { id: string; hostPattern: string; credential: Record<string, unknown> };
+ };
+ expect(service.hostPattern).toBe("API.GitHub.com");
+ expect(service.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");
+
+ const row = await testDb("agent_vault_services").where({ id: service.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 service 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}/services`, {
+ name: "datadog",
+ hostPattern: "api.datadoghq.com",
+ credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }
+ });
+ expect(created.statusCode).toBe(200);
+ const { service } = JSON.parse(created.payload) as { service: { id: string } };
+ const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
+ const sealed = async () =>
+ (await testDb("agent_vault_services").where({ id: service.id }).first()).encryptedCredential;
+
+ 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).service.credential).toEqual({
+ type: "bearer",
+ headerName: "DD-API-KEY",
+ headerPrefix: ""
+ });
+ expect((await sealed()).equals(before)).toBe(false);
+
+ 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).service.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}/services`, {
+ name: "stripe",
+ hostPattern: "api.stripe.com",
+ credential: { type: "basic", username: "sk_live_key", password: "" }
+ });
+ expect(created.statusCode).toBe(200);
+ const { service } = JSON.parse(created.payload) as {
+ service: { id: string; credential: Record<string, unknown> };
+ };
+ expect(service.credential).toEqual({ type: "basic" });
+ expect(created.payload).not.toContain("sk_live_key");
+
+ const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
+ const sealedPair = async () => {
+ const row = await testDb("agent_vault_services").where({ id: service.id }).first();
+ expect(JSON.stringify(row.credentialConfig)).not.toContain("sk_live_key");
+ return row.encryptedCredential as Buffer;
+ };
+ const before = await sealedPair();
+
+ const emptied = await inject("PATCH", url, { credential: { type: "basic", username: "" } });
+ expect(emptied.statusCode).toBe(400);
+ expect((await sealedPair()).equals(before)).toBe(true);
+
+ const flipped = await inject("PATCH", url, { credential: { type: "basic", username: "", password: "hunter2" } });
+ expect(flipped.statusCode).toBe(200);
+ expect((await sealedPair()).equals(before)).toBe(false);
+
+ const named = await inject("PATCH", url, { credential: { type: "basic", username: "sk_live_key" } });
+ expect(named.statusCode).toBe(200);
+ const cleared = await inject("PATCH", url, { credential: { type: "basic", password: "" } });
+ expect(cleared.statusCode).toBe(200);
+ const emptiedAgain = await inject("PATCH", url, { credential: { type: "basic", username: "" } });
+ expect(emptiedAgain.statusCode).toBe(400);
+
+ const afterClear = await sealedPair();
+ const renamed = await inject("PATCH", url, { name: "stripe-live" });
+ expect(renamed.statusCode).toBe(200);
+ expect((await sealedPair()).equals(afterClear)).toBe(true);
+ });
+
+ 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}/services`, {
+ name: "github",
+ hostPattern: "api.github.com",
+ credential: { type: "bearer", value: "ghp_one" }
+ });
+ const { service } = JSON.parse(created.payload) as { service: { id: string } };
+ const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
+
+ const emptyBasic = await inject("PATCH", url, { credential: { type: "basic" } });
+ expect(emptyBasic.statusCode).toBe(400);
+
+ 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}/services`, {
+ 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}/identities/${identity.id}`, { role: "member" });
+ expect(added.statusCode).toBe(200);
+
+ const listed = await inject("GET", `${memberships}/identities`);
+ 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");
+ expect(row?.name).toBeTruthy();
+
+ const promoted = await inject("PATCH", `${memberships}/identities/${identity.id}`, { role: "admin" });
+ expect(promoted.statusCode).toBe(200);
+ expect(JSON.parse(promoted.payload).role).toBe("admin");
+
+ const removed = await inject("DELETE", `${memberships}/identities/${identity.id}`);
+ expect(removed.statusCode).toBe(200);
+
+ const after = JSON.parse((await inject("GET", `${memberships}/identities`)).payload) as {
+ members: { identityId: string }[];
+ };
+ expect(after.members.some((m) => m.identityId === identity.id)).toBe(false);
+
+ await deleteOrgIdentity(identity.id);
+ });
+
+ test("the user and group lists carry the names the Access Control page shows", async () => {
+ const users = JSON.parse((await inject("GET", `${memberships}/users`)).payload) as {
+ members: { userId: string; role: string; email: string | null; isOrgMembershipPending: boolean }[];
+ };
+ const self = users.members.find((m) => m.userId === seedData1.id);
+ expect(self?.role).toBe("admin");
+ expect(self?.email).toBe(seedData1.email);
+ expect(self?.isOrgMembershipPending).toBe(false);
+
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+ const group = await createProjectGroup(projectId, "av-list-groups", ProjectMembershipRole.Member);
+ try {
+ const groups = JSON.parse((await inject("GET", `${memberships}/groups`)).payload) as {
+ members: { groupId: string; role: string; name: string }[];
+ };
+ const row = groups.members.find((m) => m.groupId === group.id);
+ expect(row?.role).toBe("member");
+ expect(row?.name).toBe("av-list-groups");
+ } finally {
+ await group.cleanup();
+ }
+ });
+
+ test("removing a user from the organization takes their grants too", async () => {
+ const bundle = await createAccessBundle("org-removal-reap");
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+
+ const [user] = (await testDb("users")
+ .insert({ username: `av-org-reap-${Date.now()}@example.com`, isAccepted: true, isGhost: false })
+ .returning("*")) as { id: string }[];
+ const [orgMembership] = (await testDb("memberships")
+ .insert({
+ scope: AccessScope.Organization,
+ scopeOrgId: seedData1.organization.id,
+ actorUserId: user.id,
+ status: "accepted"
+ })
+ .returning("*")) as { id: string }[];
+ const [projectMembership] = (await testDb("memberships")
+ .insert({
+ scope: AccessScope.Project,
+ scopeOrgId: seedData1.organization.id,
+ scopeProjectId: projectId,
+ actorUserId: user.id
+ })
+ .returning("*")) as { id: string }[];
+ await testDb("membership_roles").insert({
+ membershipId: projectMembership.id,
+ role: ProjectMembershipRole.Member
+ });
+
+ const granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ userIds: [user.id]
+ });
+ expect(granted.statusCode).toBe(200);
+ expect(await grantRows(bundle.id, { actorUserId: user.id })).toHaveLength(1);
+
+ const removed = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/organizations/${seedData1.organization.id}/memberships/${orgMembership.id}`,
+ headers: authHeader
+ });
+ expect(removed.statusCode).toBe(200);
+
+ expect(await grantRows(bundle.id, { actorUserId: user.id })).toHaveLength(0);
+
+ await testDb("users").where({ id: user.id }).delete();
+ });
+
+ 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}/identities/${identity.id}`, { role: "member" })).statusCode).toBe(
+ 200
+ );
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ identityIds: [identity.id]
+ })
+ ).statusCode
+ ).toBe(200);
+
+ expect(await grantRows(bundle.id, { actorIdentityId: identity.id })).toHaveLength(1);
+
+ expect((await inject("DELETE", `${memberships}/identities/${identity.id}`)).statusCode).toBe(200);
+
+ expect(await grantRows(bundle.id, { actorIdentityId: identity.id })).toHaveLength(0);
+
+ await deleteOrgIdentity(identity.id);
+ });
+
+ test("the guards that keep the product administrable hold", async () => {
+ const self = await inject("DELETE", `${memberships}/users/${seedData1.id}`);
+ expect(self.statusCode).toBe(403);
+
+ const unknown = await inject("POST", `${memberships}/identities/00000000-0000-0000-0000-000000000000`, {
+ role: "member"
+ });
+ expect(unknown.statusCode).toBe(404);
+
+ const badRole = await inject("PATCH", `${memberships}/users/${seedData1.id}`, { role: "viewer" });
+ expect(badRole.statusCode).toBe(422);
+
+ const notAnId = await inject("DELETE", `${memberships}/users/not-a-uuid`);
+ expect(notAnId.statusCode).toBe(422);
+ });
+ });
+
+ describe("cross-org ids and foreign resources", async () => {
+ test("an access bundle in another organization is 404, never 403", async () => {
+ 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 }[];
+
+ 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}/services`,
+ { 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 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", {
+ accessBundles: [granted.name],
+ 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 })]);
+
+ 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", { accessBundles: [bundle.name], 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", {
+ accessBundles: ["session-no-such-bundle"],
+ ttl: "1h"
+ });
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.payload).message).toContain("session-no-such-bundle");
+ });
+
+ test("a second access bundle is rejected", async () => {
+ const res = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: ["session-cap-alpha", "session-cap-beta"],
+ ttl: "1h"
+ });
+ expect(res.statusCode).toBe(422);
+ const issues = JSON.parse(res.payload).message as { path: string[] }[];
+ expect(issues.some((issue) => issue.path.join(".") === "accessBundles")).toBe(true);
+ });
+
+ test("search filters and counts on the server, not just the page", async () => {
+ const alpha = await createAccessBundle("search-alpha");
+ const beta = await createAccessBundle("search-beta");
+ for await (const bundle of [alpha, beta]) {
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ ttl: "1h"
+ });
+ expect(mint.statusCode).toBe(200);
+ }
+
+ const byBundle = await inject("GET", "/api/v1/agent-vault/sessions?search=search-alpha");
+ expect(byBundle.statusCode).toBe(200);
+ const matched = JSON.parse(byBundle.payload) as {
+ sessions: { accessBundles: { name: string }[] }[];
+ totalCount: number;
+ };
+ expect(matched.sessions).toHaveLength(1);
+ expect(matched.sessions[0].accessBundles[0].name).toBe("search-alpha");
+ // The count has to describe the filtered set, or the pager offers pages that do not exist.
+ expect(matched.totalCount).toBe(1);
+
+ // The list shows the live actor name, so the search has to reach it and not only the mint snapshot.
+ const byActor = await inject(
+ "GET",
+ `/api/v1/agent-vault/sessions?search=${encodeURIComponent(seedData1.username)}`
+ );
+ const byActorBody = JSON.parse(byActor.payload) as { totalCount: number };
+ expect(byActorBody.totalCount).toBeGreaterThan(0);
+
+ const noMatch = await inject("GET", "/api/v1/agent-vault/sessions?search=search-nothing");
+ const empty = JSON.parse(noMatch.payload) as { sessions: unknown[]; totalCount: number };
+ expect(empty.sessions).toHaveLength(0);
+ expect(empty.totalCount).toBe(0);
+ });
+
+ test("search covers every name a row can display, and pages within the match", async () => {
+ // scope=all throughout: a session whose actor was deleted has no userId, so it belongs to nobody and
+ // the default Mine scope filters it out. Only an admin listing everyone's sessions can see it.
+ const list = async (query: string) => {
+ const res = await inject("GET", `/api/v1/agent-vault/sessions?scope=all&${query}`);
+ expect(res.statusCode).toBe(200);
+ return JSON.parse(res.payload) as {
+ sessions: { id: string; actorName: string; accessBundles: { name: string }[] }[];
+ totalCount: number;
+ };
+ };
+
+ const bundles = await Promise.all(
+ ["matrix-stripe", "matrix-github", "matrix-openai"].map((name) => createAccessBundle(name))
+ );
+ const minted: string[] = [];
+ for await (const bundle of bundles) {
+ // Two sessions per bundle, so a match has to page rather than fit on one screen.
+ for await (const attempt of [1, 2]) {
+ const res = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ ttl: "1h"
+ });
+ expect(res.statusCode, `mint ${attempt} over ${bundle.name}`).toBe(200);
+ minted.push((JSON.parse(res.payload) as { session: { id: string } }).session.id);
+ }
+ }
+
+ // A deleted actor: the row keeps the snapshot the mint took, and nothing to join to.
+ const orphaned = minted[0];
+ await testDb("agent_vault_sessions")
+ .where({ id: orphaned })
+ .update({ userId: null, identityId: null, actorName: "Gone Person", actorEmail: "[email protected]" });
+
+ // A deleted bundle: the junction keeps its snapshot name.
+ const deletedBundle = await createAccessBundle("matrix-retired");
+ const overRetired = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [deletedBundle.name],
+ ttl: "1h"
+ });
+ expect(overRetired.statusCode).toBe(200);
+ expect((await inject("DELETE", `/api/v1/agent-vault/access-bundles/${deletedBundle.id}`)).statusCode).toBe(200);
+
+ const cases: { why: string; query: string; expect: (r: Awaited<ReturnType<typeof list>>) => void }[] = [
+ {
+ why: "a live bundle name",
+ query: "search=matrix-stripe&limit=100",
+ expect: (r) => {
+ expect(r.totalCount).toBe(2);
+ expect(r.sessions.every((row) => row.accessBundles[0].name === "matrix-stripe")).toBe(true);
+ }
+ },
+ {
+ why: "a prefix shared by several bundles",
+ query: "search=matrix-&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(7)
+ },
+ {
+ why: "case is ignored",
+ query: "search=MATRIX-GITHUB&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(2)
+ },
+ {
+ why: "the live actor name, from the joined user",
+ query: `search=${encodeURIComponent(seedData1.username)}&limit=100`,
+ expect: (r) => expect(r.totalCount).toBeGreaterThan(0)
+ },
+ {
+ why: "the snapshot name once the actor is gone",
+ query: "search=Gone%20Person&limit=100",
+ expect: (r) => {
+ expect(r.totalCount).toBe(1);
+ expect(r.sessions[0].id).toBe(orphaned);
+ }
+ },
+ {
+ why: "the snapshot email once the actor is gone",
+ query: "[email protected]&limit=100",
+ expect: (r) => expect(r.sessions.map((row) => row.id)).toEqual([orphaned])
+ },
+ {
+ why: "a deleted bundle, by the name the junction kept",
+ query: "search=matrix-retired&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(1)
+ },
+ {
+ why: "a LIKE wildcard is a literal, not a pattern",
+ query: "search=%25&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(0)
+ },
+ {
+ why: "an underscore is a literal too",
+ query: "search=matrix_stripe&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(0)
+ },
+ {
+ why: "no match reports nothing, so the pager can hide",
+ query: "search=matrix-nothing-here&limit=100",
+ expect: (r) => {
+ expect(r.sessions).toHaveLength(0);
+ expect(r.totalCount).toBe(0);
+ }
+ },
+ {
+ why: "the count describes the match, and the page is a slice of it",
+ query: "search=matrix-&limit=3&offset=0",
+ expect: (r) => {
+ expect(r.sessions).toHaveLength(3);
+ expect(r.totalCount).toBe(7);
+ }
+ },
+ {
+ why: "the last page of a match is partial, not empty",
+ query: "search=matrix-&limit=3&offset=6",
+ expect: (r) => {
+ expect(r.sessions).toHaveLength(1);
+ expect(r.totalCount).toBe(7);
+ }
+ },
+ {
+ why: "search and status narrow together; the ownerless row reads as revoked, not active",
+ query: "search=matrix-&status=active&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(6)
+ },
+ {
+ why: "the ownerless row is the only revoked one inside the match",
+ query: "search=matrix-&status=revoked&limit=100",
+ expect: (r) => {
+ expect(r.totalCount).toBe(1);
+ expect(r.sessions[0].id).toBe(orphaned);
+ }
+ },
+ {
+ why: "a status with no members inside the match is empty",
+ query: "search=matrix-&status=expired&limit=100",
+ expect: (r) => expect(r.totalCount).toBe(0)
+ }
+ ];
+
+ for await (const testCase of cases) {
+ const result = await list(testCase.query);
+ try {
+ testCase.expect(result);
+ } catch (err) {
+ throw new Error(`search case failed (${testCase.why}): ${(err as Error).message}`);
+ }
+ }
+ });
+
+ test("a bundle name that is not a slug is rejected before the lookup", async () => {
+ const bundle = await createAccessBundle("session-uppercase");
+ const res = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name.toUpperCase()],
+ ttl: "1h"
+ });
+ expect(res.statusCode).toBe(422);
+ });
+
+ test("ttl is a free-form duration with a one minute floor", async () => {
+ const bundle = await createAccessBundle("session-ttl-free");
+ const before = Date.now();
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "90m" });
+ expect(mint.statusCode).toBe(200);
+ const { session } = JSON.parse(mint.payload) as { session: { expiresAt: string } };
+ const lifetimeMs = new Date(session.expiresAt).getTime() - before;
+ expect(lifetimeMs).toBeGreaterThanOrEqual(90 * 60 * 1000 - 5_000);
+ expect(lifetimeMs).toBeLessThanOrEqual(90 * 60 * 1000 + 60_000);
+
+ const tooShort = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ ttl: "30s"
+ });
+ expect(tooShort.statusCode).toBe(422);
+ const garbage = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ ttl: "soon"
+ });
+ expect(garbage.statusCode).toBe(422);
+ });
+
+ 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", {
+ accessBundles: [bundle.name],
+ 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 () => {
+ const buildResolver = () =>
+ agentVaultProxyServiceFactory({
+ agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),
+ agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),
+ agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ membershipDAL: membershipDALFactory(testDb),
+ orgDAL: orgDALFactory(testDb),
+ permissionService: buildPermissionService(),
+ 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 service = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "echo",
+ hostPattern: "echo.example.com",
+ credential: { type: "passthrough" }
+ });
+ expect(service.statusCode).toBe(200);
+
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ 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.services).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 });
+ }
+
+ const after = await resolve();
+ expect(after.services).toHaveLength(1);
+ });
+ // The actor columns are SET NULL so the row outlives its owner. A null id must never reach the
+ // membership lookups: there it compiles to IS NULL, matches every user row, and once resolved as admin.
+ test("a session whose user was deleted is refused before any lookup", async () => {
+ const bundle = await createAccessBundle("resolve-deleted-user");
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "echo",
+ hostPattern: "echo.example.com",
+ credential: { type: "passthrough" }
+ });
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], 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-deleted-user" });
+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };
+ const resolve = () =>
+ buildResolver().resolveSession({
+ proxyId: proxy.id,
+ orgId: seedData1.organization.id,
+ sessionToken: session.token
+ });
+
+ const [doomed] = (await testDb("users")
+ .insert({ username: `doomed-${crypto.randomUUID()}`, isAccepted: true })
+ .returning("*")) as { id: string }[];
+ await testDb("agent_vault_sessions").where({ id: session.id }).update({ userId: doomed.id });
+ await testDb("users").where({ id: doomed.id }).del();
+
+ const row = await testDb("agent_vault_sessions").where({ id: session.id }).first();
+ expect(row.userId).toBeNull();
+ expect(row.identityId).toBeNull();
+ await expect(resolve()).rejects.toThrow("The identity this session belonged to has been deleted");
+ });
+
+ test("a session whose machine identity was deleted is refused before any lookup", async () => {
+ const bundle = await createAccessBundle("resolve-deleted-identity");
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "echo",
+ hostPattern: "echo.example.com",
+ credential: { type: "passthrough" }
+ });
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], 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-deleted-identity" });
+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };
+ const resolve = () =>
+ buildResolver().resolveSession({
+ proxyId: proxy.id,
+ orgId: seedData1.organization.id,
+ sessionToken: session.token
+ });
+
+ const identity = await createOrgIdentity(`doomed-${crypto.randomUUID()}`);
+ await testDb("agent_vault_sessions").where({ id: session.id }).update({ userId: null, identityId: identity.id });
+ await deleteOrgIdentity(identity.id);
+
+ await expect(resolve()).rejects.toThrow("The identity this session belonged to has been deleted");
+
+ // The list agrees with resolve: an ownerless session is shown as revoked, not active.
+ const list = await inject("GET", "/api/v1/agent-vault/sessions?scope=all&limit=100");
+ const { sessions } = JSON.parse(list.payload) as { sessions: { id: string; status: string }[] };
+ expect(sessions.find((row) => row.id === session.id)?.status).toBe("revoked");
+ });
+
+ test("an expired time-limited role stops resolving even though its membership row remains", async () => {
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+ const bundle = await createAccessBundle("resolve-temporary-role");
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "echo",
+ hostPattern: "echo.example.com",
+ credential: { type: "passthrough" }
+ });
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], 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-temporary-role" });
+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };
+
+ const resolver = agentVaultProxyServiceFactory({
+ agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),
+ agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),
+ agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ membershipDAL: membershipDALFactory(testDb),
+ orgDAL: orgDALFactory(testDb),
+ permissionService: buildPermissionService(),
+ kmsService: {
+ createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })
+ } as never,
+ resourceAuthMethodService: {} as never
+ });
+ const resolve = () =>
+ resolver.resolveSession({ proxyId: proxy.id, orgId: seedData1.organization.id, sessionToken: session.token });
+
+ const membership = await testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: seedData1.id })
+ .first();
+ const role = await testDb("membership_roles").where({ membershipId: membership.id }).first();
+
+ // getProjectPermission caches the raw membership rows for ten seconds, so clear it around each flip.
+ const cacheKeys = [
+ KeyStorePrefixes.ProjectPermissionMarker(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault),
+ KeyStorePrefixes.ProjectPermissionData(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault)
+ ];
+
+ try {
+ await testDb("membership_roles")
+ .where({ id: role.id })
+ .update({ isTemporary: true, temporaryAccessEndTime: new Date(Date.now() - 60_000) });
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+ await expect(resolve()).rejects.toThrow(UnauthorizedError);
+ } finally {
+ await testDb("membership_roles")
+ .where({ id: role.id })
+ .update({ isTemporary: false, temporaryAccessEndTime: null });
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+ }
+
+ expect((await resolve()).services).toHaveLength(1);
+ });
+ });
+
+ describe("proxies", async () => {
+ test("create and reissue both hand back the enrollment token at the top level", async () => {
+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: "flat-token-shape" });
+ expect(created.statusCode).toBe(200);
+ const body = JSON.parse(created.payload) as { proxy: { id: string }; token: string; expiresAt: string };
+ expect(body.token).toBeTruthy();
+ expect(body.expiresAt).toBeTruthy();
+
+ const reissued = await inject(
+ "POST",
+ `/api/v1/agent-vault/proxies/${body.proxy.id}/token-auth/generate-enrollment-token`
+ );
+ expect(reissued.statusCode).toBe(200);
+ const again = JSON.parse(reissued.payload) as { token: string; expiresAt: string };
+ expect(again.token).toBeTruthy();
+ expect(again.token).not.toBe(body.token);
+ expect(again.expiresAt).toBeTruthy();
+ });
+
+ test("revoking access also burns an enrollment token minted before the revoke", async () => {
+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: "revoke-burns-token" });
+ expect(created.statusCode).toBe(200);
+ const { proxy } = JSON.parse(created.payload) as { proxy: { id: string } };
+
+ const pendingTokens = async () => {
+ const row = (await testDb("resource_token_auths")
+ .join("resource_auth_methods", "resource_auth_methods.id", "resource_token_auths.authMethodId")
+ .where("resource_auth_methods.agentVaultProxyId", proxy.id)
+ .count("resource_token_auths.id as count")
+ .first()) as { count: string };
+ return Number(row.count);
+ };
+ expect(await pendingTokens()).toBe(1);
+
+ const revoked = await inject("POST", `/api/v1/agent-vault/proxies/${proxy.id}/revoke`);
+ expect(revoked.statusCode).toBe(200);
+ expect(await pendingTokens()).toBe(0);
+
+ const row = await testDb("agent_vault_proxies").where({ id: proxy.id }).first();
+ expect(row.tokenVersion).toBe(1);
+ expect(row.heartbeat).toBeNull();
+ expect(row.heartbeatTTL).toBeNull();
+ });
+
+ test("lowering the poll interval does not report a live proxy as unreachable", async () => {
+ const created = await inject("POST", "/api/v1/agent-vault/proxies", {
+ name: "poll-interval-health",
+ pollInterval: 60
+ });
+ expect(created.statusCode).toBe(200);
+ const { proxy } = JSON.parse(created.payload) as { proxy: { id: string } };
+
+ const isHealthy = async () => {
+ const list = await inject("GET", "/api/v1/agent-vault/proxies");
+ const found = (JSON.parse(list.payload) as { proxies: { id: string; isHealthy: boolean }[] }).proxies.find(
+ (p) => p.id === proxy.id
+ );
+ return found?.isHealthy;
+ };
+
+ // A check-in 40s ago on a 60s interval: inside 60 x 3, and the proxy is still on that schedule.
+ await testDb("agent_vault_proxies")
+ .where({ id: proxy.id })
+ .update({ heartbeat: new Date(Date.now() - 40_000), heartbeatTTL: 60 });
+ expect(await isHealthy()).toBe(true);
+
+ // Dropping to 10 would make 40s look like four missed check-ins, but the proxy has not been told
+ // yet: it learns the new interval on its next poll, which is still 60s out from the last one.
+ const patched = await inject("PATCH", `/api/v1/agent-vault/proxies/${proxy.id}`, { pollInterval: 10 });
+ expect(patched.statusCode).toBe(200);
+ expect(await isHealthy()).toBe(true);
+
+ // Once it checks in, both sides are on 10 and the tighter window applies.
+ await testDb("agent_vault_proxies")
+ .where({ id: proxy.id })
+ .update({ heartbeat: new Date(Date.now() - 40_000), heartbeatTTL: 10 });
+ expect(await isHealthy()).toBe(false);
+ });
+ });
+
+ 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", { accessBundles: [bundle.name], 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 oldOrphan = await mintOne("never");
+ const recentOrphan = await mintOne("never");
+
+ const daysAgo = (days: number) => new Date(Date.now() - days * 24 * 60 * 60 * 1000);
+ // Ownerless sessions go by age, since nothing records when their actor was deleted.
+ await testDb("agent_vault_sessions")
+ .where({ id: oldOrphan })
+ .update({ userId: null, identityId: null, createdAt: daysAgo(31) });
+ await testDb("agent_vault_sessions").where({ id: recentOrphan }).update({ userId: null, identityId: null });
+ 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) });
+ const sweeper = agentVaultSessionServiceFactory({
+ agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ agentVaultSessionAccessBundleDAL: agentVaultSessionAccessBundleDALFactory(testDb),
+ agentVaultAccessBundleDAL: agentVaultAccessBundleDALFactory(testDb),
+ membershipDAL: membershipDALFactory(testDb),
+ permissionService: { getProjectPermission: () => Promise.reject(new Error("not used by the sweep")) }
+ });
+ await sweeper.sweepRetiredSessions();
+
+ const remaining = (await testDb("agent_vault_sessions")
+ .whereIn("id", [longExpired, longRevoked, recentlyExpired, live, neverEnding, oldOrphan, recentOrphan])
+ .select("id")) as { id: string }[];
+ expect(remaining.map((row) => row.id).sort()).toEqual([recentlyExpired, live, neverEnding, recentOrphan].sort());
+
+ const orphans = await testDb("agent_vault_session_access_bundles").whereIn("sessionId", [
+ longExpired,
+ longRevoked,
+ oldOrphan
+ ]);
+ expect(orphans).toHaveLength(0);
+ });
+ });
+
+ 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("generic project routes", async () => {
+ // The org-level pages reach the Agent Vault project through the platform's own membership routes, so the
+ // last-admin rule has to hold there too, not only on the product routes.
+ const projectFor = async () =>
+ (JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as { projectId: string }).projectId;
+ const seedMembership = async (projectId: string) =>
+ testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: seedData1.id })
+ .first();
+ const clearSeedPermissionCache = (projectId: string) =>
+ testKeyStore.deleteItemsByKeyIn([
+ KeyStorePrefixes.ProjectPermissionMarker(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault),
+ KeyStorePrefixes.ProjectPermissionData(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault)
+ ]);
+
+ test("the generic role change refuses to demote the last Agent Vault admin", async () => {
+ const projectId = await projectFor();
+ const membership = await seedMembership(projectId);
+
+ const res = await inject("PATCH", `/api/v1/projects/${projectId}/memberships/${membership.id}`, {
+ roles: [{ role: ProjectMembershipRole.Member }]
+ });
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.payload).message).toContain("must keep at least one admin");
+
+ const role = await testDb("membership_roles").where({ membershipId: membership.id }).first();
+ expect(role.role).toBe(ProjectMembershipRole.Admin);
+ });
+
+ test("leaving through the generic route refuses when you are the last Agent Vault admin", async () => {
+ const projectId = await projectFor();
+
+ const res = await inject("DELETE", `/api/v1/projects/${projectId}/leave`);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.payload).message).toContain("must keep at least one admin");
+ expect(await seedMembership(projectId)).toBeTruthy();
+ });
+
+ test("the generic role change goes through once another admin exists", async () => {
+ const projectId = await projectFor();
+ const membership = await seedMembership(projectId);
+ const other = await createOrgIdentity(`av-second-admin-${Date.now()}`);
+ expect(
+ (await inject("POST", `/api/v1/agent-vault/memberships/identities/${other.id}`, { role: "admin" })).statusCode
+ ).toBe(200);
+
+ try {
+ const demoted = await inject("PATCH", `/api/v1/projects/${projectId}/memberships/${membership.id}`, {
+ roles: [{ role: ProjectMembershipRole.Member }]
+ });
+ expect(demoted.statusCode).toBe(200);
+ const role = await testDb("membership_roles").where({ membershipId: membership.id }).first();
+ expect(role.role).toBe(ProjectMembershipRole.Member);
+ } finally {
+ await testDb("membership_roles")
+ .where({ membershipId: membership.id })
+ .update({ role: ProjectMembershipRole.Admin });
+ await clearSeedPermissionCache(projectId);
+ await deleteOrgIdentity(other.id);
+ }
+ });
+ });
+
+ 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);
+ });
+
+ test("an org admin who never opened Agent Vault is joined as admin by inviting with access", async () => {
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+ // getProjectPermission caches the membership rows for ten seconds, so the cache is cleared around
+ // each direct edit or the server keeps seeing the row that was just removed.
+ const cacheKeys = [
+ KeyStorePrefixes.ProjectPermissionMarker(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault),
+ KeyStorePrefixes.ProjectPermissionData(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault)
+ ];
+ const inviterMembership = () =>
+ testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: seedData1.id })
+ .first();
+
+ // Remove the inviter's own membership so they look like an org admin arriving fresh.
+ const before = await inviterMembership();
+ await testDb("memberships").where({ id: before.id }).del();
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+
+ try {
+ const inviteeEmail = `agent-vault-invite-fresh-${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 inviter = await inviterMembership();
+ expect(inviter).toBeTruthy();
+ const inviterRole = await testDb("membership_roles").where({ membershipId: inviter.id }).first();
+ expect(inviterRole.role).toBe(ProjectMembershipRole.Admin);
+
+ const user = await testDb("users").where({ username: inviteeEmail }).first();
+ const invitee = await testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: user.id })
+ .first();
+ expect(invitee).toBeTruthy();
+ } finally {
+ // Later tests act as this admin, so put the membership back if the self-join did not.
+ if (!(await inviterMembership())) {
+ const [restored] = (await testDb("memberships")
+ .insert({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ scopeOrgId: seedData1.organization.id,
+ actorUserId: seedData1.id
+ })
+ .returning("*")) as { id: string }[];
+ await testDb("membership_roles").insert({ membershipId: restored.id, role: ProjectMembershipRole.Admin });
+ }
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+ }
+ });
+
+ test("an org admin who is an Agent Vault member is not promoted by inviting with access", async () => {
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+ const cacheKeys = [
+ KeyStorePrefixes.ProjectPermissionMarker(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault),
+ KeyStorePrefixes.ProjectPermissionData(projectId, ActorType.USER, seedData1.id, ActionProjectType.AgentVault)
+ ];
+ const membership = await testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: seedData1.id })
+ .first();
+ await testDb("membership_roles")
+ .where({ membershipId: membership.id })
+ .update({ role: ProjectMembershipRole.Member });
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+
+ try {
+ const inviteeEmail = `agent-vault-invite-member-${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?.agentVaultAccess).toBe(true);
+
+ const role = await testDb("membership_roles").where({ membershipId: membership.id }).first();
+ expect(role.role).toBe(ProjectMembershipRole.Member);
+ } finally {
+ await testDb("membership_roles")
+ .where({ membershipId: membership.id })
+ .update({ role: ProjectMembershipRole.Admin });
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+ }
+ });
+ });
+
+ describe("membership", async () => {
+ test("a grant to someone outside the Agent Vault project is refused", async () => {
+ const bundle = await createAccessBundle("member-outside-project");
+
+ const outsider = await createOrgIdentity(`av-outsider-${Date.now()}`);
+
+ const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ identityIds: [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("a grant to someone who is in the product only through a group says so", async () => {
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+ const bundle = await createAccessBundle("member-via-group");
+ const insider = await createOrgIdentity(`av-via-group-${Date.now()}`);
+
+ const [group] = (await testDb("groups")
+ .insert({ orgId: seedData1.organization.id, name: "av-via-group", slug: `av-via-group-${Date.now()}` })
+ .returning("*")) as { id: string }[];
+ 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 });
+ await testDb("identity_group_membership").insert({ groupId: group.id, identityId: insider.id });
+
+ try {
+ const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ identityIds: [insider.id]
+ });
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.payload).message).toContain("through a group");
+
+ const asGroup = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ groupIds: [group.id]
+ });
+ expect(asGroup.statusCode).toBe(200);
+ } finally {
+ 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();
+ await deleteOrgIdentity(insider.id);
+ }
+ });
+
+ test("a grant has to name at least one actor", async () => {
+ const bundle = await createAccessBundle("member-one-actor");
+
+ // The three lists each default to empty, so a body naming nobody is refused by the schema and
+ // never reaches the service.
+ const none = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {});
+ expect(none.statusCode).toBe(422);
+
+ const empty = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ userIds: [],
+ identityIds: [],
+ groupIds: []
+ });
+ expect(empty.statusCode).toBe(422);
+
+ const notAnId = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ userIds: ["not-a-uuid"]
+ });
+ expect(notAnId.statusCode).toBe(422);
+ });
+
+ test("one call grants several actors, dedupes repeats and skips the already granted", async () => {
+ const projectId = await getProjectId();
+ const bundle = await createAccessBundle("member-batch");
+ const first = await createProjectGroup(projectId, "av-batch-one", ProjectMembershipRole.Member);
+ const second = await createProjectGroup(projectId, "av-batch-two", ProjectMembershipRole.Member);
+
+ try {
+ const granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ groupIds: [first.id, second.id, first.id]
+ });
+ expect(granted.statusCode).toBe(200);
+ expect(JSON.parse(granted.payload)).toMatchObject({ skipped: [] });
+ expect(JSON.parse(granted.payload).members).toHaveLength(2);
+ expect(await grantRows(bundle.id, { actorGroupId: first.id })).toHaveLength(1);
+ expect(await grantRows(bundle.id, { actorGroupId: second.id })).toHaveLength(1);
+
+ const again = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ groupIds: [first.id, second.id]
+ });
+ expect(again.statusCode).toBe(200);
+ const repeat = JSON.parse(again.payload) as { members: unknown[]; skipped: string[] };
+ expect(repeat.members).toEqual([]);
+ expect(repeat.skipped.sort()).toEqual([first.id, second.id].sort());
+ } finally {
+ await first.cleanup();
+ await second.cleanup();
+ }
+ });
+
+ test("two admins demoted at once cannot both slip past the last-admin guard", async () => {
+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {
+ projectId: string;
+ };
+ const one = await createUaIdentity(`av-race-a-${Date.now()}`);
+ const two = await createUaIdentity(`av-race-b-${Date.now()}`);
+
+ try {
+ for await (const identity of [one, two]) {
+ const added = await inject("POST", `/api/v1/agent-vault/memberships/identities/${identity.id}`, {
+ role: ProjectMembershipRole.Admin
+ });
+ expect(added.statusCode).toBe(200);
+ }
+
+ // Demote everyone at once. Whatever interleaving wins, an admin has to be left standing.
+ const admins = (await testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId })
+ .select("id")) as { id: string }[];
+
+ await Promise.all(
+ [one, two].map((identity) =>
+ inject("PATCH", `/api/v1/agent-vault/memberships/identities/${identity.id}`, {
+ role: ProjectMembershipRole.Member
+ })
+ )
+ );
+
+ const remainingAdmins = (await testDb("membership_roles")
+ .whereIn(
+ "membershipId",
+ admins.map((row) => row.id)
+ )
+ .where({ role: ProjectMembershipRole.Admin })) as unknown[];
+ expect(remainingAdmins.length).toBeGreaterThan(0);
+ } finally {
+ await deleteUaIdentity(one.id);
+ await deleteUaIdentity(two.id);
+ }
+ });
+
+ test("an actor from outside the organization is refused, and an unknown id does not 500", async () => {
+ // Users join through the bulk route; only groups and identities are named in the URL.
+ const stranger = await inject("POST", "/api/v1/agent-vault/memberships/users", {
+ userIds: ["99999999-8888-7777-6666-555555555555"],
+ emails: [],
+ 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();
+
+ 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/identities/${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, on mint and on resolve", async () => {
+ const projectId = await getProjectId();
+ const bundle = await createAccessBundle("group-inheritance");
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "echo",
+ hostPattern: "echo.example.com",
+ credential: { type: "passthrough" }
+ })
+ ).statusCode
+ ).toBe(200);
+ const second = await createAccessBundle("group-inheritance-late");
+
+ const proxyRes = await inject("POST", "/api/v1/agent-vault/proxies", { name: "group-inheritance" });
+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };
+
+ const group = await createProjectGroup(projectId, "av-agents", ProjectMembershipRole.Member);
+ const agent = await createUaIdentity(`av-agent-${Date.now()}`);
+ await testDb("identity_group_membership").insert({ groupId: group.id, identityId: agent.id });
+
+ try {
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ groupIds: [group.id]
+ })
+ ).statusCode
+ ).toBe(200);
+
+ const mint = await agent.asIdentity("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ ttl: "never"
+ });
+ expect(mint.statusCode).toBe(200);
+ const { session } = JSON.parse(mint.payload) as { session: { id: string; token: string } };
+
+ const resolver = agentVaultProxyServiceFactory({
+ agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),
+ agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),
+ agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ membershipDAL: membershipDALFactory(testDb),
+ orgDAL: orgDALFactory(testDb),
+ permissionService: buildPermissionService(),
+ kmsService: {
+ createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })
+ } as never,
+ resourceAuthMethodService: {} as never
+ });
+ const resolve = () =>
+ resolver.resolveSession({ proxyId: proxy.id, orgId: seedData1.organization.id, sessionToken: session.token });
+
+ expect((await resolve()).services).toHaveLength(1);
+
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${second.id}/members`, {
+ groupIds: [group.id]
+ })
+ ).statusCode
+ ).toBe(200);
+ expect((await resolve()).services).toHaveLength(1);
+
+ const [grant] = await grantRows(bundle.id, { actorGroupId: group.id });
+ expect(
+ (await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}/members/${grant.id}`)).statusCode
+ ).toBe(200);
+ expect((await resolve()).services).toHaveLength(0);
+
+ const remint = await agent.asIdentity("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [bundle.name],
+ ttl: "never"
+ });
+ expect(remint.statusCode).toBe(400);
+ expect(JSON.parse(remint.payload).message).toContain("is granted to you");
+ } finally {
+ await deleteUaIdentity(agent.id);
+ await group.cleanup();
+ }
+ });
+
+ test("a group's grants stop counting the moment the group's role lapses", async () => {
+ const projectId = await getProjectId();
+ const bundle = await createAccessBundle("group-role-lapse");
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ name: "echo",
+ hostPattern: "echo.example.com",
+ credential: { type: "passthrough" }
+ })
+ ).statusCode
+ ).toBe(200);
+ const proxyRes = await inject("POST", "/api/v1/agent-vault/proxies", { name: "group-role-lapse" });
+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };
+
+ const group = await createProjectGroup(projectId, "av-lapsing", ProjectMembershipRole.Member);
+ const agent = await createUaIdentity(`av-lapse-${Date.now()}`);
+ expect(
+ (await inject("POST", `/api/v1/agent-vault/memberships/identities/${agent.id}`, { role: "member" })).statusCode
+ ).toBe(200);
+ await testDb("identity_group_membership").insert({ groupId: group.id, identityId: agent.id });
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ groupIds: [group.id]
+ })
+ ).statusCode
+ ).toBe(200);
+
+ const cacheKeys = [
+ KeyStorePrefixes.ProjectPermissionMarker(projectId, ActorType.IDENTITY, agent.id, ActionProjectType.AgentVault),
+ KeyStorePrefixes.ProjectPermissionData(projectId, ActorType.IDENTITY, agent.id, ActionProjectType.AgentVault)
+ ];
+ const mint = () =>
+ agent.asIdentity("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "never" });
+
+ try {
+ const live = await mint();
+ expect(live.statusCode).toBe(200);
+ const { session } = JSON.parse(live.payload) as { session: { token: string } };
+
+ const resolver = agentVaultProxyServiceFactory({
+ agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),
+ agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),
+ agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ membershipDAL: membershipDALFactory(testDb),
+ orgDAL: orgDALFactory(testDb),
+ permissionService: buildPermissionService(),
+ kmsService: {
+ createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })
+ } as never,
+ resourceAuthMethodService: {} as never
+ });
+ const resolve = () =>
+ resolver.resolveSession({ proxyId: proxy.id, orgId: seedData1.organization.id, sessionToken: session.token });
+ expect((await resolve()).services).toHaveLength(1);
+
+ const groupMembership = await testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorGroupId: group.id })
+ .first();
+ await testDb("membership_roles")
+ .where({ membershipId: groupMembership.id })
+ .update({ isTemporary: true, temporaryAccessEndTime: new Date(Date.now() - 60_000) });
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+
+ expect((await resolve()).services).toHaveLength(0);
+ const lapsed = await mint();
+ expect(lapsed.statusCode).toBe(400);
+ expect(JSON.parse(lapsed.payload).message).toContain("is granted to you");
+ } finally {
+ await testKeyStore.deleteItemsByKeyIn(cacheKeys);
+ await deleteUaIdentity(agent.id);
+ await group.cleanup();
+ }
+ });
+
+ test("a creator grant is written only for a directly added admin", async () => {
+ const projectId = await getProjectId();
+
+ const direct = await createAccessBundle("creator-direct");
+ const directGrants = await grantRows(direct.id, { actorUserId: seedData1.id });
+ expect(directGrants).toHaveLength(1);
+ const roles = await testDb("membership_roles").where({ membershipId: directGrants[0].id });
+ expect(roles.map((r: { role: string }) => r.role)).toEqual(["consumer"]);
+
+ const group = await createProjectGroup(projectId, "av-group-admins", ProjectMembershipRole.Admin);
+ const admin = await createUaIdentity(`av-group-admin-${Date.now()}`);
+ await testDb("identity_group_membership").insert({ groupId: group.id, identityId: admin.id });
+
+ try {
+ const created = await admin.asIdentity("POST", "/api/v1/agent-vault/access-bundles", {
+ name: "creator-via-group"
+ });
+ expect(created.statusCode).toBe(200);
+ const { accessBundle } = JSON.parse(created.payload) as { accessBundle: { id: string; name: string } };
+
+ expect(await grantRows(accessBundle.id)).toHaveLength(0);
+
+ const list = await inject("GET", "/api/v1/agent-vault/access-bundles");
+ const { accessBundles } = JSON.parse(list.payload) as { accessBundles: { id: string; memberCount: number }[] };
+ expect(accessBundles.find((row) => row.id === accessBundle.id)?.memberCount).toBe(0);
+
+ const mint = await admin.asIdentity("POST", "/api/v1/agent-vault/sessions", {
+ accessBundles: [accessBundle.name],
+ ttl: "1h"
+ });
+ expect(mint.statusCode).toBe(200);
+ } finally {
+ await deleteUaIdentity(admin.id);
+ await group.cleanup();
+ }
+ });
+
+ test("deleting a bundle reaps its grants and their roles", async () => {
+ const bundle = await createAccessBundle("delete-reaps-grants");
+ const [grant] = await grantRows(bundle.id, { actorUserId: seedData1.id });
+ expect(grant).toBeDefined();
+
+ expect((await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).statusCode).toBe(200);
+
+ expect(await grantRows(bundle.id)).toHaveLength(0);
+ expect(await testDb("membership_roles").where({ membershipId: grant.id })).toHaveLength(0);
+ });
+
+ test("a member id from another scope is refused, and grants are not seats", async () => {
+ const projectId = await getProjectId();
+ const bundle = await createAccessBundle("scoped-member-ids");
+ const identity = await createOrgIdentity(`av-seats-${Date.now()}`);
+ expect(
+ (await inject("POST", `/api/v1/agent-vault/memberships/identities/${identity.id}`, { role: "member" }))
+ .statusCode
+ ).toBe(200);
+
+ const seatsBefore = await usageCounterDALFactory(testDb).countAgentVaultIdentities(seedData1.organization.id);
+
+ const projectMembership = await testDb("memberships")
+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorIdentityId: identity.id })
+ .first();
+ const refused = await inject(
+ "DELETE",
+ `/api/v1/agent-vault/access-bundles/${bundle.id}/members/${projectMembership.id}`
+ );
+ expect(refused.statusCode).toBe(404);
+ expect(await testDb("memberships").where({ id: projectMembership.id })).toHaveLength(1);
+
+ for (const name of ["seats-a", "seats-b", "seats-c"]) {
+ // eslint-disable-next-line no-await-in-loop
+ const extra = await createAccessBundle(name);
+ // eslint-disable-next-line no-await-in-loop
+ const granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${extra.id}/members`, {
+ identityIds: [identity.id]
+ });
+ expect(granted.statusCode).toBe(200);
+ }
+ const duplicate = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ identityIds: [identity.id]
+ });
+ expect(duplicate.statusCode).toBe(200);
+ const again = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {
+ identityIds: [identity.id]
+ });
+ expect(again.statusCode).toBe(200);
+ expect(JSON.parse(again.payload)).toMatchObject({ members: [], skipped: [identity.id] });
+
+ expect(await usageCounterDALFactory(testDb).countAgentVaultIdentities(seedData1.organization.id)).toBe(
+ seatsBefore
+ );
+
+ await deleteOrgIdentity(identity.id);
+ });
+
+ 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`, {
+ userIds: [user.id]
+ });
+ expect(grant.statusCode).toBe(200);
+
+ const remove = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/projects/${projectId}/memberships/${membership.id}`,
+ headers: authHeader
+ });
+ expect(remove.statusCode).toBe(200);
+
+ expect(await grantRows(bundle.id, { actorUserId: user.id }).first()).toBeUndefined();
+
+ await testDb("memberships").where({ actorUserId: user.id }).delete();
+ await testDb("users").where({ id: user.id }).delete();
+ });
+ });
+});
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 7934fe2554..288ff7f853 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -6,6 +6,11 @@ import { TUsers } from "@app/db/schemas";
import { TAccessApprovalPolicyServiceFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
import { TAccessApprovalRequestServiceFactory } from "@app/ee/services/access-approval-request/access-approval-request-types";
import { TAgentProxyCaServiceFactory } from "@app/ee/services/agent-proxy-ca/agent-proxy-ca-service";
+import { TAgentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";
+import { TAgentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";
+import { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";
+import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";
+import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";
import { TAssumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-types";
import { TAuditLogServiceFactory, TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";
import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";
@@ -278,6 +283,7 @@ declare module "fastify" {
auditLogInfo: Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor" | "orgId">;
internalCertManagerProjectId: string;
internalPamProjectId: string;
+ internalAgentVaultProjectId: string;
ssoConfig: Awaited<ReturnType<TSamlConfigServiceFactory["getSaml"]>>;
ldapConfig: Awaited<ReturnType<TLdapConfigServiceFactory["getLdapCfg"]>> & {
allowedFields?: TAllowedFields[];
@@ -361,6 +367,11 @@ declare module "fastify" {
pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;
certManagerProjectResolver: TCertManagerProjectResolverFactory;
pamProjectResolver: TPamProjectResolverFactory;
+ agentVaultProjectResolver: TAgentVaultProjectResolverFactory;
+ agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;
+ agentVaultProxy: TAgentVaultProxyServiceFactory;
+ agentVaultSession: TAgentVaultSessionServiceFactory;
+ agentVaultMembership: TAgentVaultMembershipServiceFactory;
certManagerInstance: TCertManagerInstanceServiceFactory;
certManagerExport: TCertManagerExportServiceFactory;
certificateAuthority: TCertificateAuthorityServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index a60822eeef..ae09541361 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -20,6 +20,21 @@ import {
TAdditionalPrivileges,
TAdditionalPrivilegesInsert,
TAdditionalPrivilegesUpdate,
+ TAgentVaultAccessBundles,
+ TAgentVaultAccessBundlesInsert,
+ TAgentVaultAccessBundlesUpdate,
+ TAgentVaultProxies,
+ TAgentVaultProxiesInsert,
+ TAgentVaultProxiesUpdate,
+ TAgentVaultServices,
+ TAgentVaultServicesInsert,
+ TAgentVaultServicesUpdate,
+ TAgentVaultSessionAccessBundles,
+ TAgentVaultSessionAccessBundlesInsert,
+ TAgentVaultSessionAccessBundlesUpdate,
+ TAgentVaultSessions,
+ TAgentVaultSessionsInsert,
+ TAgentVaultSessionsUpdate,
TAlertChannelMemberships,
TAlertChannelMembershipsInsert,
TAlertChannelMembershipsUpdate,
@@ -1760,6 +1775,31 @@ declare module "knex/types/tables" {
>;
[TableName.PamDomain]: KnexOriginal.CompositeTableType<TPamDomains, TPamDomainsInsert, TPamDomainsUpdate>;
[TableName.PamAccount]: KnexOriginal.CompositeTableType<TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate>;
+ [TableName.AgentVaultAccessBundle]: KnexOriginal.CompositeTableType<
+ TAgentVaultAccessBundles,
+ TAgentVaultAccessBundlesInsert,
+ TAgentVaultAccessBundlesUpdate
+ >;
+ [TableName.AgentVaultService]: KnexOriginal.CompositeTableType<
+ TAgentVaultServices,
+ TAgentVaultServicesInsert,
+ TAgentVaultServicesUpdate
+ >;
+ [TableName.AgentVaultSession]: KnexOriginal.CompositeTableType<
+ TAgentVaultSessions,
+ TAgentVaultSessionsInsert,
+ TAgentVaultSessionsUpdate
+ >;
+ [TableName.AgentVaultSessionAccessBundle]: KnexOriginal.CompositeTableType<
+ TAgentVaultSessionAccessBundles,
+ TAgentVaultSessionAccessBundlesInsert,
+ TAgentVaultSessionAccessBundlesUpdate
+ >;
+ [TableName.AgentVaultProxy]: KnexOriginal.CompositeTableType<
+ TAgentVaultProxies,
+ TAgentVaultProxiesInsert,
+ TAgentVaultProxiesUpdate
+ >;
[TableName.PamAccountPolicy]: KnexOriginal.CompositeTableType<
TPamAccountPolicies,
TPamAccountPoliciesInsert,
diff --git a/backend/src/db/migrations/20260907100804_agent-vault.ts b/backend/src/db/migrations/20260907100804_agent-vault.ts
new file mode 100644
index 0000000000..16c5d8990f
--- /dev/null
+++ b/backend/src/db/migrations/20260907100804_agent-vault.ts
@@ -0,0 +1,220 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.AgentVaultAccessBundle))) {
+ await knex.schema.createTable(TableName.AgentVaultAccessBundle, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.string("projectId", 36).notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+
+ t.string("name", 64).notNullable();
+ t.string("description", 256);
+ t.timestamps(true, true, true);
+
+ t.unique(["projectId", "name"]);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultAccessBundle);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AgentVaultService))) {
+ await knex.schema.createTable(TableName.AgentVaultService, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("accessBundleId").notNullable();
+ t.foreign("accessBundleId").references("id").inTable(TableName.AgentVaultAccessBundle).onDelete("CASCADE");
+
+ t.string("name", 64).notNullable();
+
+ t.string("hostPattern", 1024).notNullable();
+
+ t.string("credentialType", 32).notNullable();
+
+ t.jsonb("credentialConfig").notNullable();
+
+ // NULL exactly when credentialType is passthrough, enforced in the service rather than by a CHECK.
+ t.binary("encryptedCredential");
+
+ t.timestamps(true, true, true);
+
+ t.unique(["accessBundleId", "name"]);
+ });
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.AgentVaultService}" ADD CONSTRAINT "agent_vault_services_credential_type_check" CHECK ("credentialType" IN ('bearer', 'basic', 'passthrough'))`
+ );
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultService);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AgentVaultSession))) {
+ await knex.schema.createTable(TableName.AgentVaultSession, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.string("projectId", 36).notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+
+ t.uuid("userId");
+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("SET NULL");
+
+ t.uuid("identityId");
+ t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("SET NULL");
+
+ // Snapshotted so a deleted actor still names the session it held, the way pam_sessions does.
+ t.string("actorName", 255).notNullable();
+ t.string("actorEmail", 255);
+
+ t.string("tokenHash", 64).notNullable().unique();
+
+ t.timestamp("expiresAt", { useTz: true }); // NULL means never
+ t.timestamp("revokedAt", { useTz: true });
+
+ t.timestamps(true, true, true);
+
+ t.index(["projectId", "createdAt"]);
+ });
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.AgentVaultSession}" ADD CONSTRAINT "agent_vault_sessions_one_actor" CHECK (num_nonnulls("userId", "identityId") <= 1)`
+ );
+
+ await knex.raw(
+ `CREATE INDEX agent_vault_session_by_user ON "${TableName.AgentVaultSession}" ("userId") WHERE "userId" IS NOT NULL`
+ );
+ await knex.raw(
+ `CREATE INDEX agent_vault_session_by_identity ON "${TableName.AgentVaultSession}" ("identityId") WHERE "identityId" IS NOT NULL`
+ );
+
+ await knex.raw(
+ `CREATE INDEX agent_vault_session_expires_at ON "${TableName.AgentVaultSession}" ("expiresAt") WHERE "expiresAt" IS NOT NULL`
+ );
+ await knex.raw(
+ `CREATE INDEX agent_vault_session_revoked_at ON "${TableName.AgentVaultSession}" ("revokedAt") WHERE "revokedAt" IS NOT NULL`
+ );
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultSession);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AgentVaultSessionAccessBundle))) {
+ await knex.schema.createTable(TableName.AgentVaultSessionAccessBundle, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("sessionId").notNullable();
+ t.foreign("sessionId").references("id").inTable(TableName.AgentVaultSession).onDelete("CASCADE");
+ t.index("sessionId");
+
+ t.uuid("accessBundleId");
+ t.foreign("accessBundleId").references("id").inTable(TableName.AgentVaultAccessBundle).onDelete("SET NULL");
+ t.index("accessBundleId");
+
+ t.string("accessBundleName", 64).notNullable();
+
+ t.integer("position").notNullable();
+
+ t.timestamp("createdAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
+
+ t.unique(["sessionId", "position"]);
+ });
+
+ await knex.raw(
+ `CREATE UNIQUE INDEX agent_vault_session_bundle_unique ON "${TableName.AgentVaultSessionAccessBundle}" ("sessionId", "accessBundleId") WHERE "accessBundleId" IS NOT NULL`
+ );
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.AgentVaultSessionAccessBundle}" ADD CONSTRAINT "agent_vault_session_bundles_position_check" CHECK ("position" >= 0)`
+ );
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AgentVaultProxy))) {
+ await knex.schema.createTable(TableName.AgentVaultProxy, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.string("projectId", 36).notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+
+ t.string("name", 64).notNullable();
+
+ t.integer("tokenVersion").notNullable().defaultTo(0);
+
+ t.string("rootCaFingerprint", 102);
+ t.timestamp("rootCaExpiresAt", { useTz: true });
+
+ t.timestamp("heartbeat", { useTz: true });
+ // The poll interval the proxy was running when it last checked in. Health cannot be judged by
+ // pollInterval, which changes the moment an admin saves: the proxy only learns a new interval on
+ // its next poll, which is still scheduled at the old one. Gateways keep heartbeatTTL for this.
+ t.integer("heartbeatTTL");
+
+ t.string("trafficPolicy", 32).notNullable().defaultTo("any-host");
+ t.string("allowedHosts", 1024);
+ t.integer("pollInterval").notNullable().defaultTo(60);
+
+ t.timestamps(true, true, true);
+
+ t.unique(["projectId", "name"]);
+ });
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.AgentVaultProxy}" ADD CONSTRAINT "agent_vault_proxies_traffic_policy_check" CHECK ("trafficPolicy" IN ('any-host', 'bundle-hosts'))`
+ );
+ await knex.raw(
+ `ALTER TABLE "${TableName.AgentVaultProxy}" ADD CONSTRAINT "agent_vault_proxies_poll_interval_check" CHECK ("pollInterval" BETWEEN 10 AND 300)`
+ );
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultProxy);
+ }
+
+ if (await knex.schema.hasTable(TableName.ResourceAuthMethod)) {
+ const hasAgentVaultProxyId = await knex.schema.hasColumn(TableName.ResourceAuthMethod, "agentVaultProxyId");
+ if (!hasAgentVaultProxyId) {
+ await knex.schema.alterTable(TableName.ResourceAuthMethod, (t) => {
+ t.uuid("agentVaultProxyId").nullable();
+ t.foreign("agentVaultProxyId").references("id").inTable(TableName.AgentVaultProxy).onDelete("CASCADE");
+ });
+
+ await knex.schema.raw(`
+ CREATE UNIQUE INDEX one_method_per_agent_vault_proxy
+ ON ${TableName.ResourceAuthMethod} ("agentVaultProxyId")
+ WHERE "agentVaultProxyId" IS NOT NULL
+ `);
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.ResourceAuthMethod)) {
+ const hasAgentVaultProxyId = await knex.schema.hasColumn(TableName.ResourceAuthMethod, "agentVaultProxyId");
+ if (hasAgentVaultProxyId) {
+ // The column is the only handle on these rows, so they go before it does. Their enrollment tokens
+ // in resource_token_auths cascade with them.
+ await knex(TableName.ResourceAuthMethod).whereNotNull("agentVaultProxyId").delete();
+
+ await knex.schema.raw(`DROP INDEX IF EXISTS one_method_per_agent_vault_proxy`);
+ await knex.schema.alterTable(TableName.ResourceAuthMethod, (t) => {
+ t.dropColumn("agentVaultProxyId");
+ });
+ }
+ }
+
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultProxy);
+ await knex.schema.dropTableIfExists(TableName.AgentVaultProxy);
+
+ await knex.schema.dropTableIfExists(TableName.AgentVaultSessionAccessBundle);
+
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultSession);
+ await knex.schema.dropTableIfExists(TableName.AgentVaultSession);
+
+ await knex(TableName.Membership)
+ .where({ scope: "resource", scopeResourceType: "agent-vault-access-bundle" })
+ .delete();
+
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultService);
+ await knex.schema.dropTableIfExists(TableName.AgentVaultService);
+
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultAccessBundle);
+ await knex.schema.dropTableIfExists(TableName.AgentVaultAccessBundle);
+}
diff --git a/backend/src/db/schemas/agent-vault-access-bundles.ts b/backend/src/db/schemas/agent-vault-access-bundles.ts
new file mode 100644
index 0000000000..144c8dd37e
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-access-bundles.ts
@@ -0,0 +1,23 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultAccessBundlesSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultAccessBundles = z.infer<typeof AgentVaultAccessBundlesSchema>;
+export type TAgentVaultAccessBundlesInsert = Omit<z.input<typeof AgentVaultAccessBundlesSchema>, TImmutableDBKeys>;
+export type TAgentVaultAccessBundlesUpdate = Partial<
+ Omit<z.input<typeof AgentVaultAccessBundlesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/agent-vault-proxies.ts b/backend/src/db/schemas/agent-vault-proxies.ts
new file mode 100644
index 0000000000..66cfdcf526
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-proxies.ts
@@ -0,0 +1,28 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultProxiesSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ name: z.string(),
+ tokenVersion: z.number().default(0),
+ rootCaFingerprint: z.string().nullable().optional(),
+ rootCaExpiresAt: z.date().nullable().optional(),
+ heartbeat: z.date().nullable().optional(),
+ heartbeatTTL: z.number().nullable().optional(),
+ trafficPolicy: z.string().default("any-host"),
+ allowedHosts: z.string().nullable().optional(),
+ pollInterval: z.number().default(60),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultProxies = z.infer<typeof AgentVaultProxiesSchema>;
+export type TAgentVaultProxiesInsert = Omit<z.input<typeof AgentVaultProxiesSchema>, TImmutableDBKeys>;
+export type TAgentVaultProxiesUpdate = Partial<Omit<z.input<typeof AgentVaultProxiesSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/agent-vault-services.ts b/backend/src/db/schemas/agent-vault-services.ts
new file mode 100644
index 0000000000..84cdc220e4
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-services.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultServicesSchema = z.object({
+ id: z.string().uuid(),
+ accessBundleId: z.string().uuid(),
+ name: z.string(),
+ hostPattern: z.string(),
+ credentialType: z.string(),
+ credentialConfig: z.unknown(),
+ encryptedCredential: zodBuffer.nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultServices = z.infer<typeof AgentVaultServicesSchema>;
+export type TAgentVaultServicesInsert = Omit<z.input<typeof AgentVaultServicesSchema>, TImmutableDBKeys>;
+export type TAgentVaultServicesUpdate = Partial<Omit<z.input<typeof AgentVaultServicesSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/agent-vault-session-access-bundles.ts b/backend/src/db/schemas/agent-vault-session-access-bundles.ts
new file mode 100644
index 0000000000..d454c1ab5c
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-session-access-bundles.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultSessionAccessBundlesSchema = z.object({
+ id: z.string().uuid(),
+ sessionId: z.string().uuid(),
+ accessBundleId: z.string().uuid().nullable().optional(),
+ accessBundleName: z.string(),
+ position: z.number(),
+ createdAt: z.date()
+});
+
+export type TAgentVaultSessionAccessBundles = z.infer<typeof AgentVaultSessionAccessBundlesSchema>;
+export type TAgentVaultSessionAccessBundlesInsert = Omit<
+ z.input<typeof AgentVaultSessionAccessBundlesSchema>,
+ TImmutableDBKeys
+>;
+export type TAgentVaultSessionAccessBundlesUpdate = Partial<
+ Omit<z.input<typeof AgentVaultSessionAccessBundlesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/agent-vault-sessions.ts b/backend/src/db/schemas/agent-vault-sessions.ts
new file mode 100644
index 0000000000..9ebae2bb3f
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-sessions.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultSessionsSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ userId: z.string().uuid().nullable().optional(),
+ identityId: z.string().uuid().nullable().optional(),
+ actorName: z.string(),
+ actorEmail: z.string().nullable().optional(),
+ tokenHash: z.string(),
+ expiresAt: z.date().nullable().optional(),
+ revokedAt: z.date().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultSessions = z.infer<typeof AgentVaultSessionsSchema>;
+export type TAgentVaultSessionsInsert = Omit<z.input<typeof AgentVaultSessionsSchema>, TImmutableDBKeys>;
+export type TAgentVaultSessionsUpdate = Partial<Omit<z.input<typeof AgentVaultSessionsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 47c48df72b..fedb48bf30 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -4,6 +4,11 @@ export * from "./access-approval-policies-bypassers";
export * from "./access-approval-requests";
export * from "./access-approval-requests-reviewers";
export * from "./additional-privileges";
+export * from "./agent-vault-access-bundles";
+export * from "./agent-vault-proxies";
+export * from "./agent-vault-services";
+export * from "./agent-vault-session-access-bundles";
+export * from "./agent-vault-sessions";
export * from "./alert-channel-memberships";
export * from "./alert-channel-recipients";
export * from "./alert-channels";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 98ed4fde09..14a451ec95 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -270,6 +270,11 @@ export enum TableName {
PamResourceFavorite = "pam_resource_favorites",
PamDomain = "pam_domains",
PamAccountPolicy = "pam_account_policies",
+ AgentVaultAccessBundle = "agent_vault_access_bundles",
+ AgentVaultService = "agent_vault_services",
+ AgentVaultSession = "agent_vault_sessions",
+ AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",
+ AgentVaultProxy = "agent_vault_proxies",
VaultExternalMigrationConfig = "vault_external_migration_configs",
ExternalMigrationConfig = "external_migration_configs",
@@ -408,7 +413,8 @@ export enum ResourceType {
CertificateApplication = "certificate-application",
Signer = "pki-signer",
PamFolder = "pam-folder",
- PamAccount = "pam-account"
+ PamAccount = "pam-account",
+ AgentVaultAccessBundle = "agent-vault-access-bundle"
}
export enum SecretEncryptionAlgo {
@@ -459,15 +465,29 @@ export enum ProjectType {
CertificateManager = "cert-manager",
KMS = "kms",
SecretScanning = "secret-scanning",
- PAM = "pam"
+ PAM = "pam",
+ AgentVault = "agent-vault"
}
+// These products resolve every non-admin slug to their member rule set, so a viewer, no-access or
+// custom role would promise less access than it grants. Write paths reject those roles outright;
+// rows written before a product joined this list are not re-validated.
+const ADMIN_MEMBER_ONLY_PRODUCT_LABELS: Partial<Record<ProjectType, string>> = {
+ [ProjectType.CertificateManager]: "Certificate Manager",
+ [ProjectType.PAM]: "Privileged Access Manager",
+ [ProjectType.AgentVault]: "Agent Vault"
+};
+
+export const getAdminMemberOnlyProductLabel = (projectType?: string | null) =>
+ projectType ? ADMIN_MEMBER_ONLY_PRODUCT_LABELS[projectType as ProjectType] : undefined;
+
export enum ActionProjectType {
SecretManager = ProjectType.SecretManager,
CertificateManager = ProjectType.CertificateManager,
KMS = ProjectType.KMS,
SecretScanning = ProjectType.SecretScanning,
PAM = ProjectType.PAM,
+ AgentVault = ProjectType.AgentVault,
// project operations that happen on all types
Any = "any"
}
diff --git a/backend/src/db/schemas/resource-auth-methods.ts b/backend/src/db/schemas/resource-auth-methods.ts
index 8a66b21df2..22fb5b7881 100644
--- a/backend/src/db/schemas/resource-auth-methods.ts
+++ b/backend/src/db/schemas/resource-auth-methods.ts
@@ -14,7 +14,8 @@ export const ResourceAuthMethodsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
relayId: z.string().uuid().nullable().optional(),
- kmipServerId: z.string().uuid().nullable().optional()
+ kmipServerId: z.string().uuid().nullable().optional(),
+ agentVaultProxyId: z.string().uuid().nullable().optional()
});
export type TResourceAuthMethods = z.infer<typeof ResourceAuthMethodsSchema>;
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
new file mode 100644
index 0000000000..4409ac9a93
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
@@ -0,0 +1,585 @@
+import { FastifyRequest } from "fastify";
+import { z } from "zod";
+
+import { AgentVaultAccessBundlesSchema } from "@app/db/schemas";
+import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";
+import {
+ AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,
+ AGENT_VAULT_NO_CONTROL_CHARS_RE
+} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";
+import { AgentVaultCredentialType } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import {
+ AgentVaultCreatedMemberSchema,
+ AgentVaultCredentialInputSchema,
+ AgentVaultCredentialUpdateSchema,
+ AgentVaultHostPatternSchema,
+ AgentVaultMemberIdsSchema,
+ AgentVaultMemberSchema,
+ AgentVaultNameSchema,
+ AgentVaultRemovedMemberSchema,
+ AgentVaultServiceSchema
+} from "./agent-vault-schemas";
+
+const AccessBundleDescriptionSchema = z
+ .string()
+ .trim()
+ .max(256, "A description can be at most 256 characters")
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .describe(AGENT_VAULT.ACCESS_BUNDLE.description);
+
+const AccessBundleSchema = AgentVaultAccessBundlesSchema.pick({
+ id: true,
+ name: true,
+ description: true,
+ createdAt: true
+});
+
+const memberTypeOf = (member: { userId?: string | null; identityId?: string | null; groupId?: string | null }) => {
+ if (member.userId) return "user" as const;
+ if (member.identityId) return "identity" as const;
+ return "group" as const;
+};
+
+const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+});
+
+// A passthrough switch is a replacement: mergeCredential returns a null secret and updateService nulls
+// the sealed column. The old check only looked at bearer and basic, so it reported no replacement for the
+// one case that destroys the credential outright.
+const isStoredSecretReplaced = (credential?: z.infer<typeof AgentVaultCredentialUpdateSchema>) => {
+ if (!credential) return false;
+ if (credential.type === AgentVaultCredentialType.Bearer) return credential.value !== undefined;
+ if (credential.type === AgentVaultCredentialType.Basic) {
+ return credential.username !== undefined || credential.password !== undefined;
+ }
+ return true;
+};
+
+export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultAccessBundles",
+ description: "List the Agent Vault access bundles you can reach",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ response: {
+ 200: z.object({
+ accessBundles: AccessBundleSchema.extend({
+ serviceCount: z.number().describe(AGENT_VAULT.ACCESS_BUNDLE.serviceCount),
+ memberCount: z.number().describe(AGENT_VAULT.ACCESS_BUNDLE.memberCount),
+ hostPatterns: z.string().array().describe(AGENT_VAULT.ACCESS_BUNDLE.hostPatterns)
+ }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const accessBundles = await server.services.agentVaultAccessBundle.listAccessBundles({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req)
+ });
+ return { accessBundles };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "createAgentVaultAccessBundle",
+ description: "Create an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ body: z.object({
+ name: AgentVaultNameSchema.describe(AGENT_VAULT.ACCESS_BUNDLE.name),
+ description: AccessBundleDescriptionSchema.optional()
+ }),
+ response: { 200: z.object({ accessBundle: AccessBundleSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const accessBundle = await server.services.agentVaultAccessBundle.createAccessBundle({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_CREATE,
+ metadata: {
+ accessBundleId: accessBundle.id,
+ name: accessBundle.name,
+ description: accessBundle.description
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultAccessBundleCreated,
+ properties: { accessBundleId: accessBundle.id }
+ });
+
+ return { accessBundle };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:accessBundleId",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "getAgentVaultAccessBundle",
+ description: "Get an Agent Vault access bundle with its services",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ response: {
+ 200: z.object({
+ accessBundle: AccessBundleSchema.extend({
+ services: AgentVaultServiceSchema.array(),
+ members: AgentVaultMemberSchema.array().optional()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const accessBundle = await server.services.agentVaultAccessBundle.getAccessBundleById({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId
+ });
+ return { accessBundle };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:accessBundleId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAgentVaultAccessBundle",
+ description: "Update an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ body: z
+ .object({
+ name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.ACCESS_BUNDLE.name),
+ description: AccessBundleDescriptionSchema.nullable().optional()
+ })
+ .refine(
+ (body) => body.name !== undefined || body.description !== undefined,
+ "Provide at least one of 'name' or 'description' to update"
+ ),
+ response: { 200: z.object({ accessBundle: AccessBundleSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const accessBundle = await server.services.agentVaultAccessBundle.updateAccessBundle({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_UPDATE,
+ metadata: {
+ accessBundleId: accessBundle.id,
+ name: req.body.name,
+ description: req.body.description
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultAccessBundleUpdated,
+ properties: { accessBundleId: accessBundle.id }
+ });
+
+ return { accessBundle };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:accessBundleId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "deleteAgentVaultAccessBundle",
+ description: "Delete an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ response: { 200: z.object({ accessBundle: AccessBundleSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const accessBundle = await server.services.agentVaultAccessBundle.deleteAccessBundle({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_DELETE,
+ metadata: { accessBundleId: accessBundle.id, name: accessBundle.name }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultAccessBundleDeleted,
+ properties: { accessBundleId: accessBundle.id }
+ });
+
+ return { accessBundle };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:accessBundleId/services",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "createAgentVaultService",
+ description: "Add a service to an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ body: z.object({
+ name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),
+ hostPattern: AgentVaultHostPatternSchema,
+ credential: AgentVaultCredentialInputSchema
+ }),
+ response: {
+ 200: z.object({ service: AgentVaultServiceSchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { service } = await server.services.agentVaultAccessBundle.createService({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_SERVICE_CREATE,
+ metadata: {
+ accessBundleId: req.params.accessBundleId,
+ serviceId: service.id,
+ name: service.name,
+ hostPattern: service.hostPattern,
+ credentialType: service.credential.type,
+ headerName:
+ service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerName : undefined,
+ headerPrefix:
+ service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerPrefix : undefined
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultServiceCreated,
+ properties: {
+ accessBundleId: req.params.accessBundleId,
+ serviceId: service.id,
+ credentialType: service.credential.type,
+ hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length
+ }
+ });
+
+ return { service };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:accessBundleId/services/:serviceId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAgentVaultService",
+ description: "Update a service in an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId)
+ }),
+ body: z
+ .object({
+ name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.SERVICE.name),
+ hostPattern: AgentVaultHostPatternSchema.optional(),
+ credential: AgentVaultCredentialUpdateSchema.optional()
+ })
+ .refine(
+ (body) => body.name !== undefined || body.hostPattern !== undefined || body.credential !== undefined,
+ "Provide at least one of 'name', 'hostPattern' or 'credential' to update"
+ ),
+ response: {
+ 200: z.object({ service: AgentVaultServiceSchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { service } = await server.services.agentVaultAccessBundle.updateService({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ serviceId: req.params.serviceId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_SERVICE_UPDATE,
+ // Every field comes off the body, so an absent one means the PATCH did not touch it.
+ metadata: {
+ accessBundleId: req.params.accessBundleId,
+ serviceId: service.id,
+ name: req.body.name,
+ hostPattern: req.body.hostPattern,
+ credentialType: req.body.credential?.type,
+ headerName:
+ req.body.credential?.type === AgentVaultCredentialType.Bearer
+ ? req.body.credential.headerName
+ : undefined,
+ headerPrefix:
+ req.body.credential?.type === AgentVaultCredentialType.Bearer
+ ? req.body.credential.headerPrefix
+ : undefined,
+ credentialReplaced: isStoredSecretReplaced(req.body.credential)
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultServiceUpdated,
+ properties: {
+ accessBundleId: req.params.accessBundleId,
+ serviceId: service.id,
+ credentialType: service.credential.type,
+ hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length
+ }
+ });
+
+ return { service };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:accessBundleId/services/:serviceId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "deleteAgentVaultService",
+ description: "Delete a service from an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId)
+ }),
+ response: { 200: z.object({ service: AgentVaultServiceSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const service = await server.services.agentVaultAccessBundle.deleteService({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ serviceId: req.params.serviceId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_SERVICE_DELETE,
+ metadata: {
+ accessBundleId: req.params.accessBundleId,
+ serviceId: service.id,
+ name: service.name
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultServiceDeleted,
+ properties: { accessBundleId: req.params.accessBundleId, serviceId: service.id }
+ });
+
+ return { service };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:accessBundleId/members",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultAccessBundleMembers",
+ description: "List who can reach an Agent Vault access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ response: { 200: z.object({ members: AgentVaultMemberSchema.array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const members = await server.services.agentVaultAccessBundle.listMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId
+ });
+ return { members };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:accessBundleId/members",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "addAgentVaultAccessBundleMembers",
+ description: "Grant an Agent Vault access bundle to users, machine identities or groups",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ body: AgentVaultMemberIdsSchema,
+ response: {
+ 200: z.object({
+ members: AgentVaultCreatedMemberSchema.array(),
+ skipped: z.string().uuid().array().describe(AGENT_VAULT.MEMBER.skipped)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { members, skipped, accessBundleName } = await server.services.agentVaultAccessBundle.addMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ ...req.body
+ });
+
+ await Promise.all(
+ members.map((member) =>
+ server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD,
+ metadata: {
+ accessBundleId: req.params.accessBundleId,
+ accessBundleName,
+ memberId: member.id,
+ ...(member.userId && { userId: member.userId }),
+ ...(member.identityId && { identityId: member.identityId }),
+ ...(member.groupId && { groupId: member.groupId })
+ }
+ }
+ })
+ )
+ );
+
+ members.forEach((member) =>
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultAccessBundleMemberAdded,
+ properties: { accessBundleId: req.params.accessBundleId, memberType: memberTypeOf(member) }
+ })
+ );
+
+ return { members, skipped };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:accessBundleId/members/:memberId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "removeAgentVaultAccessBundleMember",
+ description: "Revoke an Agent Vault access bundle from a user, machine identity or group",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ memberId: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId)
+ }),
+ response: { 200: z.object({ member: AgentVaultRemovedMemberSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const member = await server.services.agentVaultAccessBundle.removeMember({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ memberId: req.params.memberId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,
+ metadata: {
+ accessBundleId: req.params.accessBundleId,
+ accessBundleName: member.accessBundleName,
+ memberId: member.id
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultAccessBundleMemberRemoved,
+ properties: { accessBundleId: req.params.accessBundleId, memberType: memberTypeOf(member) }
+ });
+
+ return { member };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts
new file mode 100644
index 0000000000..aacac91ac3
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts
@@ -0,0 +1,512 @@
+import { FastifyRequest } from "fastify";
+import { z } from "zod";
+
+import { ProjectMembershipRole } from "@app/db/schemas";
+import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+});
+
+const ProductRoleSchema = z
+ .enum([ProjectMembershipRole.Admin, ProjectMembershipRole.Member])
+ .describe(AGENT_VAULT.MEMBERSHIP.role);
+
+const MemberSchema = z.object({
+ membershipId: z.string().uuid(),
+ userId: z.string().uuid().nullable(),
+ groupId: z.string().uuid().nullable(),
+ identityId: z.string().uuid().nullable(),
+ role: z.string().describe(AGENT_VAULT.MEMBERSHIP.role),
+ isActive: z.boolean(),
+ createdAt: z.date()
+});
+
+// Mirrors PAM's MemberResultSchema so every membership write reports the row it touched.
+const MemberResultSchema = z.object({
+ membershipId: z.string().uuid(),
+ userId: z.string().uuid().optional().describe(AGENT_VAULT.MEMBER.userId),
+ identityId: z.string().uuid().optional().describe(AGENT_VAULT.MEMBER.identityId),
+ groupId: z.string().uuid().optional().describe(AGENT_VAULT.MEMBER.groupId),
+ role: z.string().describe(AGENT_VAULT.MEMBERSHIP.role),
+ createdAt: z.date()
+});
+
+export const registerAgentVaultMembershipRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/users",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultProductUserMembers",
+ description: "List the users that are members of Agent Vault",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ response: {
+ 200: z.object({
+ members: MemberSchema.extend({
+ email: z.string().nullable(),
+ username: z.string(),
+ firstName: z.string().nullable(),
+ lastName: z.string().nullable(),
+ isOrgMembershipPending: z.boolean()
+ }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => ({
+ members: await server.services.agentVaultMembership.listProductUserMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req)
+ })
+ })
+ });
+ server.route({
+ method: "GET",
+ url: "/groups",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultProductGroupMembers",
+ description: "List the groups that are members of Agent Vault",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ response: { 200: z.object({ members: MemberSchema.extend({ name: z.string() }).array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => ({
+ members: await server.services.agentVaultMembership.listProductGroupMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req)
+ })
+ })
+ });
+ server.route({
+ method: "GET",
+ url: "/identities",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultProductIdentityMembers",
+ description: "List the machine identities that are members of Agent Vault",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ response: {
+ 200: z.object({
+ members: MemberSchema.extend({
+ name: z.string(),
+ identityProjectId: z.string().nullable(),
+ identityOrgId: z.string().nullable()
+ }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => ({
+ members: await server.services.agentVaultMembership.listProductIdentityMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req)
+ })
+ })
+ });
+ server.route({
+ method: "POST",
+ url: "/users",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "addAgentVaultProductUserMembers",
+ description: "Give one or more users access to Agent Vault, by id or by email",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ body: z
+ .object({
+ userIds: z.string().uuid().array().max(100).default([]),
+ // Usernames are stored lowercase and the lookup is an exact match, so a mixed-case address
+ // would come back as "not a member" rather than resolving.
+ emails: z
+ .string()
+ .email()
+ .array()
+ .max(100)
+ .default([])
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),
+ role: ProductRoleSchema
+ })
+ .refine((val) => val.userIds.length + val.emails.length > 0, {
+ message: "Provide at least one userId or email."
+ }),
+ response: { 200: z.object({ members: MemberResultSchema.array(), skipped: z.string().array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { memberships, skipped } = await server.services.agentVaultMembership.addProductUserMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ...req.body,
+ ctx: actorContext(req)
+ });
+
+ await Promise.all(
+ memberships.map((membership) =>
+ server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_ADD,
+ metadata: { userId: membership.userId, userName: membership.userName, role: membership.role }
+ }
+ })
+ )
+ );
+
+ memberships.forEach((membership) =>
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberAdded,
+ properties: { memberType: "user", role: membership.role }
+ })
+ );
+
+ return { members: memberships, skipped };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/users/:userId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAgentVaultProductUserMemberRole",
+ description: "Change a user's Agent Vault role",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ userId: z.string().uuid().describe(AGENT_VAULT.MEMBER.userId) }),
+ body: z.object({ role: ProductRoleSchema }),
+ response: { 200: MemberResultSchema.omit({ createdAt: true }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const member = await server.services.agentVaultMembership.updateProductMemberRole({
+ projectId: req.internalAgentVaultProjectId,
+ userId: req.params.userId,
+ role: req.body.role,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_UPDATE,
+ metadata: {
+ userId: req.params.userId,
+ userName: member.userName,
+ role: req.body.role
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberUpdated,
+ properties: { memberType: "user", role: req.body.role }
+ });
+
+ return member;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/users/:userId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "removeAgentVaultProductUserMember",
+ description: "Remove a user from Agent Vault, and with it every bundle they hold",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ userId: z.string().uuid().describe(AGENT_VAULT.MEMBER.userId) }),
+ response: { 200: MemberResultSchema.pick({ membershipId: true, userId: true }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const removed = await server.services.agentVaultMembership.removeProductMember({
+ projectId: req.internalAgentVaultProjectId,
+ userId: req.params.userId,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_REMOVE,
+ metadata: { userId: req.params.userId, userName: removed.userName }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberRemoved,
+ properties: { memberType: "user" }
+ });
+
+ return { membershipId: removed.membershipId, userId: req.params.userId };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/groups/:groupId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "addAgentVaultProductGroupMember",
+ description: "Give a group access to Agent Vault",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ groupId: z.string().uuid().describe(AGENT_VAULT.MEMBER.groupId) }),
+ body: z.object({ role: ProductRoleSchema }),
+ response: { 200: MemberResultSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const member = await server.services.agentVaultMembership.addProductMember({
+ projectId: req.internalAgentVaultProjectId,
+ groupId: req.params.groupId,
+ role: req.body.role,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_ADD,
+ metadata: {
+ groupId: req.params.groupId,
+ groupName: member.groupName,
+ role: req.body.role
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberAdded,
+ properties: { memberType: "group", role: req.body.role }
+ });
+
+ return member;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/groups/:groupId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAgentVaultProductGroupMemberRole",
+ description: "Change a group's Agent Vault role",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ groupId: z.string().uuid().describe(AGENT_VAULT.MEMBER.groupId) }),
+ body: z.object({ role: ProductRoleSchema }),
+ response: { 200: MemberResultSchema.omit({ createdAt: true }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const member = await server.services.agentVaultMembership.updateProductMemberRole({
+ projectId: req.internalAgentVaultProjectId,
+ groupId: req.params.groupId,
+ role: req.body.role,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_UPDATE,
+ metadata: {
+ groupId: req.params.groupId,
+ groupName: member.groupName,
+ role: req.body.role
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberUpdated,
+ properties: { memberType: "group", role: req.body.role }
+ });
+
+ return member;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/groups/:groupId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "removeAgentVaultProductGroupMember",
+ description: "Remove a group from Agent Vault, and with it every bundle they hold",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ groupId: z.string().uuid().describe(AGENT_VAULT.MEMBER.groupId) }),
+ response: { 200: MemberResultSchema.pick({ membershipId: true, groupId: true }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const removed = await server.services.agentVaultMembership.removeProductMember({
+ projectId: req.internalAgentVaultProjectId,
+ groupId: req.params.groupId,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_REMOVE,
+ metadata: { groupId: req.params.groupId, groupName: removed.groupName }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberRemoved,
+ properties: { memberType: "group" }
+ });
+
+ return { membershipId: removed.membershipId, groupId: req.params.groupId };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/identities/:identityId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "addAgentVaultProductIdentityMember",
+ description: "Give a machine identity access to Agent Vault",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ identityId: z.string().uuid().describe(AGENT_VAULT.MEMBER.identityId) }),
+ body: z.object({ role: ProductRoleSchema }),
+ response: { 200: MemberResultSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const member = await server.services.agentVaultMembership.addProductMember({
+ projectId: req.internalAgentVaultProjectId,
+ identityId: req.params.identityId,
+ role: req.body.role,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_ADD,
+ metadata: {
+ identityId: req.params.identityId,
+ identityName: member.identityName,
+ role: req.body.role
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberAdded,
+ properties: { memberType: "identity", role: req.body.role }
+ });
+
+ return member;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/identities/:identityId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAgentVaultProductIdentityMemberRole",
+ description: "Change a machine identity's Agent Vault role",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ identityId: z.string().uuid().describe(AGENT_VAULT.MEMBER.identityId) }),
+ body: z.object({ role: ProductRoleSchema }),
+ response: { 200: MemberResultSchema.omit({ createdAt: true }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const member = await server.services.agentVaultMembership.updateProductMemberRole({
+ projectId: req.internalAgentVaultProjectId,
+ identityId: req.params.identityId,
+ role: req.body.role,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_UPDATE,
+ metadata: {
+ identityId: req.params.identityId,
+ identityName: member.identityName,
+ role: req.body.role
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberUpdated,
+ properties: { memberType: "identity", role: req.body.role }
+ });
+
+ return member;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/identities/:identityId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "removeAgentVaultProductIdentityMember",
+ description: "Remove a machine identity from Agent Vault, and with it every bundle they hold",
+ tags: [ApiDocsTags.AgentVaultMemberships],
+ params: z.object({ identityId: z.string().uuid().describe(AGENT_VAULT.MEMBER.identityId) }),
+ response: { 200: MemberResultSchema.pick({ membershipId: true, identityId: true }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const removed = await server.services.agentVaultMembership.removeProductMember({
+ projectId: req.internalAgentVaultProjectId,
+ identityId: req.params.identityId,
+ ctx: actorContext(req)
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_REMOVE,
+ metadata: { identityId: req.params.identityId, identityName: removed.identityName }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberRemoved,
+ properties: { memberType: "identity" }
+ });
+
+ return { membershipId: removed.membershipId, identityId: req.params.identityId };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-project-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-project-router.ts
new file mode 100644
index 0000000000..29ceb3cd31
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-project-router.ts
@@ -0,0 +1,25 @@
+import z from "zod";
+
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerAgentVaultProjectRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ schema: {
+ hide: true,
+ operationId: "getAgentVaultProject",
+ description: "Resolve the organization's Agent Vault project, creating it on first access",
+ tags: [ApiDocsTags.AgentVault],
+ response: { 200: z.object({ projectId: z.string() }) }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ // A deliberate REST deviation: injectAgentVaultProjectId is a preValidation hook, so this GET
+ // bootstraps the project on first access.
+ handler: async (req) => ({ projectId: req.internalAgentVaultProjectId })
+ });
+};
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts
new file mode 100644
index 0000000000..341dd8c1da
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts
@@ -0,0 +1,172 @@
+import { z } from "zod";
+
+import { AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { AGENT_VAULT_SESSION_TOKEN_PREFIX } from "@app/ee/services/agent-vault-session/agent-vault-session-fns";
+import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
+import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { logger } from "@app/lib/logger";
+import { agentVaultHeartbeatLimit, agentVaultResolveLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const ProxyConfigSchema = z.object({
+ trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),
+ allowedHosts: z.string().nullable().describe(AGENT_VAULT.PROXY.allowedHosts),
+ pollInterval: z.number().describe(AGENT_VAULT.PROXY.pollInterval)
+});
+
+const SESSION_HEADER = "x-infisical-agent-session";
+
+export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/login",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "loginAgentVaultProxy",
+ description:
+ "Proxy login. Body discriminates on `method`; token exchanges a one-time enrollment token for the proxy's access token.",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ body: z.discriminatedUnion("method", [
+ z.object({
+ method: z.literal(ResourceAuthMethodType.Token),
+ token: z.string().trim().min(1).max(256).describe(AGENT_VAULT.PROXY.enrollmentToken),
+ rootCaCertificate: z.string().trim().min(1).max(16384).describe(AGENT_VAULT.PROXY.rootCaCertificate)
+ })
+ ]),
+ response: {
+ 200: z.object({
+ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId),
+ name: z.string().describe(AGENT_VAULT.PROXY.name),
+ accessToken: z.string(),
+ config: ProxyConfigSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const result = await server.services.agentVaultProxy.enroll({
+ enrollmentToken: req.body.token,
+ rootCaCertificate: req.body.rootCaCertificate
+ });
+
+ // The enrollment token is already consumed and this response is the only copy of the access token,
+ // so an audit failure must not fail the request.
+ try {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ actor: { type: ActorType.AGENT_VAULT_PROXY, metadata: { agentVaultProxyId: result.proxyId } },
+ orgId: result.orgId,
+ projectId: result.projectId,
+ event: {
+ type: EventType.AGENT_VAULT_PROXY_ENROLL,
+ metadata: {
+ proxyId: result.proxyId,
+ name: result.name,
+ rootCaFingerprint: result.rootCaFingerprint,
+ replacedExistingCa: result.replacedExistingCa
+ }
+ }
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `agentVaultProxyEnroll: failed to write the enrollment audit log [proxyId=${result.proxyId}]`
+ );
+ }
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.AgentVaultProxyEnrolled,
+ distinctId: `agent-vault-proxy-${result.proxyId}`,
+ organizationId: result.orgId,
+ anonymous: true,
+ properties: {
+ orgId: result.orgId,
+ channel: req.auditLogInfo.userAgentType ?? UserAgentType.OTHER,
+ proxyId: result.proxyId,
+ replacedExistingCa: result.replacedExistingCa
+ }
+ })
+ .catch(() => {});
+
+ return {
+ proxyId: result.proxyId,
+ name: result.name,
+ accessToken: result.accessToken,
+ config: result.config
+ };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/heartbeat",
+ config: { rateLimit: agentVaultHeartbeatLimit },
+ schema: {
+ operationId: "agentVaultProxyHeartbeat",
+ description: "Report a proxy as alive and read back its settings",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ response: { 200: z.object({ config: ProxyConfigSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),
+ handler: async (req) => server.services.agentVaultProxy.heartbeat({ proxyId: req.permission.id })
+ });
+
+ server.route({
+ method: "POST",
+ url: "/resolve",
+ config: { rateLimit: agentVaultResolveLimit },
+ schema: {
+ operationId: "resolveAgentVaultSession",
+ description: "Resolve a session into the services and credentials the proxy should attach",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ headers: z
+ .object({
+ [SESSION_HEADER]: z
+ .string()
+ .trim()
+ .min(1)
+ .max(128)
+ .startsWith(AGENT_VAULT_SESSION_TOKEN_PREFIX)
+ .describe(AGENT_VAULT.PROXY.sessionToken)
+ })
+ .passthrough(),
+ response: {
+ 200: z.object({
+ sessionId: z.string().uuid(),
+ expiresAt: z.date().nullable(),
+ services: z
+ .object({
+ id: z.string().uuid(),
+ name: z.string(),
+ accessBundleName: z.string(),
+ hostPattern: z.string(),
+ credential: z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("bearer"),
+ headerName: z.string(),
+ headerPrefix: z.string(),
+ value: z.string()
+ }),
+ z.object({ type: z.literal("basic"), username: z.string(), password: z.string() }),
+ z.object({ type: z.literal("passthrough") })
+ ])
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ // Deliberately unaudited: one row per poll per session is ~144k a day for a hundred sessions.
+ return server.services.agentVaultProxy.resolveSession({
+ proxyId: req.permission.id,
+ orgId: req.permission.orgId,
+ sessionToken: req.headers[SESSION_HEADER]
+ });
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts
new file mode 100644
index 0000000000..3e1419d70b
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts
@@ -0,0 +1,291 @@
+import { FastifyRequest } from "fastify";
+import { z } from "zod";
+
+import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";
+import { AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { buildHostPatternSchema, parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+});
+
+const ProxyMemberViewSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId),
+ name: z.string().describe(AGENT_VAULT.PROXY.name),
+ heartbeat: z.date().nullable().describe(AGENT_VAULT.PROXY.heartbeat),
+ isHealthy: z.boolean().describe(AGENT_VAULT.PROXY.isHealthy),
+ rootCaFingerprint: z.string().nullable().describe(AGENT_VAULT.PROXY.rootCaFingerprint),
+ rootCaExpiresAt: z.date().nullable().describe(AGENT_VAULT.PROXY.rootCaExpiresAt)
+});
+
+const ProxyAdminViewSchema = ProxyMemberViewSchema.extend({
+ trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),
+ allowedHosts: z.string().nullable().describe(AGENT_VAULT.PROXY.allowedHosts),
+ pollInterval: z.number().describe(AGENT_VAULT.PROXY.pollInterval),
+ createdAt: z.date()
+});
+
+const EnrollmentSchema = z.object({
+ token: z.string().describe(AGENT_VAULT.PROXY.enrollmentToken),
+ expiresAt: z.date()
+});
+
+const ProxySettingsSchema = {
+ trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),
+ allowedHosts: buildHostPatternSchema("host exception").nullable().describe(AGENT_VAULT.PROXY.allowedHosts),
+ pollInterval: z.number().int().min(10).max(300).describe(AGENT_VAULT.PROXY.pollInterval)
+};
+
+export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultProxies",
+ description: "List the organization's Agent Vault proxies",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ response: { 200: z.object({ proxies: z.union([ProxyAdminViewSchema, ProxyMemberViewSchema]).array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const proxies = await server.services.agentVaultProxy.listProxies({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req)
+ });
+ return { proxies };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "createAgentVaultProxy",
+ description: "Register an Agent Vault proxy and issue its one-time enrollment token",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ body: z.object({
+ name: slugSchema({ max: 64, field: "Name" }).describe(AGENT_VAULT.PROXY.name),
+ trafficPolicy: ProxySettingsSchema.trafficPolicy.optional(),
+ allowedHosts: ProxySettingsSchema.allowedHosts.optional(),
+ pollInterval: ProxySettingsSchema.pollInterval.optional()
+ }),
+ response: { 200: z.object({ proxy: ProxyAdminViewSchema, ...EnrollmentSchema.shape }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { proxy, enrollment } = await server.services.agentVaultProxy.createProxy({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_PROXY_REGISTER,
+ metadata: { proxyId: proxy.id, name: proxy.name }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProxyRegistered,
+ properties: {
+ proxyId: proxy.id,
+ trafficPolicy: proxy.trafficPolicy,
+ allowedHostCount: proxy.allowedHosts
+ ? parseHostPatterns(proxy.allowedHosts, "host exception").patterns.length
+ : 0
+ }
+ });
+
+ return { proxy, ...enrollment };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:proxyId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAgentVaultProxy",
+ description: "Update an Agent Vault proxy's name or settings",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ params: z.object({ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId) }),
+ body: z
+ .object({
+ name: slugSchema({ max: 64, field: "Name" }).optional().describe(AGENT_VAULT.PROXY.name),
+ trafficPolicy: ProxySettingsSchema.trafficPolicy.optional(),
+ allowedHosts: ProxySettingsSchema.allowedHosts.optional(),
+ pollInterval: ProxySettingsSchema.pollInterval.optional()
+ })
+ .refine(
+ (body) =>
+ body.name !== undefined ||
+ body.trafficPolicy !== undefined ||
+ body.allowedHosts !== undefined ||
+ body.pollInterval !== undefined,
+ "Provide at least one setting to update"
+ ),
+ response: { 200: z.object({ proxy: ProxyAdminViewSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const proxy = await server.services.agentVaultProxy.updateProxy({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ proxyId: req.params.proxyId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_PROXY_UPDATE,
+ metadata: { proxyId: proxy.id, ...req.body }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProxyUpdated,
+ properties: {
+ proxyId: proxy.id,
+ trafficPolicy: proxy.trafficPolicy,
+ allowedHostCount: proxy.allowedHosts
+ ? parseHostPatterns(proxy.allowedHosts, "host exception").patterns.length
+ : 0
+ }
+ });
+
+ return { proxy };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:proxyId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "deleteAgentVaultProxy",
+ description: "Delete an Agent Vault proxy",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ params: z.object({ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId) }),
+ response: { 200: z.object({ proxy: z.object({ id: z.string().uuid(), name: z.string() }) }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const proxy = await server.services.agentVaultProxy.deleteProxy({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ proxyId: req.params.proxyId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: { type: EventType.AGENT_VAULT_PROXY_DELETE, metadata: { proxyId: proxy.id, name: proxy.name } }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProxyDeleted,
+ properties: { proxyId: proxy.id }
+ });
+
+ return { proxy };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:proxyId/token-auth/generate-enrollment-token",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "reissueAgentVaultProxyEnrollmentToken",
+ description: "Issue a replacement enrollment token for an Agent Vault proxy",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ params: z.object({ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId) }),
+ response: { 200: EnrollmentSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { proxy, enrollment } = await server.services.agentVaultProxy.reissueEnrollmentToken({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ proxyId: req.params.proxyId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE,
+ metadata: { proxyId: proxy.id, name: proxy.name }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProxyEnrollmentTokenReissued,
+ properties: { proxyId: proxy.id }
+ });
+
+ return enrollment;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:proxyId/revoke",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "revokeAgentVaultProxyAccess",
+ description: "Revoke an Agent Vault proxy's access token",
+ tags: [ApiDocsTags.AgentVaultProxies],
+ params: z.object({ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId) }),
+ response: { 200: z.object({ proxy: ProxyAdminViewSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const proxy = await server.services.agentVaultProxy.revokeProxyAccess({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ proxyId: req.params.proxyId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_PROXY_REVOKE,
+ metadata: { proxyId: proxy.id, name: proxy.name }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProxyAccessRevoked,
+ properties: { proxyId: proxy.id }
+ });
+
+ return { proxy };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
new file mode 100644
index 0000000000..bfdc904867
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
@@ -0,0 +1,189 @@
+import { z } from "zod";
+
+import {
+ AGENT_VAULT_HEADER_NAME_MESSAGE,
+ AGENT_VAULT_HEADER_NAME_RE,
+ AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,
+ AGENT_VAULT_NO_CONTROL_CHARS_RE
+} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";
+import { AgentVaultCredentialType } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern";
+import { AGENT_VAULT_MAX_GRANTEES } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { slugSchema } from "@app/server/lib/schemas";
+
+export const AgentVaultNameSchema = slugSchema({ max: 64, field: "Name" });
+
+export const AgentVaultHostPatternSchema = hostPatternSchema.describe(AGENT_VAULT.SERVICE.hostPattern);
+
+const basicHalvesAreNotBothEmpty = (
+ data: { type: AgentVaultCredentialType; username?: string; password?: string },
+ ctx: z.RefinementCtx
+) => {
+ // Either half may be blank, but not both. The check cannot be an object-level refine, because
+ // discriminatedUnion options must be plain objects.
+ if (data.type !== AgentVaultCredentialType.Basic) return;
+ if (data.username === undefined || data.password === undefined) return;
+ if (data.username.length > 0 || data.password.length > 0) return;
+
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["username"],
+ message: "A basic credential needs a username, a password, or both"
+ });
+};
+
+export const AgentVaultCredentialInputSchema = z
+ .discriminatedUnion("type", [
+ z.object({
+ type: z.literal(AgentVaultCredentialType.Bearer),
+ headerName: z
+ .string()
+ .trim()
+ .min(1)
+ .max(128)
+ .regex(AGENT_VAULT_HEADER_NAME_RE, AGENT_VAULT_HEADER_NAME_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.headerName),
+ headerPrefix: z
+ .string()
+ .trim()
+ .max(64)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.headerPrefix),
+ value: z
+ .string()
+ .min(1)
+ .max(8192)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .describe(AGENT_VAULT.SERVICE.value)
+ }),
+ z.object({
+ type: z.literal(AgentVaultCredentialType.Basic),
+ username: z.string().trim().max(256).describe(AGENT_VAULT.SERVICE.username),
+ password: z
+ .string()
+ .max(8192)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .describe(AGENT_VAULT.SERVICE.password)
+ }),
+ z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
+ ])
+ .superRefine(basicHalvesAreNotBothEmpty);
+
+// Not derived from the create schema: its `.default()`s would turn an omitted field into a reset on a PATCH.
+export const AgentVaultCredentialUpdateSchema = z
+ .discriminatedUnion("type", [
+ z.object({
+ type: z.literal(AgentVaultCredentialType.Bearer),
+ headerName: z
+ .string()
+ .trim()
+ .min(1)
+ .max(128)
+ .regex(AGENT_VAULT_HEADER_NAME_RE, AGENT_VAULT_HEADER_NAME_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.headerName),
+ headerPrefix: z
+ .string()
+ .trim()
+ .max(64)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.headerPrefix),
+ value: z
+ .string()
+ .min(1)
+ .max(8192)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.updateValue)
+ }),
+ z.object({
+ type: z.literal(AgentVaultCredentialType.Basic),
+ username: z.string().trim().max(256).optional().describe(AGENT_VAULT.SERVICE.updateUsername),
+ password: z
+ .string()
+ .max(8192)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.updatePassword)
+ }),
+ z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
+ ])
+ .superRefine(basicHalvesAreNotBothEmpty);
+
+export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal(AgentVaultCredentialType.Bearer),
+ headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),
+ headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix)
+ }),
+ z.object({ type: z.literal(AgentVaultCredentialType.Basic) }),
+ z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
+]);
+
+export const AgentVaultServiceSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId),
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ name: z.string().describe(AGENT_VAULT.SERVICE.name),
+ hostPattern: z.string().describe(AGENT_VAULT.SERVICE.hostPattern),
+ credential: AgentVaultCredentialSummarySchema,
+ createdAt: z.date().describe(AGENT_VAULT.SERVICE.createdAt)
+});
+
+// One list per actor type rather than a list of one-of-three objects: the field name carries the type,
+// so nothing has to be validated after parsing, and the grant stays a single atomic request.
+export const AgentVaultMemberIdsSchema = z
+ .object({
+ userIds: z.string().uuid().array().default([]).describe(AGENT_VAULT.MEMBER.userIds),
+ identityIds: z.string().uuid().array().default([]).describe(AGENT_VAULT.MEMBER.identityIds),
+ groupIds: z.string().uuid().array().default([]).describe(AGENT_VAULT.MEMBER.groupIds)
+ })
+ .refine(
+ (body) => body.userIds.length + body.identityIds.length + body.groupIds.length > 0,
+ "Name at least one user, machine identity or group"
+ )
+ .refine(
+ (body) => body.userIds.length + body.identityIds.length + body.groupIds.length <= AGENT_VAULT_MAX_GRANTEES,
+ `Grant an access bundle to at most ${AGENT_VAULT_MAX_GRANTEES} users, machine identities and groups at a time`
+ );
+
+// A removed grant is gone, so this reports the row's own columns rather than joining the actor's name,
+// the way every other membership delete on the platform does.
+export const AgentVaultRemovedMemberSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ userId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.userId),
+ identityId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.identityId),
+ groupId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.groupId),
+ createdAt: z.date()
+});
+
+export const AgentVaultMemberSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),
+ userId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.userId),
+ identityId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.identityId),
+ groupId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.groupId),
+ createdAt: z.date(),
+ user: z
+ .object({
+ username: z.string(),
+ email: z.string().nullable(),
+ firstName: z.string().nullable(),
+ lastName: z.string().nullable()
+ })
+ .nullable(),
+ identity: z.object({ name: z.string() }).nullable(),
+ group: z.object({ name: z.string() }).nullable()
+});
+
+export const AgentVaultCreatedMemberSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ userId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.userId),
+ identityId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.identityId),
+ groupId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.groupId),
+ createdAt: z.date()
+});
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts
new file mode 100644
index 0000000000..e5fc32d93f
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts
@@ -0,0 +1,243 @@
+import { z } from "zod";
+
+import {
+ AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,
+ AGENT_VAULT_NO_CONTROL_CHARS_RE
+} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";
+import { AgentVaultSessionScope, AgentVaultSessionStatus } from "@app/ee/services/agent-vault/agent-vault-enums";
+import {
+ AGENT_VAULT_MAX_SESSION_BUNDLES,
+ AGENT_VAULT_SESSION_DEFAULT_TTL,
+ AGENT_VAULT_SESSION_MAX_TTL_MS,
+ AGENT_VAULT_SESSION_TTL_NEVER
+} from "@app/ee/services/agent-vault-session/agent-vault-session-service";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { ms } from "@app/lib/ms";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";
+import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const SessionAccessBundleSchema = z.object({
+ id: z.string().uuid().nullable(),
+ name: z.string(),
+ position: z.number()
+});
+
+const SessionSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),
+ userId: z.string().uuid().nullable(),
+ identityId: z.string().uuid().nullable(),
+ actorName: z.string(),
+ actorEmail: z.string().nullable(),
+ status: z.nativeEnum(AgentVaultSessionStatus),
+ expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),
+ revokedAt: z.date().nullable(),
+ createdAt: z.date()
+});
+
+export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAgentVaultSessions",
+ description: "List Agent Vault sessions",
+ tags: [ApiDocsTags.AgentVaultSessions],
+ querystring: z.object({
+ scope: z
+ .nativeEnum(AgentVaultSessionScope)
+ .default(AgentVaultSessionScope.Mine)
+ .describe(AGENT_VAULT.SESSION.scope),
+ status: z.nativeEnum(AgentVaultSessionStatus).optional().describe(AGENT_VAULT.SESSION.status),
+ search: z
+ .string()
+ .trim()
+ .max(255)
+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ .optional()
+ .describe(AGENT_VAULT.SESSION.search),
+ limit: z.coerce.number().int().min(1).max(100).default(20).describe(AGENT_VAULT.SESSION.limit),
+ offset: z.coerce.number().int().min(0).max(10000).default(0).describe(AGENT_VAULT.SESSION.offset)
+ }),
+ response: {
+ 200: z.object({
+ sessions: SessionSchema.extend({ accessBundles: SessionAccessBundleSchema.array() }).array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) =>
+ server.services.agentVaultSession.listSessions({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: {
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ },
+ ...req.query
+ })
+ });
+
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "createAgentVaultSession",
+ description: "Mint an Agent Vault session over an access bundle you can reach",
+ tags: [ApiDocsTags.AgentVaultSessions],
+ body: z.object({
+ accessBundles: slugSchema({ max: 64, field: "Access bundle" })
+ .array()
+ .min(1)
+ .max(AGENT_VAULT_MAX_SESSION_BUNDLES)
+ .describe(AGENT_VAULT.SESSION.accessBundles),
+ ttl: z
+ .string()
+ .trim()
+ .default(AGENT_VAULT_SESSION_DEFAULT_TTL)
+ .superRefine((val, ctx) => {
+ if (val === AGENT_VAULT_SESSION_TTL_NEVER) return;
+ let parsed: number | undefined;
+ try {
+ parsed = ms(val);
+ } catch {
+ parsed = undefined;
+ }
+ if (typeof parsed !== "number" || Number.isNaN(parsed) || parsed < 60 * 1000) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "TTL must be a duration of at least 1 minute, such as 30m, 8h or 7d, or never"
+ });
+ return;
+ }
+ if (parsed > AGENT_VAULT_SESSION_MAX_TTL_MS) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "TTL must be at most 100 years. Use never for a session that does not expire"
+ });
+ }
+ })
+ .describe(AGENT_VAULT.SESSION.ttl)
+ }),
+ response: {
+ 200: z.object({
+ session: z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),
+ token: z.string().describe(AGENT_VAULT.SESSION.token),
+ expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),
+ createdAt: z.date(),
+ accessBundles: SessionAccessBundleSchema.array()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ // Snapshotted from the request, the way PAM's session create does it, so a deleted actor still names
+ // the session it held. Nothing extra is queried for it.
+ let actorEmail: string | null = null;
+ let actorName = "";
+ if (isUserSessionAuth(req.auth)) {
+ actorEmail = req.auth.user.email ?? null;
+ actorName = `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim() || (actorEmail ?? "");
+ } else if (req.auth.authMode === AuthMode.IDENTITY_ACCESS_TOKEN) {
+ actorName = req.auth.identityName;
+ }
+
+ const { session, token } = await server.services.agentVaultSession.mintSession({
+ actorName,
+ actorEmail,
+ projectId: req.internalAgentVaultProjectId,
+ ctx: {
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ },
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_SESSION_MINT,
+ metadata: {
+ sessionId: session.id,
+ accessBundleId: session.accessBundles[0].id,
+ accessBundleName: session.accessBundles[0].name,
+ expiresAt: session.expiresAt?.toISOString() ?? null
+ }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultSessionCreated,
+ properties: {
+ sessionId: session.id,
+ accessBundleId: session.accessBundles[0].id,
+ ttlSeconds: req.body.ttl === AGENT_VAULT_SESSION_TTL_NEVER ? null : Math.floor(ms(req.body.ttl) / 1000)
+ }
+ });
+
+ return { session: { ...session, token } };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:sessionId/revoke",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "revokeAgentVaultSession",
+ description: "Revoke an Agent Vault session",
+ tags: [ApiDocsTags.AgentVaultSessions],
+ params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),
+ response: { 200: z.object({ session: SessionSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { session, revokedNow } = await server.services.agentVaultSession.revokeSession({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: {
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ },
+ sessionId: req.params.sessionId
+ });
+
+ // Revoking is idempotent, so a repeat would otherwise credit the second caller with a revocation.
+ if (revokedNow) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_SESSION_REVOKE,
+ metadata: { sessionId: session.id }
+ }
+ });
+
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultSessionRevoked,
+ properties: { sessionId: session.id }
+ });
+ }
+
+ return { session };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.ts
new file mode 100644
index 0000000000..dabe1544dc
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts
@@ -0,0 +1,16 @@
+import { registerAgentVaultAccessBundleRouter } from "./agent-vault-access-bundle-router";
+import { registerAgentVaultMembershipRouter } from "./agent-vault-membership-router";
+import { registerAgentVaultProjectRouter } from "./agent-vault-project-router";
+import { registerAgentVaultProxyAgentRouter } from "./agent-vault-proxy-agent-router";
+import { registerAgentVaultProxyRouter } from "./agent-vault-proxy-router";
+import { registerAgentVaultSessionRouter } from "./agent-vault-session-router";
+
+export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {
+ await server.register(registerAgentVaultProjectRouter, { prefix: "/project" });
+ await server.register(registerAgentVaultAccessBundleRouter, { prefix: "/access-bundles" });
+ await server.register(registerAgentVaultSessionRouter, { prefix: "/sessions" });
+ await server.register(registerAgentVaultProxyRouter, { prefix: "/proxies" });
+ await server.register(registerAgentVaultMembershipRouter, { prefix: "/memberships" });
+ // Separate prefix so the preValidation project hook still matches while these routes authenticate as the proxy.
+ await server.register(registerAgentVaultProxyAgentRouter, { prefix: "/proxy" });
+};
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 1a621cf7bf..7c816365ca 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -5,6 +5,7 @@ import { injectCertManagerProjectId } from "@app/server/plugins/inject-cert-mana
import { registerAccessApprovalPolicyRouter } from "./access-approval-policy-router";
import { registerAccessApprovalRequestRouter } from "./access-approval-request-router";
import { registerAgentProxyCaRouter } from "./agent-proxy-ca-router";
+import { registerAgentVaultRouters } from "./agent-vault-routers";
import { registerAssumePrivilegeRouter } from "./assume-privilege-router";
import { AUDIT_LOG_STREAM_REGISTER_ROUTER_MAP, registerAuditLogStreamRouter } from "./audit-log-stream-routers";
import { registerCaCrlRouter } from "./certificate-authority-crl-router";
@@ -202,4 +203,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
);
await server.register(registerPamRouters, { prefix: "/pam" });
+
+ await server.register(registerAgentVaultRouters, { prefix: "/agent-vault" });
};
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.ts
new file mode 100644
index 0000000000..f7acb98171
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.ts
@@ -0,0 +1,203 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { RESOURCE_SCOPE, ResourceType, TableName, TAgentVaultAccessBundles } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TAgentVaultAccessBundleDALFactory = ReturnType<typeof agentVaultAccessBundleDALFactory>;
+
+export type TAgentVaultAccessBundleListRow = {
+ id: string;
+ name: string;
+ description: string | null;
+ createdAt: Date;
+ serviceCount: number;
+ hostPatterns: string[];
+ memberCount: number;
+};
+
+export type TAgentVaultAccessBundleMemberDetail = {
+ id: string;
+ accessBundleId: string;
+ userId: string | null;
+ identityId: string | null;
+ groupId: string | null;
+ createdAt: Date;
+ user: { username: string; email: string | null; firstName: string | null; lastName: string | null } | null;
+ identity: { name: string } | null;
+ group: { name: string } | null;
+};
+
+const grantScope = (projectId: string, accessBundleId?: string) => ({
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.AgentVaultAccessBundle,
+ ...(accessBundleId ? { scopeResourceId: accessBundleId } : {})
+});
+
+export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultAccessBundle);
+
+ const findWithCounts = async (
+ { projectId, accessBundleIds }: { projectId: string; accessBundleIds: string[] | null },
+ tx?: Knex
+ ): Promise<TAgentVaultAccessBundleListRow[]> => {
+ if (accessBundleIds?.length === 0) return [];
+
+ try {
+ const conn = tx || db.replicaNode();
+
+ const memberCounts = conn(TableName.Membership)
+ .select("scopeResourceId")
+ .where({ ...grantScope(projectId), isActive: true })
+ .count("* as count")
+ .groupBy("scopeResourceId")
+ .as("mc");
+
+ const rows = (await conn(TableName.AgentVaultAccessBundle)
+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)
+ .where((qb) => {
+ if (accessBundleIds) void qb.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);
+ })
+ .leftJoin(
+ TableName.AgentVaultService,
+ `${TableName.AgentVaultService}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ )
+ .leftJoin(memberCounts, function joinMemberCount() {
+ this.on(db.raw(`mc."scopeResourceId" = ??.id::text`, [TableName.AgentVaultAccessBundle]));
+ })
+ .select(
+ db.ref("id").withSchema(TableName.AgentVaultAccessBundle),
+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle),
+ db.ref("description").withSchema(TableName.AgentVaultAccessBundle),
+ db.ref("createdAt").withSchema(TableName.AgentVaultAccessBundle),
+ db.ref("id").withSchema(TableName.AgentVaultService).as("serviceId"),
+ db.ref("hostPattern").withSchema(TableName.AgentVaultService),
+ db.raw('COALESCE(mc.count, 0)::int as "memberCount"')
+ )
+ .orderBy(`${TableName.AgentVaultAccessBundle}.name`, "asc")) as {
+ id: string;
+ name: string;
+ description: string | null;
+ createdAt: Date;
+ serviceId: string | null;
+ hostPattern: string | null;
+ memberCount: number;
+ }[];
+
+ const byBundle = new Map<string, TAgentVaultAccessBundleListRow>();
+ rows.forEach((row) => {
+ let bundle = byBundle.get(row.id);
+ if (!bundle) {
+ bundle = {
+ id: row.id,
+ name: row.name,
+ description: row.description,
+ createdAt: row.createdAt,
+ serviceCount: 0,
+ hostPatterns: [],
+ memberCount: row.memberCount
+ };
+ byBundle.set(row.id, bundle);
+ }
+ if (!row.serviceId) return;
+ bundle.serviceCount += 1;
+ if (row.hostPattern) bundle.hostPatterns.push(...row.hostPattern.split(","));
+ });
+
+ return [...byBundle.values()];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault access bundles" });
+ }
+ };
+
+ const findByIdInProject = async (
+ { id, projectId }: { id: string; projectId: string },
+ tx?: Knex
+ ): Promise<TAgentVaultAccessBundles | undefined> => {
+ try {
+ return await (tx || db.replicaNode())(TableName.AgentVaultAccessBundle).where({ id, projectId }).first();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault access bundle by id" });
+ }
+ };
+
+ // Inside addMember's transaction, so a concurrent bundle delete either waits for the grant and reaps
+ // it, or leaves nothing to grant to.
+ const lockByIdInProject = async (
+ { id, projectId }: { id: string; projectId: string },
+ tx: Knex
+ ): Promise<TAgentVaultAccessBundles | undefined> => {
+ try {
+ return await tx(TableName.AgentVaultAccessBundle).where({ id, projectId }).forUpdate().first();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Lock agent vault access bundle" });
+ }
+ };
+
+ const findMembers = async (
+ { projectId, accessBundleId }: { projectId: string; accessBundleId: string },
+ tx?: Knex
+ ): Promise<TAgentVaultAccessBundleMemberDetail[]> => {
+ try {
+ const rows = (await (tx || db.replicaNode())(TableName.Membership)
+ .where({ ...grantScope(projectId, accessBundleId), isActive: true })
+ .leftJoin(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
+ .leftJoin(TableName.Identity, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)
+ .leftJoin(TableName.Groups, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`)
+ .select(
+ db.ref("id").withSchema(TableName.Membership),
+ db.ref("scopeResourceId").withSchema(TableName.Membership).as("accessBundleId"),
+ db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),
+ db.ref("actorIdentityId").withSchema(TableName.Membership).as("identityId"),
+ db.ref("actorGroupId").withSchema(TableName.Membership).as("groupId"),
+ db.ref("createdAt").withSchema(TableName.Membership),
+ db.ref("username").withSchema(TableName.Users).as("userUsername"),
+ db.ref("firstName").withSchema(TableName.Users).as("userFirstName"),
+ db.ref("lastName").withSchema(TableName.Users).as("userLastName"),
+ db.ref("email").withSchema(TableName.Users).as("userEmail"),
+ db.ref("name").withSchema(TableName.Identity).as("identityName"),
+ db.ref("name").withSchema(TableName.Groups).as("groupName")
+ )
+ .orderBy(`${TableName.Membership}.createdAt`, "asc")) as {
+ id: string;
+ accessBundleId: string;
+ userId: string | null;
+ identityId: string | null;
+ groupId: string | null;
+ createdAt: Date;
+ userUsername: string | null;
+ userFirstName: string | null;
+ userLastName: string | null;
+ userEmail: string | null;
+ identityName: string | null;
+ groupName: string | null;
+ }[];
+
+ return rows.map((row) => ({
+ id: row.id,
+ accessBundleId: row.accessBundleId,
+ userId: row.userId,
+ identityId: row.identityId,
+ groupId: row.groupId,
+ createdAt: row.createdAt,
+ user: row.userId
+ ? {
+ username: row.userUsername ?? "",
+ email: row.userEmail,
+ firstName: row.userFirstName,
+ lastName: row.userLastName
+ }
+ : null,
+ identity: row.identityId ? { name: row.identityName ?? "" } : null,
+ group: row.groupId ? { name: row.groupName ?? "" } : null
+ }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault access bundle members" });
+ }
+ };
+
+ return { ...orm, findWithCounts, findByIdInProject, lockByIdInProject, findMembers };
+};
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
new file mode 100644
index 0000000000..dfc0b291b9
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
@@ -0,0 +1,765 @@
+import { ForbiddenError } from "@casl/ability";
+import { Knex } from "knex";
+
+import { AccessScope, RESOURCE_SCOPE, ResourceType, TAgentVaultServices, TMemberships } from "@app/db/schemas";
+import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+
+import { describeConflict, findHostPatternConflicts } from "../agent-vault/agent-vault-conflict-fns";
+import {
+ AgentVaultBearerConfigSchema,
+ TAgentVaultCredentialConfig
+} from "../agent-vault/agent-vault-credential-schemas";
+import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";
+import { AgentVaultCredentialType, AgentVaultResourceRole } from "../agent-vault/agent-vault-enums";
+import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
+import { TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";
+import {
+ TAddMembersDTO,
+ TAgentVaultCredentialInput,
+ TAgentVaultCredentialSummary,
+ TAgentVaultCredentialUpdate,
+ TCreateAccessBundleDTO,
+ TCreateServiceDTO,
+ TDeleteAccessBundleDTO,
+ TDeleteServiceDTO,
+ TGetAccessBundleDTO,
+ TListAccessBundlesDTO,
+ TListMembersDTO,
+ TRemoveMemberDTO,
+ TUpdateAccessBundleDTO,
+ TUpdateServiceDTO
+} from "./agent-vault-access-bundle-types";
+import { TAgentVaultServiceDALFactory } from "./agent-vault-service-dal";
+
+type TAgentVaultAccessBundleServiceFactoryDep = {
+ agentVaultAccessBundleDAL: TAgentVaultAccessBundleDALFactory;
+ agentVaultServiceDAL: TAgentVaultServiceDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ membershipDAL: Pick<
+ TMembershipDALFactory,
+ "findOne" | "find" | "insertMany" | "delete" | "deleteById" | "transaction" | "findResourceMembershipsForActor"
+ >;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany">;
+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
+};
+
+export type TAgentVaultAccessBundleServiceFactory = ReturnType<typeof agentVaultAccessBundleServiceFactory>;
+
+// The old shape capped the array at 100 entries; the cap moves here now that the body is three lists.
+export const AGENT_VAULT_MAX_GRANTEES = 100;
+
+export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundleServiceFactoryDep) => {
+ const {
+ agentVaultAccessBundleDAL,
+ agentVaultServiceDAL,
+ permissionService,
+ kmsService,
+ membershipDAL,
+ membershipRoleDAL,
+ userGroupMembershipDAL,
+ identityGroupMembershipDAL
+ } = deps;
+
+ const bundleScope = (projectId: string, accessBundleId: string) => ({
+ scope: RESOURCE_SCOPE as typeof RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.AgentVaultAccessBundle,
+ scopeResourceId: accessBundleId
+ });
+
+ const toMember = (row: TMemberships) => ({
+ id: row.id,
+ accessBundleId: row.scopeResourceId!,
+ userId: row.actorUserId ?? null,
+ identityId: row.actorIdentityId ?? null,
+ groupId: row.actorGroupId ?? null,
+ createdAt: row.createdAt
+ });
+
+ type TGrantActorColumn = "actorUserId" | "actorIdentityId" | "actorGroupId";
+
+ type TGrantActor = { actorColumn: TGrantActorColumn; actorId: string };
+
+ const actorKey = ({ actorColumn, actorId }: TGrantActor) => `${actorColumn}:${actorId}`;
+
+ const ACTOR_FIELD_OF: Record<TGrantActorColumn, "userId" | "identityId" | "groupId"> = {
+ actorUserId: "userId",
+ actorIdentityId: "identityId",
+ actorGroupId: "groupId"
+ };
+
+ const writeGrants = async (
+ {
+ projectId,
+ orgId,
+ accessBundleId,
+ actors
+ }: { projectId: string; orgId: string; accessBundleId: string; actors: TGrantActor[] },
+ tx: Knex
+ ) => {
+ const memberships = await membershipDAL.insertMany(
+ actors.map(({ actorColumn, actorId }) => ({
+ ...bundleScope(projectId, accessBundleId),
+ scopeOrgId: orgId,
+ [actorColumn]: actorId,
+ isActive: true
+ })),
+ tx
+ );
+ await membershipRoleDAL.insertMany(
+ memberships.map((membership) => ({ membershipId: membership.id, role: AgentVaultResourceRole.Consumer })),
+ tx
+ );
+ return memberships;
+ };
+
+ const isInProjectThroughGroup = async ({
+ projectId,
+ userId,
+ identityId
+ }: {
+ projectId: string;
+ userId?: string;
+ identityId?: string;
+ }) => {
+ const groups = userId
+ ? await userGroupMembershipDAL.find({ userId })
+ : await identityGroupMembershipDAL.find({ identityId: identityId! });
+ if (!groups.length) return false;
+
+ const viaGroup = await membershipDAL.find({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ $in: { actorGroupId: groups.map((group) => group.groupId) }
+ });
+ return viaGroup.length > 0;
+ };
+
+ const assertActorInProject = async ({
+ projectId,
+ userId,
+ identityId,
+ groupId
+ }: {
+ projectId: string;
+ userId?: string;
+ identityId?: string;
+ groupId?: string;
+ }) => {
+ const membership = await membershipDAL.findOne({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ ...(userId ? { actorUserId: userId } : {}),
+ ...(identityId ? { actorIdentityId: identityId } : {}),
+ ...(groupId ? { actorGroupId: groupId } : {})
+ });
+
+ if (membership) return;
+
+ // Named, because a batch grant rejects on the first offender and the caller would otherwise have to bisect.
+ let actor = `group '${groupId}'`;
+ if (userId) actor = `user '${userId}'`;
+ else if (identityId) actor = `machine identity '${identityId}'`;
+
+ if (!groupId && (await isInProjectThroughGroup({ projectId, userId, identityId }))) {
+ throw new BadRequestError({
+ message: `The ${actor} is in Agent Vault through a group. Grant the access bundle to the group, or add them directly under Access Control first.`
+ });
+ }
+
+ throw new BadRequestError({
+ message: `The ${actor} is not a member of Agent Vault. Add them under Access Control first.`
+ });
+ };
+
+ const assertActorsInProject = async ({ projectId, actors }: { projectId: string; actors: TGrantActor[] }) => {
+ const idsByColumn = new Map<TGrantActorColumn, string[]>();
+ actors.forEach((actor) => {
+ idsByColumn.set(actor.actorColumn, [...(idsByColumn.get(actor.actorColumn) ?? []), actor.actorId]);
+ });
+
+ const found = new Set<string>();
+ await Promise.all(
+ [...idsByColumn].map(async ([actorColumn, actorIds]) => {
+ const rows = await membershipDAL.find({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ $in: { [actorColumn]: actorIds }
+ });
+ rows.forEach((row) => found.add(actorKey({ actorColumn, actorId: row[actorColumn]! })));
+ })
+ );
+
+ // The single-actor check re-queries the first offender so the caller gets the specific reason, not just a count.
+ const missing = actors.find((actor) => !found.has(actorKey(actor)));
+ if (missing) {
+ await assertActorInProject({ projectId, [ACTOR_FIELD_OF[missing.actorColumn]]: missing.actorId });
+ }
+ };
+
+ const getProjectCipher = (projectId: string) =>
+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+
+ // `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret
+ // as passthrough, so the two are not interchangeable.
+ type TCredentialWrite = { config: TAgentVaultCredentialConfig; secret: Record<string, string> | null | undefined };
+
+ const splitCredential = (credential: TAgentVaultCredentialInput): TCredentialWrite => {
+ switch (credential.type) {
+ case AgentVaultCredentialType.Bearer: {
+ const config = AgentVaultBearerConfigSchema.parse({
+ headerName: credential.headerName,
+ headerPrefix: credential.headerPrefix
+ });
+ return { config: { type: credential.type, ...config }, secret: { value: credential.value } };
+ }
+ case AgentVaultCredentialType.Basic: {
+ if (!credential.username && !credential.password) {
+ throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });
+ }
+ return {
+ config: { type: credential.type },
+ secret: { username: credential.username, password: credential.password }
+ };
+ }
+ default:
+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };
+ }
+ };
+
+ const mergeCredential = (
+ credential: TAgentVaultCredentialUpdate,
+ stored: TAgentVaultServices,
+ storedSecret: Record<string, string> | null
+ ): TCredentialWrite => {
+ if (credential.type !== stored.credentialType) {
+ if (credential.type === AgentVaultCredentialType.Bearer && credential.value === undefined) {
+ throw new BadRequestError({
+ message:
+ "Changing the credential type to bearer needs the token, because the stored secret belongs to the old type"
+ });
+ }
+ return splitCredential(
+ credential.type === AgentVaultCredentialType.Basic
+ ? { type: credential.type, username: credential.username ?? "", password: credential.password ?? "" }
+ : (credential as TAgentVaultCredentialInput)
+ );
+ }
+
+ const prev = (stored.credentialConfig ?? {}) as { headerName?: string; headerPrefix?: string };
+
+ switch (credential.type) {
+ case AgentVaultCredentialType.Bearer:
+ return {
+ config: {
+ type: credential.type,
+ headerName: credential.headerName ?? prev.headerName ?? "Authorization",
+ headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""
+ },
+ secret: credential.value === undefined ? undefined : { value: credential.value }
+ };
+ case AgentVaultCredentialType.Basic: {
+ if (credential.username === undefined && credential.password === undefined) {
+ return { config: { type: credential.type }, secret: undefined };
+ }
+ const username = credential.username ?? storedSecret?.username ?? "";
+ const password = credential.password ?? storedSecret?.password ?? "";
+ if (!username && !password) {
+ throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });
+ }
+ return { config: { type: credential.type }, secret: { username, password } };
+ }
+ default:
+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };
+ }
+ };
+
+ const summarizeCredential = (service: TAgentVaultServices): TAgentVaultCredentialSummary => {
+ const config = service.credentialConfig as Record<string, string>;
+ switch (service.credentialType as AgentVaultCredentialType) {
+ case AgentVaultCredentialType.Bearer:
+ return {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: config.headerName,
+ headerPrefix: config.headerPrefix
+ };
+ case AgentVaultCredentialType.Basic:
+ return { type: AgentVaultCredentialType.Basic };
+ default:
+ return { type: AgentVaultCredentialType.Passthrough };
+ }
+ };
+
+ // A bundle the caller cannot reach is a 404, never a 403, which would confirm the id exists.
+ const resolveReachableBundle = async ({ projectId, ctx, accessBundleId }: TGetAccessBundleDTO) => {
+ const reachability = await getAgentVaultReachability({ permissionService, membershipDAL }, { projectId, ctx });
+
+ const bundle = await agentVaultAccessBundleDAL.findByIdInProject({ id: accessBundleId, projectId });
+ // Postgres compares uuids case-insensitively but this list does not, so an uppercase id would miss.
+ const unreachable =
+ reachability.accessBundleIds && !reachability.accessBundleIds.includes(accessBundleId.toLowerCase());
+ if (!bundle || unreachable) {
+ throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });
+ }
+
+ return { bundle, ...reachability };
+ };
+
+ const listAccessBundles = async ({ projectId, ctx }: TListAccessBundlesDTO) => {
+ const { permission, accessBundleIds } = await getAgentVaultReachability(
+ { permissionService, membershipDAL },
+ { projectId, ctx }
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Read,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ return agentVaultAccessBundleDAL.findWithCounts({ projectId, accessBundleIds });
+ };
+
+ const getAccessBundleById = async (dto: TGetAccessBundleDTO) => {
+ const { bundle, permission, isAdmin } = await resolveReachableBundle(dto);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Read,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const services = await agentVaultServiceDAL.findByAccessBundleId(bundle.id);
+ const members = isAdmin
+ ? await agentVaultAccessBundleDAL.findMembers({ projectId: dto.projectId, accessBundleId: bundle.id })
+ : undefined;
+
+ return {
+ id: bundle.id,
+ name: bundle.name,
+ description: bundle.description ?? null,
+ createdAt: bundle.createdAt,
+ services: services.map((service) => ({
+ id: service.id,
+ accessBundleId: service.accessBundleId,
+ name: service.name,
+ hostPattern: service.hostPattern,
+ credential: summarizeCredential(service),
+ createdAt: service.createdAt
+ })),
+ members
+ };
+ };
+
+ const createAccessBundle = async ({ projectId, ctx, name, description }: TCreateAccessBundleDTO) => {
+ const { permission } = await getAgentVaultReachability({ permissionService, membershipDAL }, { projectId, ctx });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Create,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const existing = await agentVaultAccessBundleDAL.findOne({ projectId, name });
+ if (existing) {
+ throw new BadRequestError({ message: `An access bundle named '${name}' already exists` });
+ }
+
+ let creatorColumn: TGrantActorColumn | null = null;
+ if (ctx.actor === ActorType.USER) creatorColumn = "actorUserId";
+ else if (ctx.actor === ActorType.IDENTITY) creatorColumn = "actorIdentityId";
+
+ const create = () =>
+ agentVaultAccessBundleDAL.transaction(async (tx) => {
+ const bundle = await agentVaultAccessBundleDAL.create({ projectId, name, description }, tx);
+
+ if (creatorColumn) {
+ const direct = await membershipDAL.findOne(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [creatorColumn]: ctx.actorId },
+ tx
+ );
+ if (direct) {
+ await writeGrants(
+ {
+ projectId,
+ orgId: ctx.actorOrgId,
+ accessBundleId: bundle.id,
+ actors: [{ actorColumn: creatorColumn, actorId: ctx.actorId }]
+ },
+ tx
+ );
+ }
+ }
+
+ return bundle;
+ });
+
+ try {
+ return await create();
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new BadRequestError({ message: `An access bundle named '${name}' already exists` });
+ }
+ throw err;
+ }
+ };
+
+ const updateAccessBundle = async ({ accessBundleId, name, description, ...rest }: TUpdateAccessBundleDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ if (name && name !== bundle.name) {
+ const existing = await agentVaultAccessBundleDAL.findOne({ projectId: rest.projectId, name });
+ if (existing) throw new BadRequestError({ message: `An access bundle named '${name}' already exists` });
+ }
+
+ try {
+ return await agentVaultAccessBundleDAL.updateById(bundle.id, { name, description });
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new BadRequestError({ message: `An access bundle named '${name}' already exists` });
+ }
+ throw err;
+ }
+ };
+
+ const deleteAccessBundle = async ({ accessBundleId, ...rest }: TDeleteAccessBundleDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Delete,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ // Bundle row first: its DELETE holds the row lock addMember takes. Roles cascade.
+ return agentVaultAccessBundleDAL.transaction(async (tx) => {
+ const deleted = await agentVaultAccessBundleDAL.deleteById(bundle.id, tx);
+ await membershipDAL.delete(bundleScope(rest.projectId, bundle.id), tx);
+ return deleted;
+ });
+ };
+
+ const checkHostPatternConflicts = async (
+ {
+ accessBundleId,
+ hostPattern,
+ excludeServiceId
+ }: {
+ accessBundleId: string;
+ hostPattern: string;
+ excludeServiceId?: string;
+ },
+ // Without a tx this reads the replica outside any lock, so two creates for the same host both pass.
+ tx?: Knex
+ ) => {
+ const siblings = await agentVaultServiceDAL.findByAccessBundleId(accessBundleId, tx);
+ const conflicts = findHostPatternConflicts(
+ hostPattern,
+ siblings.filter((candidate) => candidate.id !== excludeServiceId)
+ );
+ if (conflicts.length) {
+ throw new BadRequestError({ message: describeConflict(conflicts[0]) });
+ }
+ };
+
+ const createService = async ({ accessBundleId, name, hostPattern, credential, ...rest }: TCreateServiceDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const existing = await agentVaultServiceDAL.findOne({ accessBundleId: bundle.id, name });
+ if (existing) {
+ throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });
+ }
+
+ await checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern });
+
+ // Encrypt before the lock: KMS is a network call and the transaction has to stay short.
+ const { config, secret } = splitCredential(credential);
+ const { encryptor } = await getProjectCipher(rest.projectId);
+ const encryptedCredential = secret
+ ? encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob
+ : null;
+
+ // The pre-check above is only a fast failure. The authoritative one runs under the bundle row lock,
+ // the same lock addMembers takes, because no database constraint can express host-pattern overlap.
+ const write = () =>
+ agentVaultServiceDAL.transaction(async (tx) => {
+ const locked = await agentVaultAccessBundleDAL.lockByIdInProject(
+ { id: bundle.id, projectId: rest.projectId },
+ tx
+ );
+ if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });
+
+ await checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern }, tx);
+
+ return agentVaultServiceDAL.create(
+ {
+ accessBundleId: bundle.id,
+ name,
+ hostPattern,
+ credentialType: credential.type,
+ credentialConfig: config,
+ encryptedCredential
+ },
+ tx
+ );
+ });
+
+ let service;
+ try {
+ service = await write();
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });
+ }
+ throw err;
+ }
+
+ return { service: { ...service, credential: summarizeCredential(service) } };
+ };
+
+ const updateService = async ({
+ accessBundleId,
+ serviceId,
+ name,
+ hostPattern,
+ credential,
+ ...rest
+ }: TUpdateServiceDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const service = await agentVaultServiceDAL.findOne({ id: serviceId, accessBundleId: bundle.id });
+ if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });
+
+ if (name && name !== service.name) {
+ const existing = await agentVaultServiceDAL.findOne({ accessBundleId: bundle.id, name });
+ if (existing) {
+ throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });
+ }
+ }
+
+ if (hostPattern && hostPattern !== service.hostPattern) {
+ await checkHostPatternConflicts({
+ accessBundleId: bundle.id,
+ hostPattern,
+ excludeServiceId: service.id
+ });
+ }
+
+ let credentialUpdate = {};
+ if (credential) {
+ const needsStoredSecret =
+ credential.type === AgentVaultCredentialType.Basic &&
+ service.credentialType === AgentVaultCredentialType.Basic &&
+ (credential.username === undefined) !== (credential.password === undefined) &&
+ Boolean(service.encryptedCredential);
+ const cipher = needsStoredSecret ? await getProjectCipher(rest.projectId) : null;
+ const storedSecret = cipher
+ ? (JSON.parse(cipher.decryptor({ cipherTextBlob: service.encryptedCredential! }).toString("utf-8")) as Record<
+ string,
+ string
+ >)
+ : null;
+
+ const { config, secret } = mergeCredential(credential, service, storedSecret);
+ let encryptedCredential: Buffer | null | undefined;
+ if (secret === null) encryptedCredential = null;
+ if (secret) {
+ const { encryptor } = cipher ?? (await getProjectCipher(rest.projectId));
+ encryptedCredential = encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob;
+ }
+
+ credentialUpdate = {
+ credentialType: credential.type,
+ credentialConfig: config,
+ ...(encryptedCredential === undefined ? {} : { encryptedCredential })
+ };
+ }
+
+ // Same lock as create, and below the credential work so no KMS call sits inside the transaction. The
+ // re-check only earns its place when the pattern actually changes.
+ const write = () =>
+ agentVaultServiceDAL.transaction(async (tx) => {
+ const locked = await agentVaultAccessBundleDAL.lockByIdInProject(
+ { id: bundle.id, projectId: rest.projectId },
+ tx
+ );
+ if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });
+
+ if (hostPattern && hostPattern !== service.hostPattern) {
+ await checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern, excludeServiceId: service.id }, tx);
+ }
+
+ return agentVaultServiceDAL.updateById(
+ service.id,
+ {
+ name,
+ hostPattern,
+ ...credentialUpdate
+ },
+ tx
+ );
+ });
+
+ let updated;
+ try {
+ updated = await write();
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });
+ }
+ throw err;
+ }
+
+ return { service: { ...updated, credential: summarizeCredential(updated) } };
+ };
+
+ const deleteService = async ({ accessBundleId, serviceId, ...rest }: TDeleteServiceDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const service = await agentVaultServiceDAL.findOne({ id: serviceId, accessBundleId: bundle.id });
+ if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });
+
+ const deleted = await agentVaultServiceDAL.deleteById(service.id);
+ return { ...deleted, credential: summarizeCredential(deleted) };
+ };
+
+ const listMembers = async ({ accessBundleId, ...rest }: TListMembersDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+ return agentVaultAccessBundleDAL.findMembers({ projectId: rest.projectId, accessBundleId: bundle.id });
+ };
+
+ const addMembers = async ({ accessBundleId, userIds, groupIds, identityIds, ...rest }: TAddMembersDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const requested = new Map<string, TGrantActor>();
+ const byColumn: [TGrantActorColumn, string[]][] = [
+ ["actorUserId", userIds],
+ ["actorGroupId", groupIds],
+ ["actorIdentityId", identityIds]
+ ];
+ byColumn.forEach(([actorColumn, ids]) => {
+ ids.forEach((actorId) => {
+ const actor = { actorColumn, actorId };
+ requested.set(actorKey(actor), actor);
+ });
+ });
+
+ const actors = [...requested.values()];
+ await assertActorsInProject({ projectId: rest.projectId, actors });
+
+ // The bundle row lock serializes grants for this bundle, so reading the existing ones inside it is
+ // enough to dedupe. The unique index per actor per bundle stays as the backstop, and its violation
+ // has to be caught outside the transaction.
+ const grant = () =>
+ membershipDAL.transaction(async (tx) => {
+ const locked = await agentVaultAccessBundleDAL.lockByIdInProject(
+ { id: bundle.id, projectId: rest.projectId },
+ tx
+ );
+ if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });
+
+ const existing = await membershipDAL.find(bundleScope(rest.projectId, bundle.id), { tx });
+ const alreadyGranted = new Set(
+ existing.flatMap((row) => {
+ if (row.actorUserId) return [actorKey({ actorColumn: "actorUserId", actorId: row.actorUserId })];
+ if (row.actorIdentityId)
+ return [actorKey({ actorColumn: "actorIdentityId", actorId: row.actorIdentityId })];
+ if (row.actorGroupId) return [actorKey({ actorColumn: "actorGroupId", actorId: row.actorGroupId })];
+ return [];
+ })
+ );
+
+ const skipped = actors.filter((actor) => alreadyGranted.has(actorKey(actor))).map((actor) => actor.actorId);
+ const toGrant = actors.filter((actor) => !alreadyGranted.has(actorKey(actor)));
+ if (!toGrant.length) return { created: [] as TMemberships[], skipped };
+
+ const created = await writeGrants(
+ { projectId: rest.projectId, orgId: rest.ctx.actorOrgId, accessBundleId: bundle.id, actors: toGrant },
+ tx
+ );
+ return { created, skipped };
+ });
+
+ let outcome: { created: TMemberships[]; skipped: string[] };
+ try {
+ outcome = await grant();
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new BadRequestError({ message: "That user, machine identity or group already has this access bundle" });
+ }
+ throw err;
+ }
+
+ return {
+ members: outcome.created.map(toMember),
+ skipped: outcome.skipped,
+ accessBundleName: bundle.name
+ };
+ };
+
+ const removeMember = async ({ accessBundleId, memberId, ...rest }: TRemoveMemberDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ const member = await membershipDAL.findOne({ ...bundleScope(rest.projectId, bundle.id), id: memberId });
+ if (!member) throw new NotFoundError({ message: `Access bundle membership with ID '${memberId}' not found` });
+
+ await membershipDAL.deleteById(member.id);
+ return {
+ id: member.id,
+ accessBundleId: bundle.id,
+ userId: member.actorUserId ?? null,
+ identityId: member.actorIdentityId ?? null,
+ groupId: member.actorGroupId ?? null,
+ createdAt: member.createdAt,
+ accessBundleName: bundle.name
+ };
+ };
+
+ return {
+ listAccessBundles,
+ getAccessBundleById,
+ createAccessBundle,
+ updateAccessBundle,
+ deleteAccessBundle,
+ createService,
+ updateService,
+ deleteService,
+ listMembers,
+ addMembers,
+ removeMember
+ };
+};
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
new file mode 100644
index 0000000000..21974e4c80
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
@@ -0,0 +1,70 @@
+import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";
+import { AgentVaultCredentialType } from "../agent-vault/agent-vault-enums";
+
+export type TAgentVaultCredentialInput =
+ | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value: string }
+ | { type: AgentVaultCredentialType.Basic; username: string; password: string }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type TAgentVaultCredentialUpdate =
+ | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value?: string }
+ | { type: AgentVaultCredentialType.Basic; username?: string; password?: string }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type TAgentVaultCredentialSummary =
+ | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }
+ | { type: AgentVaultCredentialType.Basic }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type TAgentVaultProjectScoped = { projectId: string; ctx: TAgentVaultActorContext };
+
+export type TListAccessBundlesDTO = TAgentVaultProjectScoped;
+
+export type TGetAccessBundleDTO = TAgentVaultProjectScoped & { accessBundleId: string };
+
+export type TCreateAccessBundleDTO = TAgentVaultProjectScoped & {
+ name: string;
+ description?: string;
+};
+
+export type TUpdateAccessBundleDTO = TAgentVaultProjectScoped & {
+ accessBundleId: string;
+ name?: string;
+ description?: string | null;
+};
+
+export type TDeleteAccessBundleDTO = TAgentVaultProjectScoped & { accessBundleId: string };
+
+export type TCreateServiceDTO = TAgentVaultProjectScoped & {
+ accessBundleId: string;
+ name: string;
+ hostPattern: string;
+ credential: TAgentVaultCredentialInput;
+};
+
+export type TUpdateServiceDTO = TAgentVaultProjectScoped & {
+ accessBundleId: string;
+ serviceId: string;
+ name?: string;
+ hostPattern?: string;
+ credential?: TAgentVaultCredentialUpdate;
+};
+
+export type TDeleteServiceDTO = TAgentVaultProjectScoped & {
+ accessBundleId: string;
+ serviceId: string;
+};
+
+export type TListMembersDTO = TAgentVaultProjectScoped & { accessBundleId: string };
+
+export type TAddMembersDTO = TAgentVaultProjectScoped & {
+ accessBundleId: string;
+ userIds: string[];
+ groupIds: string[];
+ identityIds: string[];
+};
+
+export type TRemoveMemberDTO = TAgentVaultProjectScoped & {
+ accessBundleId: string;
+ memberId: string;
+};
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts
new file mode 100644
index 0000000000..3f0ad4be22
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts
@@ -0,0 +1,24 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAgentVaultServices } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TAgentVaultServiceDALFactory = ReturnType<typeof agentVaultServiceDALFactory>;
+
+export const agentVaultServiceDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultService);
+
+ const findByAccessBundleId = async (accessBundleId: string, tx?: Knex): Promise<TAgentVaultServices[]> => {
+ try {
+ return (await (tx || db.replicaNode())(TableName.AgentVaultService)
+ .where({ accessBundleId })
+ .orderBy("name", "asc")) as TAgentVaultServices[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault services" });
+ }
+ };
+
+ return { ...orm, findByAccessBundleId };
+};
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
new file mode 100644
index 0000000000..e7f1aa1175
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, test, vi } from "vitest";
+
+import { AccessScope, ProjectMembershipRole } from "@app/db/schemas";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { agentVaultMembershipServiceFactory } from "./agent-vault-membership-service";
+
+const ORG_ID = "org-1";
+const PROJECT_ID = "project-1";
+const OTHER_PROJECT_ID = "project-2";
+const ACTOR_ID = "actor-1";
+const IDENTITY_ID = "identity-1";
+
+const ctx = {
+ actor: ActorType.USER,
+ actorId: ACTOR_ID,
+ actorOrgId: ORG_ID,
+ actorAuthMethod: undefined
+} as unknown as Parameters<ReturnType<typeof agentVaultMembershipServiceFactory>["addProductMember"]>[0]["ctx"];
+
+const buildTx = (adminCount: number) => {
+ const chain: Record<string, unknown> = {};
+ ["join", "where", "orWhere", "whereNotIn", "countDistinct"].forEach((method) => {
+ chain[method] = vi.fn((arg: unknown) => {
+ if (typeof arg === "function") (arg as (qb: unknown) => void)(chain);
+ return chain;
+ });
+ });
+ chain.first = vi.fn().mockResolvedValue({ count: String(adminCount) });
+
+ const tx = vi.fn(() => chain) as unknown as { raw: ReturnType<typeof vi.fn> };
+ tx.raw = vi.fn();
+ return tx;
+};
+
+// Only the collaborators these three guards touch; everything else is left undefined so a guard that
+// fails to short-circuit shows up as a crash rather than a silent pass.
+const buildService = ({
+ identityProjectId = null as string | null,
+ productMemberships = [] as { id: string }[],
+ adminMembershipIds = [] as string[]
+} = {}) => {
+ const deps = {
+ permissionService: { getProjectPermission: vi.fn().mockResolvedValue({ hasRole: () => true }) },
+ identityDAL: {
+ find: vi.fn().mockResolvedValue([{ id: IDENTITY_ID, name: "agent", orgId: ORG_ID, projectId: identityProjectId }])
+ },
+ groupDAL: { find: vi.fn().mockResolvedValue([]) },
+ userDAL: { find: vi.fn().mockResolvedValue([]) },
+ userAliasDAL: { findBySsoExternalIds: vi.fn().mockResolvedValue([]) },
+ orgDAL: {
+ findById: vi.fn().mockResolvedValue({ id: ORG_ID, rootOrgId: null }),
+ findEffectiveOrgMembership: vi.fn().mockResolvedValue({ isActive: true })
+ },
+ membershipDAL: {
+ find: vi.fn(({ scope }: { scope: string }) =>
+ Promise.resolve(scope === AccessScope.Project ? productMemberships : [])
+ ),
+ // assertWillRetainProjectAdmin takes an advisory lock through tx.raw, then counts live admins
+ // with a query built off tx() itself. The chain answers with the fixture's admin count, so
+ // adminMembershipIds still decides whether the guard lets the write through.
+ transaction: vi.fn((cb: (tx: unknown) => unknown) => Promise.resolve(cb(buildTx(adminMembershipIds.length)))),
+ create: vi.fn().mockResolvedValue({ id: "mem-new", createdAt: new Date() }),
+ delete: vi.fn().mockResolvedValue(undefined),
+ deleteById: vi.fn().mockResolvedValue(undefined)
+ },
+ membershipRoleDAL: {
+ find: vi
+ .fn()
+ .mockResolvedValue(adminMembershipIds.map((id) => ({ membershipId: id, role: ProjectMembershipRole.Admin }))),
+ create: vi.fn(({ role }: { role: string }) => Promise.resolve({ role })),
+ delete: vi.fn().mockResolvedValue(undefined),
+ update: vi.fn().mockResolvedValue(undefined)
+ },
+ projectAccessRequestDAL: { delete: vi.fn().mockResolvedValue(undefined) },
+ usageMeteringService: { emitForProject: vi.fn() }
+ };
+
+ const service = agentVaultMembershipServiceFactory(
+ deps as unknown as Parameters<typeof agentVaultMembershipServiceFactory>[0]
+ );
+ return { service, deps };
+};
+
+describe("agentVaultMembership guards", () => {
+ // A project-scoped identity also carries an org-scope NoAccess membership, so the organization check
+ // alone lets another product's identity in, and it could then mint Agent Vault sessions.
+ test("refuses an identity scoped to another project", async () => {
+ const { service, deps } = buildService({ identityProjectId: OTHER_PROJECT_ID });
+
+ await expect(
+ service.addProductMember({
+ projectId: PROJECT_ID,
+ identityId: IDENTITY_ID,
+ role: ProjectMembershipRole.Member,
+ ctx
+ })
+ ).rejects.toThrow("belongs to another project");
+
+ expect(deps.membershipDAL.create).not.toHaveBeenCalled();
+ });
+
+ test("accepts an identity that belongs to no project", async () => {
+ const { service } = buildService({ identityProjectId: null });
+
+ const added = await service.addProductMember({
+ projectId: PROJECT_ID,
+ identityId: IDENTITY_ID,
+ role: ProjectMembershipRole.Member,
+ ctx
+ });
+
+ expect(added.membershipId).toBe("mem-new");
+ });
+
+ test("accepts an identity created inside Agent Vault itself", async () => {
+ const { service } = buildService({ identityProjectId: PROJECT_ID });
+
+ const added = await service.addProductMember({
+ projectId: PROJECT_ID,
+ identityId: IDENTITY_ID,
+ role: ProjectMembershipRole.Member,
+ ctx
+ });
+
+ expect(added.membershipId).toBe("mem-new");
+ });
+
+ // Removing only the membership would leave the identity live but off every screen: this product's tab
+ // lists by membership, and the organization list hides project-scoped identities.
+ test("refuses to detach an identity Agent Vault owns, pointing at delete instead", async () => {
+ const { service, deps } = buildService({ identityProjectId: PROJECT_ID });
+
+ await expect(service.removeProductMember({ projectId: PROJECT_ID, identityId: IDENTITY_ID, ctx })).rejects.toThrow(
+ "Delete the identity instead"
+ );
+
+ expect(deps.membershipDAL.deleteById).not.toHaveBeenCalled();
+ });
+
+ test("still detaches an identity the organization owns", async () => {
+ const { service, deps } = buildService({
+ identityProjectId: null,
+ productMemberships: [{ id: "mem-1" }],
+ adminMembershipIds: ["mem-other"]
+ });
+
+ await service.removeProductMember({ projectId: PROJECT_ID, identityId: IDENTITY_ID, ctx });
+
+ expect(deps.membershipDAL.deleteById).toHaveBeenCalledWith("mem-1", expect.anything());
+ });
+
+ test("refuses to change your own role", async () => {
+ const { service, deps } = buildService();
+
+ await expect(
+ service.updateProductMemberRole({
+ projectId: PROJECT_ID,
+ userId: ACTOR_ID,
+ role: ProjectMembershipRole.Member,
+ ctx
+ })
+ ).rejects.toThrow("your own role");
+
+ expect(deps.membershipRoleDAL.create).not.toHaveBeenCalled();
+ });
+
+ test("still changes someone else's role", async () => {
+ const { service } = buildService({
+ productMemberships: [{ id: "mem-1" }],
+ adminMembershipIds: ["mem-other"]
+ });
+
+ const updated = await service.updateProductMemberRole({
+ projectId: PROJECT_ID,
+ userId: "someone-else",
+ role: ProjectMembershipRole.Member,
+ ctx
+ });
+
+ expect(updated.role).toBe(ProjectMembershipRole.Member);
+ });
+});
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
new file mode 100644
index 0000000000..66d5e7dafc
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
@@ -0,0 +1,529 @@
+import { ForbiddenError } from "@casl/ability";
+
+import {
+ AccessScope,
+ ActionProjectType,
+ OrgMembershipStatus,
+ ProjectMembershipRole,
+ RESOURCE_SCOPE
+} from "@app/db/schemas";
+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionGroupActions,
+ ProjectPermissionIdentityActions,
+ ProjectPermissionMemberActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
+import { AgentVaultIdentities } from "@app/services/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { assertWillRetainProjectAdmin } from "@app/services/membership/membership-fns";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TProjectAccessRequestDALFactory } from "@app/services/project/project-access-request-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
+import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
+import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias-fns";
+
+import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";
+
+type TAgentVaultMembershipServiceFactoryDep = {
+ membershipDAL: Pick<TMembershipDALFactory, "create" | "find" | "transaction" | "delete" | "deleteById">;
+ identityDAL: Pick<TIdentityDALFactory, "find">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find" | "delete" | "update">;
+ groupDAL: Pick<TGroupDALFactory, "find">;
+ projectAccessRequestDAL: Pick<TProjectAccessRequestDALFactory, "delete">;
+ userDAL: Pick<TUserDALFactory, "find">;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;
+ orgDAL: Pick<TOrgDALFactory, "findById" | "findEffectiveOrgMembership">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
+};
+
+export type TAgentVaultMembershipServiceFactory = ReturnType<typeof agentVaultMembershipServiceFactory>;
+
+export type TListAgentVaultProductMembersDTO = {
+ projectId: string;
+ ctx: TAgentVaultActorContext;
+};
+
+type TAgentVaultProductActor = {
+ userId?: string;
+ groupId?: string;
+ identityId?: string;
+};
+
+export type TAddAgentVaultProductMemberDTO = TAgentVaultProductActor & {
+ projectId: string;
+ role: string;
+ ctx: TAgentVaultActorContext;
+};
+
+export type TUpdateAgentVaultProductMemberDTO = TAddAgentVaultProductMemberDTO;
+
+export type TRemoveAgentVaultProductMemberDTO = TAgentVaultProductActor & {
+ projectId: string;
+ ctx: TAgentVaultActorContext;
+};
+
+export type TAddAgentVaultProductUserMembersDTO = {
+ projectId: string;
+ userIds: string[];
+ emails: string[];
+ role: ProjectMembershipRole.Admin | ProjectMembershipRole.Member;
+ ctx: TAgentVaultActorContext;
+};
+
+const VALID_PRODUCT_ROLES: string[] = [ProjectMembershipRole.Admin, ProjectMembershipRole.Member];
+
+export const agentVaultMembershipServiceFactory = ({
+ membershipDAL,
+ identityDAL,
+ membershipRoleDAL,
+ groupDAL,
+ projectAccessRequestDAL,
+ userDAL,
+ userAliasDAL,
+ orgDAL,
+ permissionService,
+ usageMeteringService
+}: TAgentVaultMembershipServiceFactoryDep) => {
+ const getActorPermission = (projectId: string, ctx: TAgentVaultActorContext) =>
+ permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+
+ const checkProductAdmin = async (projectId: string, ctx: TAgentVaultActorContext) => {
+ const { hasRole } = await getActorPermission(projectId, ctx);
+ if (!hasRole(ProjectMembershipRole.Admin)) {
+ throw new ForbiddenRequestError({ message: "Only Agent Vault admins can perform this action" });
+ }
+ };
+
+ const addProductUserMembers = async ({
+ projectId,
+ userIds,
+ emails,
+ role,
+ ctx
+ }: TAddAgentVaultProductUserMembersDTO) => {
+ await checkProductAdmin(projectId, ctx);
+
+ if (!VALID_PRODUCT_ROLES.includes(role)) {
+ throw new BadRequestError({
+ message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`
+ });
+ }
+
+ const usersByEmail = emails.length ? await userDAL.find({ $in: { username: emails } }) : [];
+ const userByEmail = new Map(usersByEmail.map((u) => [u.username, u]));
+
+ // The invite this accompanies resolves IdP identifiers through SSO aliases, so this half has to as well.
+ const unmatched = emails.filter((e) => !userByEmail.has(e));
+ if (unmatched.length) {
+ const org = await orgDAL.findById(ctx.actorOrgId);
+ const { resolved, ambiguousIdentifiers } = await resolveUsersBySsoExternalId({
+ identifiers: unmatched,
+ orgId: ctx.actorOrgId,
+ rootOrgId: org?.rootOrgId,
+ userAliasDAL,
+ userDAL
+ });
+
+ if (ambiguousIdentifiers.length) {
+ throw new BadRequestError({
+ message: `Identifier(s) ${ambiguousIdentifiers
+ .map((el) => `'${el}'`)
+ .join(
+ ", "
+ )} match more than one SSO account in this organization. Use the user's email address instead, or contact support to resolve the duplicate.`
+ });
+ }
+
+ resolved.forEach((user, identifier) => userByEmail.set(identifier, user));
+ }
+
+ const unresolved = emails.filter((e) => !userByEmail.has(e));
+
+ const candidates: { userId: string; label: string }[] = [];
+ const seen = new Set<string>();
+ for (const id of userIds) {
+ if (!seen.has(id)) {
+ seen.add(id);
+ candidates.push({ userId: id, label: id });
+ }
+ }
+ for (const email of emails) {
+ const user = userByEmail.get(email);
+ if (user && !seen.has(user.id)) {
+ seen.add(user.id);
+ candidates.push({ userId: user.id, label: email });
+ }
+ }
+
+ const existing = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });
+ const alreadyAttached = new Set(existing.map((m) => m.actorUserId).filter((v): v is string => Boolean(v)));
+ const skipped: string[] = [];
+
+ const orgMemberships = candidates.length
+ ? await membershipDAL.find({
+ scope: AccessScope.Organization,
+ scopeOrgId: ctx.actorOrgId,
+ isActive: true,
+ $in: { actorUserId: candidates.map((c) => c.userId) }
+ })
+ : [];
+ const orgMemberIds = new Set(orgMemberships.map((m) => m.actorUserId));
+
+ const toCreate = candidates.filter((c) => {
+ if (!orgMemberIds.has(c.userId)) {
+ unresolved.push(c.label);
+ return false;
+ }
+ if (alreadyAttached.has(c.userId)) {
+ skipped.push(c.label);
+ return false;
+ }
+ return true;
+ });
+
+ if (unresolved.length) {
+ const rejected = unresolved.map((el) => `'${el}'`).join(", ");
+ throw new BadRequestError({
+ message: `Cannot add ${rejected} to Agent Vault because they are not an active member of this organization. Invite them to the organization first.`
+ });
+ }
+
+ const memberships = await membershipDAL.transaction(async (tx) => {
+ const results: { membershipId: string; userId: string; userName?: string; role: string; createdAt: Date }[] = [];
+ for (const { userId, label } of toCreate) {
+ // eslint-disable-next-line no-await-in-loop
+ const membership = await membershipDAL.create(
+ {
+ scope: AccessScope.Project,
+ scopeOrgId: ctx.actorOrgId,
+ scopeProjectId: projectId,
+ actorUserId: userId,
+ isActive: true
+ },
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop
+ const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);
+ // eslint-disable-next-line no-await-in-loop
+ await projectAccessRequestDAL.delete({ projectId, requesterUserId: userId }, tx);
+ results.push({
+ userName: label.includes("@") ? label : undefined,
+ membershipId: membership.id,
+ userId,
+ role: membershipRole.role,
+ createdAt: membership.createdAt
+ });
+ }
+ return results;
+ });
+
+ if (memberships.length > 0) {
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
+ }
+
+ return { memberships, skipped };
+ };
+
+ const resolveMemberships = async (memberships: Awaited<ReturnType<typeof membershipDAL.find>>) => {
+ if (!memberships.length) return [];
+
+ const roles = await membershipRoleDAL.find({ $in: { membershipId: memberships.map((m) => m.id) } });
+ const roleByMembership = new Map(roles.map((r) => [r.membershipId, r]));
+
+ return memberships.map((m) => {
+ const role = roleByMembership.get(m.id);
+ return {
+ membershipId: m.id,
+ userId: m.actorUserId ?? null,
+ identityId: m.actorIdentityId ?? null,
+ groupId: m.actorGroupId ?? null,
+ role: role?.role ?? ProjectMembershipRole.Member,
+ isActive: m.isActive,
+ createdAt: m.createdAt
+ };
+ });
+ };
+
+ const listProductUserMembers = async ({ projectId, ctx }: TListAgentVaultProductMembersDTO) => {
+ const { permission } = await getActorPermission(projectId, ctx);
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member);
+
+ const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });
+ const resolved = await resolveMemberships(memberships.filter((m) => m.actorUserId));
+
+ const userIds = resolved.map((m) => m.userId).filter((v): v is string => Boolean(v));
+ if (!userIds.length) return [];
+ const [users, orgMemberships] = await Promise.all([
+ userDAL.find({ $in: { id: userIds } }),
+ membershipDAL.find({ scope: AccessScope.Organization, scopeOrgId: ctx.actorOrgId, $in: { actorUserId: userIds } })
+ ]);
+ const userById = new Map(users.map((u) => [u.id, u]));
+ const orgStatusByUser = new Map(orgMemberships.map((m) => [m.actorUserId, m.status]));
+
+ return resolved.map((m) => {
+ const user = m.userId ? userById.get(m.userId) : undefined;
+ return {
+ ...m,
+ email: user?.email ?? null,
+ username: user?.username ?? "",
+ firstName: user?.firstName ?? null,
+ lastName: user?.lastName ?? null,
+ isOrgMembershipPending: orgStatusByUser.get(m.userId ?? "") === OrgMembershipStatus.Invited
+ };
+ });
+ };
+
+ const listProductGroupMembers = async ({ projectId, ctx }: TListAgentVaultProductMembersDTO) => {
+ const { permission } = await getActorPermission(projectId, ctx);
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionGroupActions.Read, ProjectPermissionSub.Groups);
+
+ const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });
+ const resolved = await resolveMemberships(memberships.filter((m) => m.actorGroupId));
+
+ const groupIds = resolved.map((m) => m.groupId).filter((v): v is string => Boolean(v));
+ const groups = groupIds.length ? await groupDAL.find({ $in: { id: groupIds } }) : [];
+ const groupById = new Map(groups.map((g) => [g.id, g]));
+
+ return resolved.map((m) => ({ ...m, name: (m.groupId && groupById.get(m.groupId)?.name) || "" }));
+ };
+
+ const listProductIdentityMembers = async ({ projectId, ctx }: TListAgentVaultProductMembersDTO) => {
+ const { permission } = await getActorPermission(projectId, ctx);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionIdentityActions.Read,
+ ProjectPermissionSub.Identity
+ );
+
+ const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });
+ const identityMemberships = memberships.filter((m) => m.actorIdentityId);
+ const resolved = await resolveMemberships(identityMemberships);
+
+ const identityIds = resolved.map((m) => m.identityId).filter((v): v is string => Boolean(v));
+ const identities = identityIds.length ? await identityDAL.find({ $in: { id: identityIds } }) : [];
+ const identityById = new Map(identities.map((i) => [i.id, i]));
+
+ return resolved.map((m) => {
+ const identity = m.identityId ? identityById.get(m.identityId) : undefined;
+ return {
+ ...m,
+ name: identity?.name ?? "",
+ identityProjectId: identity?.projectId ?? null,
+ identityOrgId: identity?.orgId ?? null
+ };
+ });
+ };
+
+ const resolveActorColumn = (dto: { userId?: string; groupId?: string; identityId?: string }) => {
+ if (dto.userId) return { column: "actorUserId" as const, id: dto.userId, label: "User" };
+ if (dto.groupId) return { column: "actorGroupId" as const, id: dto.groupId, label: "Group" };
+ if (dto.identityId) return { column: "actorIdentityId" as const, id: dto.identityId, label: "Machine identity" };
+ throw new BadRequestError({ message: "Name exactly one user, group or machine identity" });
+ };
+
+ const assertValidRole = (role: string) => {
+ if (!VALID_PRODUCT_ROLES.includes(role)) {
+ throw new BadRequestError({
+ message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`
+ });
+ }
+ };
+
+ // resolveSession refuses an actor without an active org membership, so a member added without one could never mint.
+ const assertActorIsInOrg = async (
+ dto: { userId?: string; groupId?: string; identityId?: string },
+ orgId: string,
+ projectId: string,
+ label: string
+ ) => {
+ if (dto.groupId) {
+ const [group] = await groupDAL.find({ id: dto.groupId, orgId });
+ if (!group) throw new NotFoundError({ message: `Group with ID '${dto.groupId}' not found` });
+ return;
+ }
+ if (dto.identityId) {
+ const [identity] = await identityDAL.find({ id: dto.identityId, orgId });
+ if (!identity) throw new NotFoundError({ message: `Machine identity with ID '${dto.identityId}' not found` });
+ // An identity created inside another product still carries an org-scope NoAccess membership, so the
+ // org check below passes for it. Only Agent Vault's own identities and unscoped org ones belong here.
+ if (identity.projectId && identity.projectId !== projectId) {
+ throw new BadRequestError({
+ message: `Machine identity with ID '${dto.identityId}' belongs to another project and cannot be given Agent Vault access`
+ });
+ }
+ }
+
+ const actorId = dto.userId ?? dto.identityId!;
+ // Status is not required: an org invite that has not been accepted still gets project access
+ // everywhere else on the platform, and resolveSession refuses the actor until it is. isActive is the
+ // real gate, so a deactivated member is still refused.
+ const membership = await orgDAL.findEffectiveOrgMembership({
+ actorType: dto.userId ? ActorType.USER : ActorType.IDENTITY,
+ actorId,
+ orgId,
+ acceptAnyStatus: true
+ });
+ if (!membership?.isActive) {
+ throw new BadRequestError({
+ message: `Cannot add ${label.toLowerCase()} '${actorId}' to Agent Vault because they are not an active member of this organization. Invite them to the organization first.`
+ });
+ }
+ };
+
+ const resolveActorLabel = async (dto: { userId?: string; groupId?: string; identityId?: string }) => {
+ if (dto.groupId) {
+ const [group] = await groupDAL.find({ id: dto.groupId });
+ return { groupName: group?.name };
+ }
+ if (dto.identityId) {
+ const [identity] = await identityDAL.find({ id: dto.identityId });
+ return { identityName: identity?.name };
+ }
+ const [user] = dto.userId ? await userDAL.find({ id: dto.userId }) : [];
+ return { userName: user?.username };
+ };
+
+ const addProductMember = async ({ projectId, role, ctx, ...dto }: TAddAgentVaultProductMemberDTO) => {
+ await checkProductAdmin(projectId, ctx);
+ assertValidRole(role);
+
+ const { column, id, label } = resolveActorColumn(dto);
+ await assertActorIsInOrg(dto, ctx.actorOrgId, projectId, label);
+
+ const result = await membershipDAL.transaction(async (tx) => {
+ const existing = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ if (existing.length) {
+ throw new BadRequestError({ message: `${label} already has access to Agent Vault` });
+ }
+
+ const membership = await membershipDAL.create(
+ {
+ scope: AccessScope.Project,
+ scopeOrgId: ctx.actorOrgId,
+ scopeProjectId: projectId,
+ [column]: id,
+ isActive: true
+ },
+ tx
+ );
+ const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);
+
+ if (dto.userId) await projectAccessRequestDAL.delete({ projectId, requesterUserId: dto.userId }, tx);
+
+ return { membershipId: membership.id, ...dto, role: membershipRole.role, createdAt: membership.createdAt };
+ });
+
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
+ return { ...result, ...(await resolveActorLabel(dto)) };
+ };
+
+ const updateProductMemberRole = async ({ projectId, role, ctx, ...dto }: TUpdateAgentVaultProductMemberDTO) => {
+ await checkProductAdmin(projectId, ctx);
+ assertValidRole(role);
+
+ if ((dto.userId && dto.userId === ctx.actorId) || (dto.identityId && dto.identityId === ctx.actorId)) {
+ throw new ForbiddenRequestError({ message: "You cannot change your own role" });
+ }
+
+ const { column, id, label } = resolveActorColumn(dto);
+ // The add paths check this; promoting did not, so a deactivated member could still be made an admin.
+ await assertActorIsInOrg(dto, ctx.actorOrgId, projectId, label);
+
+ const updated = await membershipDAL.transaction(async (tx) => {
+ const [membership] = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ if (!membership) throw new NotFoundError({ message: `${label} does not have access to Agent Vault` });
+
+ if (role !== ProjectMembershipRole.Admin) {
+ await assertWillRetainProjectAdmin({
+ scopeProjectId: projectId,
+ excludeMembershipIds: [membership.id],
+ productLabel: "Agent Vault",
+ tx
+ });
+ }
+
+ await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
+ const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);
+
+ return { membershipId: membership.id, ...dto, role: membershipRole.role };
+ });
+
+ return { ...updated, ...(await resolveActorLabel(dto)) };
+ };
+
+ const removeProductMember = async ({ projectId, ctx, ...dto }: TRemoveAgentVaultProductMemberDTO) => {
+ await checkProductAdmin(projectId, ctx);
+
+ if ((dto.userId && dto.userId === ctx.actorId) || (dto.identityId && dto.identityId === ctx.actorId)) {
+ throw new ForbiddenRequestError({ message: "You cannot remove your own access" });
+ }
+
+ const { column, id, label } = resolveActorColumn(dto);
+
+ // An identity scoped to this project exists only to be an Agent Vault member. Detaching it would leave
+ // a live identity no screen can reach: this tab lists by membership, and the org list hides scoped ones.
+ if (dto.identityId) {
+ const [identity] = await identityDAL.find({ id: dto.identityId });
+ if (identity?.projectId === projectId) {
+ throw new BadRequestError({
+ message: `Machine identity with ID '${dto.identityId}' is managed by Agent Vault. Delete the identity instead of removing its access`
+ });
+ }
+ }
+
+ const membershipId = await membershipDAL.transaction(async (tx) => {
+ const [membership] = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ if (!membership) throw new NotFoundError({ message: `${label} does not have access to Agent Vault` });
+
+ await assertWillRetainProjectAdmin({
+ scopeProjectId: projectId,
+ excludeMembershipIds: [membership.id],
+ productLabel: "Agent Vault",
+ tx
+ });
+
+ await membershipDAL.delete({ scope: RESOURCE_SCOPE, scopeProjectId: projectId, [column]: id }, tx);
+
+ await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
+ await membershipDAL.deleteById(membership.id, tx);
+
+ return membership.id;
+ });
+
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
+ return { membershipId, ...dto, ...(await resolveActorLabel(dto)) };
+ };
+
+ return {
+ addProductUserMembers,
+ listProductUserMembers,
+ listProductGroupMembers,
+ listProductIdentityMembers,
+ addProductMember,
+ updateProductMemberRole,
+ removeProductMember
+ };
+};
diff --git a/backend/src/ee/services/agent-vault-project/agent-vault-project-bootstrap.ts b/backend/src/ee/services/agent-vault-project/agent-vault-project-bootstrap.ts
new file mode 100644
index 0000000000..0cc0d8836a
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-project/agent-vault-project-bootstrap.ts
@@ -0,0 +1,77 @@
+import slugify from "@sindresorhus/slugify";
+import { Knex } from "knex";
+
+import { AccessScope, ProjectMembershipRole, ProjectType, ProjectVersion, TProjects } from "@app/db/schemas";
+import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+type TBootstrapDeps = {
+ projectDAL: Pick<TProjectDALFactory, "create" | "findOne">;
+ membershipDAL: Pick<TMembershipDALFactory, "create">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create">;
+};
+
+type TBootstrapInput = {
+ orgId: string;
+ adminUserIds?: string[];
+ adminIdentityIds?: string[];
+ adminGroupIds?: string[];
+};
+
+export const bootstrapAgentVaultProject = async (
+ { orgId, adminUserIds = [], adminIdentityIds = [], adminGroupIds = [] }: TBootstrapInput,
+ { projectDAL, membershipDAL, membershipRoleDAL }: TBootstrapDeps,
+ tx: Knex
+): Promise<{ project: TProjects; created: boolean }> => {
+ const existing = await projectDAL.findOne({ orgId, type: ProjectType.AgentVault }, tx);
+ if (existing) {
+ return { project: existing, created: false };
+ }
+
+ const slug = slugify(`agent-vault-${alphaNumericNanoId(4)}`);
+
+ const project = await projectDAL.create(
+ {
+ name: "Agent Vault",
+ slug,
+ type: ProjectType.AgentVault,
+ orgId,
+ version: ProjectVersion.V3,
+ pitVersionLimit: 10
+ },
+ tx
+ );
+
+ const adminActors: Array<{ actorUserId: string } | { actorIdentityId: string } | { actorGroupId: string }> = [
+ ...adminUserIds.map((actorUserId) => ({ actorUserId })),
+ ...adminIdentityIds.map((actorIdentityId) => ({ actorIdentityId })),
+ ...adminGroupIds.map((actorGroupId) => ({ actorGroupId }))
+ ];
+
+ for (const actor of adminActors) {
+ // eslint-disable-next-line no-await-in-loop
+ const membership = await membershipDAL.create(
+ {
+ scope: AccessScope.Project,
+ scopeOrgId: orgId,
+ scopeProjectId: project.id,
+ ...actor,
+ isActive: true
+ },
+ tx
+ );
+
+ // eslint-disable-next-line no-await-in-loop
+ await membershipRoleDAL.create(
+ {
+ membershipId: membership.id,
+ role: ProjectMembershipRole.Admin
+ },
+ tx
+ );
+ }
+
+ return { project, created: true };
+};
diff --git a/backend/src/ee/services/agent-vault-project/agent-vault-project-resolver.ts b/backend/src/ee/services/agent-vault-project/agent-vault-project-resolver.ts
new file mode 100644
index 0000000000..3ed8af190f
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-project/agent-vault-project-resolver.ts
@@ -0,0 +1,68 @@
+import { Knex } from "knex";
+
+import { ProjectType } from "@app/db/schemas";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { withCache } from "@app/lib/cache/with-cache";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+import { bootstrapAgentVaultProject } from "./agent-vault-project-bootstrap";
+
+type TResolverDeps = {
+ db: Knex;
+ projectDAL: Pick<TProjectDALFactory, "find" | "findOne" | "create">;
+ membershipDAL: Pick<TMembershipDALFactory, "create">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
+};
+
+export type TAgentVaultProjectResolverFactory = ReturnType<typeof agentVaultProjectResolverFactory>;
+
+export const agentVaultProjectResolverFactory = ({
+ db,
+ projectDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ keyStore
+}: TResolverDeps) => {
+ const findDefaultProjectId = async (orgId: string, tx?: Knex): Promise<string | null> => {
+ const projects = await projectDAL.find(
+ { orgId, type: ProjectType.AgentVault },
+ { sort: [["createdAt", "desc"]], limit: 1, tx }
+ );
+ return projects.length ? projects[0].id : null;
+ };
+
+ const ensureDefaultProject = async (orgId: string): Promise<string> =>
+ db.transaction(async (tx) => {
+ // Serialize concurrent bootstraps; a unique constraint won't work since zombie projects share type=agent-vault.
+ await tx.raw("SELECT pg_advisory_xact_lock(hashtext(?))", [`agent-vault-bootstrap:${orgId}`]);
+
+ const existingId = await findDefaultProjectId(orgId, tx);
+ if (existingId) return existingId;
+
+ // The project starts with no members. Org admins join themselves through grant-admin-access the
+ // first time they open the product, which is also the only path for admins promoted later.
+ const { project } = await bootstrapAgentVaultProject(
+ { orgId },
+ { projectDAL, membershipDAL, membershipRoleDAL },
+ tx
+ );
+ return project.id;
+ });
+
+ return {
+ resolve: (actorOrgId: string): Promise<string> =>
+ withCache({
+ keyStore,
+ key: KeyStorePrefixes.AgentVaultDefaultProject(actorOrgId),
+ ttlSeconds: KeyStoreTtls.AgentVaultDefaultProjectInSeconds,
+ fetcher: async () => {
+ const existingId = await findDefaultProjectId(actorOrgId);
+ if (existingId) return existingId;
+ return ensureDefaultProject(actorOrgId);
+ }
+ })
+ };
+};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-ca-fns.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-ca-fns.ts
new file mode 100644
index 0000000000..350bd2de6d
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-ca-fns.ts
@@ -0,0 +1,56 @@
+import * as x509 from "@peculiar/x509";
+
+import { crypto } from "@app/lib/crypto";
+import { BadRequestError } from "@app/lib/errors";
+
+export type TParsedRootCa = {
+ fingerprint: string;
+ expiresAt: Date;
+};
+
+const MAX_ROOT_CA_PEM_LENGTH = 16384;
+
+/** Derives the fingerprint and expiry once, at enrollment; the certificate itself is never stored. */
+export const parseRootCaCertificate = (pem: string): TParsedRootCa => {
+ if (pem.length > MAX_ROOT_CA_PEM_LENGTH) {
+ throw new BadRequestError({ message: "The certificate authority is too large to be a valid CA certificate" });
+ }
+
+ let certificate: x509.X509Certificate;
+ try {
+ certificate = new x509.X509Certificate(pem);
+ } catch {
+ throw new BadRequestError({
+ message: "The certificate authority is not a valid PEM certificate. Send the proxy's ca.crt exactly as written."
+ });
+ }
+
+ const basicConstraints = certificate.getExtension(x509.BasicConstraintsExtension);
+ if (!basicConstraints?.ca) {
+ throw new BadRequestError({
+ message:
+ "The certificate is not a certificate authority. A proxy enrolls with its own CA, not a leaf certificate."
+ });
+ }
+
+ if (certificate.notAfter <= new Date()) {
+ throw new BadRequestError({
+ message: `The certificate authority expired on ${certificate.notAfter.toISOString()}. Generate a new one and enroll again.`
+ });
+ }
+
+ if (certificate.notBefore > new Date()) {
+ throw new BadRequestError({
+ message: `The certificate authority is not valid until ${certificate.notBefore.toISOString()}. Nothing will accept the certificates it signs before then.`
+ });
+ }
+
+ const digest = crypto.nativeCrypto
+ .createHash("sha256")
+ .update(Buffer.from(certificate.rawData))
+ .digest("hex")
+ .toUpperCase();
+ const fingerprint = `SHA256:${digest.match(/.{2}/g)!.join(":")}`;
+
+ return { fingerprint, expiresAt: certificate.notAfter };
+};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts
new file mode 100644
index 0000000000..740df9786c
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts
@@ -0,0 +1,68 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAgentVaultProxies } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TAgentVaultProxyDALFactory = ReturnType<typeof agentVaultProxyDALFactory>;
+
+export type TAgentVaultProxyWithOrg = TAgentVaultProxies & { orgId: string };
+
+export const agentVaultProxyDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultProxy);
+
+ // loginWithToken refuses a null orgId, so this path joins projects rather than denormalising a column.
+ const findByIdWithOrg = async (id: string, tx?: Knex): Promise<TAgentVaultProxyWithOrg | undefined> => {
+ try {
+ const row = (await (tx || db.replicaNode())(TableName.AgentVaultProxy)
+ .where(`${TableName.AgentVaultProxy}.id`, id)
+ .join(TableName.Project, `${TableName.AgentVaultProxy}.projectId`, `${TableName.Project}.id`)
+ .select(db.ref("orgId").withSchema(TableName.Project))
+ .select(`${TableName.AgentVaultProxy}.*`)
+ .first()) as TAgentVaultProxyWithOrg | undefined;
+ return row;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault proxy with org" });
+ }
+ };
+
+ const findByIdInProject = async (
+ { id, projectId }: { id: string; projectId: string },
+ tx?: Knex
+ ): Promise<TAgentVaultProxies | undefined> => {
+ try {
+ return await (tx || db.replicaNode())(TableName.AgentVaultProxy).where({ id, projectId }).first();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault proxy by id" });
+ }
+ };
+
+ const findForProject = async (projectId: string, tx?: Knex): Promise<TAgentVaultProxies[]> => {
+ try {
+ return (await (tx || db.replicaNode())(TableName.AgentVaultProxy)
+ .where({ projectId })
+ .orderBy("name", "asc")) as TAgentVaultProxies[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault proxies" });
+ }
+ };
+
+ // heartbeatTTL is copied from the row's own pollInterval in the same statement, so it records the
+ // interval the proxy is about to be handed back rather than whatever the settings said earlier.
+ const recordHeartbeat = async (id: string, tx?: Knex): Promise<TAgentVaultProxies | undefined> => {
+ try {
+ // Raw because the typed update builder will not take a column reference as a value, and copying
+ // pollInterval across in one statement is the point: two statements could straddle a settings save.
+ const updated = await (tx || db).raw<{ rows: TAgentVaultProxies[] }>(
+ `UPDATE ?? SET "heartbeat" = ?, "heartbeatTTL" = "pollInterval" WHERE "id" = ? RETURNING *`,
+ [TableName.AgentVaultProxy, new Date(), id]
+ );
+ return updated.rows[0];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Record agent vault proxy heartbeat" });
+ }
+ };
+
+ return { ...orm, findByIdWithOrg, findByIdInProject, findForProject, recordHeartbeat };
+};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
new file mode 100644
index 0000000000..a43d1cd826
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
@@ -0,0 +1,422 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, OrgMembershipStatus, ProjectMembershipRole, TAgentVaultProxies } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionAgentVaultProxyActions,
+ ProjectPermissionAgentVaultSessionActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import {
+ BadRequestError,
+ ForbiddenRequestError,
+ InternalServerError,
+ NotFoundError,
+ UnauthorizedError
+} from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+
+import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";
+import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";
+import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";
+import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";
+import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";
+import { RESOURCE_TYPE_AGENT_VAULT_PROXY } from "../resource-auth-method/resource-auth-method-fns";
+import { TResourceAuthMethodServiceFactory } from "../resource-auth-method/resource-auth-method-service";
+import { parseRootCaCertificate } from "./agent-vault-ca-fns";
+import { TAgentVaultProxyDALFactory } from "./agent-vault-proxy-dal";
+import {
+ TAgentVaultProxyConfig,
+ TCreateProxyDTO,
+ TEnrollProxyDTO,
+ THeartbeatDTO,
+ TListProxiesDTO,
+ TProxyByIdDTO,
+ TResolvedService,
+ TResolveSessionDTO,
+ TUpdateProxyDTO
+} from "./agent-vault-proxy-types";
+import { TAgentVaultResolveDALFactory } from "./agent-vault-resolve-dal";
+
+// Health is derived from the last heartbeat and the poll interval, never stored.
+const HEARTBEAT_MISSES_BEFORE_UNHEALTHY = 3;
+
+type TAgentVaultProxyServiceFactoryDep = {
+ agentVaultProxyDAL: TAgentVaultProxyDALFactory;
+ agentVaultResolveDAL: TAgentVaultResolveDALFactory;
+ agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;
+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+ orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ resourceAuthMethodService: Pick<
+ TResourceAuthMethodServiceFactory,
+ "initAtCreate" | "mintToken" | "loginWithToken" | "revokeAccess"
+ >;
+};
+
+export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;
+
+export const agentVaultProxyServiceFactory = ({
+ agentVaultProxyDAL,
+ agentVaultResolveDAL,
+ agentVaultSessionDAL,
+ membershipDAL,
+ orgDAL,
+ permissionService,
+ kmsService,
+ resourceAuthMethodService
+}: TAgentVaultProxyServiceFactoryDep) => {
+ const isHealthy = (proxy: Pick<TAgentVaultProxies, "heartbeat" | "pollInterval" | "heartbeatTTL">) => {
+ if (!proxy.heartbeat) return false;
+ // Judged against the interval the proxy is running, not the one an admin may have just saved: it
+ // only learns a new interval on its next poll, which is still scheduled at the old one. Lowering
+ // the interval would otherwise report a live proxy as unreachable until that poll landed.
+ const interval = proxy.heartbeatTTL ?? proxy.pollInterval;
+ return proxy.heartbeat.getTime() > Date.now() - interval * HEARTBEAT_MISSES_BEFORE_UNHEALTHY * 1000;
+ };
+
+ const toConfig = (proxy: TAgentVaultProxies): TAgentVaultProxyConfig => ({
+ trafficPolicy: proxy.trafficPolicy as AgentVaultTrafficPolicy,
+ allowedHosts: proxy.allowedHosts ?? null,
+ pollInterval: proxy.pollInterval
+ });
+
+ const toMemberView = (proxy: TAgentVaultProxies) => ({
+ id: proxy.id,
+ name: proxy.name,
+ heartbeat: proxy.heartbeat ?? null,
+ isHealthy: isHealthy(proxy),
+ rootCaFingerprint: proxy.rootCaFingerprint ?? null,
+ rootCaExpiresAt: proxy.rootCaExpiresAt ?? null
+ });
+
+ const toAdminView = (proxy: TAgentVaultProxies) => ({
+ ...toMemberView(proxy),
+ ...toConfig(proxy),
+ createdAt: proxy.createdAt
+ });
+
+ const $authorize = async ({ projectId, ctx }: TListProxiesDTO, action: ProjectPermissionAgentVaultProxyActions) => {
+ const { permission, hasRole } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+ ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.AgentVaultProxies);
+ return { isAdmin: hasRole(ProjectMembershipRole.Admin) };
+ };
+
+ const $findProxyOr404 = async ({ projectId, proxyId }: { projectId: string; proxyId: string }) => {
+ const proxy = await agentVaultProxyDAL.findByIdInProject({ id: proxyId, projectId });
+ if (!proxy) throw new NotFoundError({ message: `Proxy with ID '${proxyId}' not found` });
+ return proxy;
+ };
+
+ const getProxyForAuth = (proxyId: string) => agentVaultProxyDAL.findByIdWithOrg(proxyId);
+
+ const listProxies = async (dto: TListProxiesDTO) => {
+ const { isAdmin } = await $authorize(dto, ProjectPermissionAgentVaultProxyActions.Read);
+ const proxies = await agentVaultProxyDAL.findForProject(dto.projectId);
+ return proxies.map((proxy) => (isAdmin ? toAdminView(proxy) : toMemberView(proxy)));
+ };
+
+ const $resourceActor = (ctx: TCreateProxyDTO["ctx"]) => ({
+ type: ctx.actor,
+ id: ctx.actorId,
+ orgId: ctx.actorOrgId,
+ rootOrgId: ctx.actorOrgId,
+ parentOrgId: ctx.actorOrgId,
+ authMethod: ctx.actorAuthMethod
+ });
+
+ // The first token belongs to creating the proxy; a replacement is its own permission, since enrolling
+ // again rotates the CA and breaks every agent that trusted the old one.
+ const $issueEnrollmentToken = async (proxyId: string, ctx: TCreateProxyDTO["ctx"], intent: "create" | "issue") => {
+ const enrollment = await resourceAuthMethodService.mintToken({
+ resource: { type: RESOURCE_TYPE_AGENT_VAULT_PROXY, id: proxyId },
+ actor: $resourceActor(ctx),
+ intent
+ });
+ return { token: enrollment.token, expiresAt: enrollment.expiresAt };
+ };
+
+ const createProxy = async ({ projectId, ctx, name, ...settings }: TCreateProxyDTO) => {
+ await $authorize({ projectId, ctx }, ProjectPermissionAgentVaultProxyActions.Create);
+
+ const existing = await agentVaultProxyDAL.findOne({ projectId, name });
+ if (existing) throw new BadRequestError({ message: `A proxy named '${name}' already exists` });
+
+ const create = () =>
+ agentVaultProxyDAL.transaction(async (tx) => {
+ const created = await agentVaultProxyDAL.create(
+ {
+ projectId,
+ name,
+ trafficPolicy: settings.trafficPolicy ?? AgentVaultTrafficPolicy.AnyHost,
+ allowedHosts: settings.allowedHosts ?? null,
+ pollInterval: settings.pollInterval ?? 60
+ },
+ tx
+ );
+
+ await resourceAuthMethodService.initAtCreate(
+ { resource: { type: RESOURCE_TYPE_AGENT_VAULT_PROXY, id: created.id }, authMethod: { method: "token" } },
+ tx
+ );
+
+ return created;
+ });
+
+ let proxy;
+ try {
+ proxy = await create();
+ } catch (err) {
+ if (isUniqueViolation(err)) throw new BadRequestError({ message: `A proxy named '${name}' already exists` });
+ throw err;
+ }
+
+ // Outside the transaction: minting hits KMS.
+ const enrollment = await $issueEnrollmentToken(proxy.id, ctx, "create");
+ return { proxy: toAdminView(proxy), enrollment };
+ };
+
+ // Does NOT bump tokenVersion, so a running proxy keeps serving until the replacement enrolls.
+ const reissueEnrollmentToken = async ({ projectId, ctx, proxyId }: TProxyByIdDTO) => {
+ await $authorize({ projectId, ctx }, ProjectPermissionAgentVaultProxyActions.IssueToken);
+ const proxy = await $findProxyOr404({ projectId, proxyId });
+ const enrollment = await $issueEnrollmentToken(proxy.id, ctx, "issue");
+ return { proxy: toAdminView(proxy), enrollment };
+ };
+
+ const updateProxy = async ({ projectId, ctx, proxyId, name, ...settings }: TUpdateProxyDTO) => {
+ await $authorize({ projectId, ctx }, ProjectPermissionAgentVaultProxyActions.Edit);
+ const proxy = await $findProxyOr404({ projectId, proxyId });
+
+ if (name && name !== proxy.name) {
+ const existing = await agentVaultProxyDAL.findOne({ projectId, name });
+ if (existing) throw new BadRequestError({ message: `A proxy named '${name}' already exists` });
+ }
+
+ try {
+ const updated = await agentVaultProxyDAL.updateById(proxy.id, { name, ...settings });
+ return toAdminView(updated);
+ } catch (err) {
+ if (isUniqueViolation(err)) throw new BadRequestError({ message: `A proxy named '${name}' already exists` });
+ throw err;
+ }
+ };
+
+ const deleteProxy = async ({ projectId, ctx, proxyId }: TProxyByIdDTO) => {
+ await $authorize({ projectId, ctx }, ProjectPermissionAgentVaultProxyActions.Delete);
+ const proxy = await $findProxyOr404({ projectId, proxyId });
+ await agentVaultProxyDAL.deleteById(proxy.id);
+ return { id: proxy.id, name: proxy.name };
+ };
+
+ // Through the shared revoke, which also deletes an enrollment token still waiting to be used; bumping
+ // tokenVersion alone left it able to enroll.
+ const revokeProxyAccess = async ({ projectId, ctx, proxyId }: TProxyByIdDTO) => {
+ await $authorize({ projectId, ctx }, ProjectPermissionAgentVaultProxyActions.Revoke);
+ const proxy = await $findProxyOr404({ projectId, proxyId });
+ await resourceAuthMethodService.revokeAccess({
+ resource: { type: RESOURCE_TYPE_AGENT_VAULT_PROXY, id: proxy.id },
+ actor: $resourceActor(ctx)
+ });
+ return toAdminView({ ...proxy, heartbeat: null });
+ };
+
+ const enroll = async ({ enrollmentToken, rootCaCertificate }: TEnrollProxyDTO) => {
+ // Validate the PEM before the login: loginWithToken consumes the enrollment token in-transaction.
+ const parsed = parseRootCaCertificate(rootCaCertificate);
+
+ const login = await resourceAuthMethodService.loginWithToken({
+ token: enrollmentToken,
+ expectedResourceType: RESOURCE_TYPE_AGENT_VAULT_PROXY
+ });
+
+ const before = await agentVaultProxyDAL.findByIdWithOrg(login.resourceId);
+ const proxy = await agentVaultProxyDAL.updateById(login.resourceId, {
+ rootCaFingerprint: parsed.fingerprint,
+ rootCaExpiresAt: parsed.expiresAt
+ });
+ // updateById is typed non-nullable but returns nothing when the row is gone, which a delete during
+ // the replica-lag window can produce. The CLI treats 401 as terminal and rides out a 5xx.
+ if (!proxy) throw new UnauthorizedError({ message: "This proxy no longer exists" });
+
+ return {
+ proxyId: proxy.id,
+ name: proxy.name,
+ orgId: login.orgId,
+ projectId: proxy.projectId,
+ accessToken: login.accessToken,
+ config: toConfig(proxy),
+ rootCaFingerprint: parsed.fingerprint,
+ replacedExistingCa: Boolean(before?.rootCaFingerprint)
+ };
+ };
+
+ const heartbeat = async ({ proxyId }: THeartbeatDTO) => {
+ const proxy = await agentVaultProxyDAL.recordHeartbeat(proxyId);
+ if (!proxy) throw new UnauthorizedError({ message: "This proxy no longer exists" });
+ return { config: toConfig(proxy) };
+ };
+
+ const $decryptCredential = (
+ row: { credentialType: string; credentialConfig: unknown; encryptedCredential: Buffer | null },
+ decryptor: ((input: { cipherTextBlob: Buffer }) => Buffer) | null
+ ): TResolvedService["credential"] => {
+ const config = (row.credentialConfig ?? {}) as Record<string, string>;
+ if (row.credentialType === AgentVaultCredentialType.Passthrough || !row.encryptedCredential) {
+ return { type: "passthrough" };
+ }
+ if (!decryptor) throw new InternalServerError({ message: "Failed to resolve the session's credentials" });
+
+ const secret = JSON.parse(decryptor({ cipherTextBlob: row.encryptedCredential }).toString("utf-8")) as Record<
+ string,
+ string
+ >;
+
+ if (row.credentialType === AgentVaultCredentialType.Bearer) {
+ return {
+ type: "bearer",
+ headerName: config.headerName,
+ headerPrefix: config.headerPrefix,
+ value: secret.value
+ };
+ }
+ return { type: "basic", username: secret.username ?? "", password: secret.password ?? "" };
+ };
+
+ /** The only endpoint that decrypts a credential. The proxy's JWT authorizes; the session token is a selector. */
+ const resolveSession = async ({ proxyId, orgId, sessionToken }: TResolveSessionDTO) => {
+ const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));
+ if (!session) throw new NotFoundError({ message: "Session not found" });
+
+ // A mismatch is 404, not 403, so a proxy cannot probe another tenant for session ids.
+ const proxy = await agentVaultProxyDAL.findByIdWithOrg(proxyId);
+ if (!proxy || proxy.projectId !== session.projectId || proxy.orgId !== orgId) {
+ throw new NotFoundError({ message: "Session not found" });
+ }
+
+ if (session.revokedAt) throw new UnauthorizedError({ message: "Session revoked" });
+ if (session.expiresAt && session.expiresAt <= new Date()) {
+ throw new UnauthorizedError({ message: "Session expired" });
+ }
+ // The actor columns are SET NULL so the row outlives its owner for history. A null id must not reach the
+ // lookups below: knex compiles `where col = null` to `IS NULL`, which matches every user row and made an
+ // ownerless session resolve as an admin.
+ if (!session.userId && !session.identityId) {
+ throw new UnauthorizedError({ message: "The identity this session belonged to has been deleted" });
+ }
+
+ const actor = session.userId
+ ? { type: ActorType.USER as const, id: session.userId }
+ : { type: ActorType.IDENTITY as const, id: session.identityId! };
+
+ // Deactivation writes isActive on the org-scope membership row, which getProjectPermission never reads.
+ const orgMembership = await orgDAL.findEffectiveOrgMembership({
+ actorType: actor.type,
+ actorId: actor.id,
+ orgId,
+ status: OrgMembershipStatus.Accepted
+ });
+ if (!orgMembership?.isActive) {
+ throw new UnauthorizedError({
+ message: "The identity this session belongs to is no longer active in this organization"
+ });
+ }
+
+ // The role is re-derived here, never trusted from mint, and it has to be a live role: a time-limited one
+ // leaves its row behind when it lapses. actorAuthMethod is passed as null *explicitly* — validateOrgSSO
+ // throws on `undefined` but passes on `null`, and the session row stores no auth method.
+ let isAdmin: boolean;
+ let liveGroupIds: string[];
+ try {
+ const { permission, hasRole, memberships } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: session.projectId,
+ actorAuthMethod: null,
+ actorOrgId: orgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+ if (!permission.can(ProjectPermissionAgentVaultSessionActions.Read, ProjectPermissionSub.AgentVaultSessions)) {
+ throw new UnauthorizedError({ message: "The role this session's actor held has expired" });
+ }
+ isAdmin = hasRole(ProjectMembershipRole.Admin);
+ liveGroupIds = liveGroupIdsFrom(memberships);
+ } catch (error) {
+ // A 403 reads to the proxy as "Infisical is unreachable", which would keep a removed member's agent
+ // running through its grace window.
+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") {
+ throw new UnauthorizedError({ message: "The actor no longer has Agent Vault access" });
+ }
+ throw error;
+ }
+
+ const accessBundleIds = isAdmin
+ ? null
+ : await findReachableAccessBundleIds(membershipDAL, {
+ projectId: session.projectId,
+ actor,
+ groupIds: liveGroupIds
+ });
+
+ const rows = await agentVaultResolveDAL.findResolvableServices({
+ sessionId: session.id,
+ projectId: session.projectId,
+ accessBundleIds
+ });
+
+ // A bundle of pass-through services has nothing sealed, so deriving the project data key would be
+ // a kms_keys read (or an external KMS round trip) per resolve for nothing.
+ const decryptor = rows.some((row) => row.encryptedCredential)
+ ? (
+ await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId: session.projectId
+ })
+ ).decryptor
+ : null;
+
+ const services: TResolvedService[] = rows.map((row) => ({
+ id: row.id,
+ name: row.name,
+ accessBundleName: row.accessBundleName,
+ hostPattern: row.hostPattern,
+ credential: $decryptCredential(row, decryptor)
+ }));
+
+ logger.info(
+ `agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}]`
+ );
+
+ return {
+ sessionId: session.id,
+ expiresAt: session.expiresAt ?? null,
+ services
+ };
+ };
+
+ return {
+ getProxyForAuth,
+ listProxies,
+ createProxy,
+ reissueEnrollmentToken,
+ updateProxy,
+ deleteProxy,
+ revokeProxyAccess,
+ enroll,
+ heartbeat,
+ resolveSession
+ };
+};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts
new file mode 100644
index 0000000000..d7f3f07d58
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts
@@ -0,0 +1,55 @@
+import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";
+import { AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";
+
+export type TAgentVaultProxyScoped = { projectId: string; ctx: TAgentVaultActorContext };
+
+export type TAgentVaultProxyConfig = {
+ trafficPolicy: AgentVaultTrafficPolicy;
+ allowedHosts: string | null;
+ pollInterval: number;
+};
+
+export type TListProxiesDTO = TAgentVaultProxyScoped;
+
+export type TCreateProxyDTO = TAgentVaultProxyScoped & {
+ name: string;
+ trafficPolicy?: AgentVaultTrafficPolicy;
+ allowedHosts?: string | null;
+ pollInterval?: number;
+};
+
+export type TUpdateProxyDTO = TAgentVaultProxyScoped & {
+ proxyId: string;
+ name?: string;
+ trafficPolicy?: AgentVaultTrafficPolicy;
+ allowedHosts?: string | null;
+ pollInterval?: number;
+};
+
+export type TProxyByIdDTO = TAgentVaultProxyScoped & { proxyId: string };
+
+export type TEnrollProxyDTO = {
+ enrollmentToken: string;
+ rootCaCertificate: string;
+};
+
+export type THeartbeatDTO = {
+ proxyId: string;
+};
+
+export type TResolveSessionDTO = {
+ proxyId: string;
+ orgId: string;
+ sessionToken: string;
+};
+
+export type TResolvedService = {
+ id: string;
+ name: string;
+ accessBundleName: string;
+ hostPattern: string;
+ credential:
+ | { type: "bearer"; headerName: string; headerPrefix: string; value: string }
+ | { type: "basic"; username: string; password: string }
+ | { type: "passthrough" };
+};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
new file mode 100644
index 0000000000..b73fa28d02
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
@@ -0,0 +1,80 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+
+export type TAgentVaultResolveDALFactory = ReturnType<typeof agentVaultResolveDALFactory>;
+
+export type TResolveServiceRow = {
+ id: string;
+ name: string;
+ accessBundleName: string;
+ hostPattern: string;
+ credentialType: string;
+ credentialConfig: unknown;
+ encryptedCredential: Buffer | null;
+ position: number;
+};
+
+export const agentVaultResolveDALFactory = (db: TDbClient) => {
+ /**
+ * The hot path, and an intersection: a session's bundle set is a ceiling fixed at mint, re-checked against
+ * live grants on every resolve, so losing a grant empties a running session without touching its row.
+ *
+ * Read on the replica, so replica lag adds to the one-poll-interval staleness promise.
+ */
+ const findResolvableServices = async (
+ {
+ sessionId,
+ projectId,
+ accessBundleIds
+ }: {
+ sessionId: string;
+ projectId: string;
+ accessBundleIds: string[] | null;
+ },
+ tx?: Knex
+ ): Promise<TResolveServiceRow[]> => {
+ if (accessBundleIds?.length === 0) return [];
+ try {
+ const conn = tx || db.replicaNode();
+
+ const query = conn(TableName.AgentVaultSessionAccessBundle)
+ .where(`${TableName.AgentVaultSessionAccessBundle}.sessionId`, sessionId)
+ .whereNotNull(`${TableName.AgentVaultSessionAccessBundle}.accessBundleId`)
+ .join(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultSessionAccessBundle}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ )
+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)
+ .join(
+ TableName.AgentVaultService,
+ `${TableName.AgentVaultService}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ );
+
+ if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);
+
+ return (await query
+ .select(
+ db.ref("id").withSchema(TableName.AgentVaultService),
+ db.ref("name").withSchema(TableName.AgentVaultService),
+ db.ref("hostPattern").withSchema(TableName.AgentVaultService),
+ db.ref("credentialType").withSchema(TableName.AgentVaultService),
+ db.ref("credentialConfig").withSchema(TableName.AgentVaultService),
+ db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),
+ // Resolve only reaches live bundles, so the current name is always the truthful one here.
+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName"),
+ db.ref("position").withSchema(TableName.AgentVaultSessionAccessBundle)
+ )
+ .orderBy(`${TableName.AgentVaultSessionAccessBundle}.position`, "asc")
+ .orderBy(`${TableName.AgentVaultService}.name`, "asc")) as TResolveServiceRow[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find resolvable agent vault services" });
+ }
+ };
+
+ return { findResolvableServices };
+};
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal.ts
new file mode 100644
index 0000000000..362c6d9f0a
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal.ts
@@ -0,0 +1,8 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TAgentVaultSessionAccessBundleDALFactory = ReturnType<typeof agentVaultSessionAccessBundleDALFactory>;
+
+export const agentVaultSessionAccessBundleDALFactory = (db: TDbClient) =>
+ ormify(db, TableName.AgentVaultSessionAccessBundle);
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts
new file mode 100644
index 0000000000..ed6a1dece3
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts
@@ -0,0 +1,289 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAgentVaultSessions } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { sanitizeSqlLikeString } from "@app/lib/fn/string";
+import { ormify } from "@app/lib/knex";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";
+
+export type TAgentVaultSessionDALFactory = ReturnType<typeof agentVaultSessionDALFactory>;
+
+export type TAgentVaultSessionListRow = {
+ id: string;
+ userId: string | null;
+ identityId: string | null;
+ actorName: string;
+ actorEmail: string | null;
+ expiresAt: Date | null;
+ revokedAt: Date | null;
+ createdAt: Date;
+ accessBundles: { id: string | null; name: string; position: number }[];
+};
+
+// Mirrors deriveSessionStatus: a session with neither actor id counts as revoked.
+const ownerless = (qb: Knex.QueryBuilder) =>
+ void qb.whereNull(`${TableName.AgentVaultSession}.userId`).whereNull(`${TableName.AgentVaultSession}.identityId`);
+const owned = (qb: Knex.QueryBuilder) =>
+ void qb
+ .whereNotNull(`${TableName.AgentVaultSession}.userId`)
+ .orWhereNotNull(`${TableName.AgentVaultSession}.identityId`);
+
+const statusFilter = (query: Knex.QueryBuilder, status: AgentVaultSessionStatus, now: Date) => {
+ if (status === AgentVaultSessionStatus.Revoked) {
+ void query.where((qb) => {
+ void qb.whereNotNull(`${TableName.AgentVaultSession}.revokedAt`).orWhere(ownerless);
+ });
+ return;
+ }
+ if (status === AgentVaultSessionStatus.Expired) {
+ void query
+ .whereNull(`${TableName.AgentVaultSession}.revokedAt`)
+ .where(owned)
+ .whereNotNull(`${TableName.AgentVaultSession}.expiresAt`)
+ .where(`${TableName.AgentVaultSession}.expiresAt`, "<=", now);
+ return;
+ }
+ void query
+ .whereNull(`${TableName.AgentVaultSession}.revokedAt`)
+ .where(owned)
+ .where((qb) => {
+ void qb
+ .whereNull(`${TableName.AgentVaultSession}.expiresAt`)
+ .orWhere(`${TableName.AgentVaultSession}.expiresAt`, ">", now);
+ });
+};
+
+const userDisplayName = ({
+ userFirstName,
+ userLastName
+}: {
+ userFirstName: string | null;
+ userLastName: string | null;
+}) => [userFirstName, userLastName].filter(Boolean).join(" ") || null;
+
+export const agentVaultSessionDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultSession);
+
+ const findByTokenHash = async (tokenHash: string, tx?: Knex): Promise<TAgentVaultSessions | undefined> => {
+ try {
+ return await (tx || db.replicaNode())(TableName.AgentVaultSession).where({ tokenHash }).first();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault session by token hash" });
+ }
+ };
+
+ const findForList = async (
+ {
+ projectId,
+ actor,
+ status,
+ search,
+ limit,
+ offset
+ }: {
+ projectId: string;
+ actor?: { type: ActorType.USER | ActorType.IDENTITY; id: string };
+ status?: AgentVaultSessionStatus;
+ search?: string;
+ limit: number;
+ offset: number;
+ },
+ tx?: Knex
+ ): Promise<{ sessions: TAgentVaultSessionListRow[]; totalCount: number }> => {
+ try {
+ const conn = tx || db.replicaNode();
+ const now = new Date();
+
+ const applyFilters = (query: Knex.QueryBuilder) => {
+ void query.where(`${TableName.AgentVaultSession}.projectId`, projectId);
+ if (actor?.type === ActorType.USER) void query.where(`${TableName.AgentVaultSession}.userId`, actor.id);
+ if (actor?.type === ActorType.IDENTITY) void query.where(`${TableName.AgentVaultSession}.identityId`, actor.id);
+ if (status) statusFilter(query, status, now);
+ // Shared with the count query, so the pager describes the filtered set rather than the whole one.
+ if (search) {
+ const term = `%${sanitizeSqlLikeString(search)}%`;
+ // Joined so the search sees the same live-then-snapshot name the rows display; searching the
+ // snapshot alone would miss a renamed actor and match a name no longer shown.
+ void query
+ .leftJoin(TableName.Users, `${TableName.AgentVaultSession}.userId`, `${TableName.Users}.id`)
+ .leftJoin(TableName.Identity, `${TableName.AgentVaultSession}.identityId`, `${TableName.Identity}.id`);
+
+ void query.where((qb) => {
+ void qb
+ .orWhereILike(`${TableName.Identity}.name`, term)
+ .orWhereILike(`${TableName.Users}.username`, term)
+ // Covers a first name, a last name and the two together, so no separate checks are needed.
+ .orWhereRaw(`CONCAT_WS(' ', ??, ??) ILIKE ?`, [
+ `${TableName.Users}.firstName`,
+ `${TableName.Users}.lastName`,
+ term
+ ])
+ .orWhereILike(`${TableName.AgentVaultSession}.actorName`, term)
+ .orWhereILike(`${TableName.AgentVaultSession}.actorEmail`, term)
+ .orWhereExists((sub) => {
+ void sub
+ .select(db.raw("1"))
+ .from(TableName.AgentVaultSessionAccessBundle)
+ .leftJoin(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultAccessBundle}.id`,
+ `${TableName.AgentVaultSessionAccessBundle}.accessBundleId`
+ )
+ .whereRaw(`?? = ??`, [
+ `${TableName.AgentVaultSessionAccessBundle}.sessionId`,
+ `${TableName.AgentVaultSession}.id`
+ ])
+ // The live name is what the row displays, with the snapshot standing in once the
+ // bundle is gone, so the search has to look at whichever one is shown.
+ .whereRaw(`COALESCE(??, ??) ILIKE ?`, [
+ `${TableName.AgentVaultAccessBundle}.name`,
+ `${TableName.AgentVaultSessionAccessBundle}.accessBundleName`,
+ term
+ ]);
+ });
+ });
+ }
+ return query;
+ };
+
+ const countResult = (await applyFilters(conn(TableName.AgentVaultSession))
+ .count(`${TableName.AgentVaultSession}.id as count`)
+ .first()) as { count: string } | undefined;
+ const totalCount = parseInt(countResult?.count || "0", 10);
+
+ const pageIds = (await applyFilters(conn(TableName.AgentVaultSession))
+ .orderBy(`${TableName.AgentVaultSession}.createdAt`, "desc")
+ .limit(limit)
+ .offset(offset)
+ .select(`${TableName.AgentVaultSession}.id`)) as { id: string }[];
+
+ if (!pageIds.length) return { sessions: [], totalCount };
+
+ const rows = (await conn(TableName.AgentVaultSession)
+ .whereIn(
+ `${TableName.AgentVaultSession}.id`,
+ pageIds.map((row) => row.id)
+ )
+ .leftJoin(TableName.Users, `${TableName.AgentVaultSession}.userId`, `${TableName.Users}.id`)
+ .leftJoin(TableName.Identity, `${TableName.AgentVaultSession}.identityId`, `${TableName.Identity}.id`)
+ .leftJoin(
+ TableName.AgentVaultSessionAccessBundle,
+ `${TableName.AgentVaultSessionAccessBundle}.sessionId`,
+ `${TableName.AgentVaultSession}.id`
+ )
+ // The snapshot on the junction row is what a deleted bundle leaves behind; while the bundle is
+ // still there its current name is the truthful one, so a rename shows on every session at once.
+ .leftJoin(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultAccessBundle}.id`,
+ `${TableName.AgentVaultSessionAccessBundle}.accessBundleId`
+ )
+ .select(
+ db.ref("id").withSchema(TableName.AgentVaultSession),
+ db.ref("userId").withSchema(TableName.AgentVaultSession),
+ db.ref("identityId").withSchema(TableName.AgentVaultSession),
+ db.ref("expiresAt").withSchema(TableName.AgentVaultSession),
+ db.ref("revokedAt").withSchema(TableName.AgentVaultSession),
+ db.ref("createdAt").withSchema(TableName.AgentVaultSession),
+ db.ref("username").withSchema(TableName.Users).as("userUsername"),
+ db.ref("firstName").withSchema(TableName.Users).as("userFirstName"),
+ db.ref("lastName").withSchema(TableName.Users).as("userLastName"),
+ db.ref("name").withSchema(TableName.Identity).as("identityName"),
+ db.ref("actorName").withSchema(TableName.AgentVaultSession),
+ db.ref("actorEmail").withSchema(TableName.AgentVaultSession),
+ db.ref("accessBundleId").withSchema(TableName.AgentVaultSessionAccessBundle),
+ db.ref("accessBundleName").withSchema(TableName.AgentVaultSessionAccessBundle),
+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("liveAccessBundleName"),
+ db.ref("position").withSchema(TableName.AgentVaultSessionAccessBundle)
+ )
+ .orderBy(`${TableName.AgentVaultSession}.createdAt`, "desc")
+ .orderBy(`${TableName.AgentVaultSessionAccessBundle}.position`, "asc")) as {
+ id: string;
+ userId: string | null;
+ identityId: string | null;
+ expiresAt: Date | null;
+ revokedAt: Date | null;
+ createdAt: Date;
+ userUsername: string | null;
+ userFirstName: string | null;
+ userLastName: string | null;
+ identityName: string | null;
+ actorName: string;
+ actorEmail: string | null;
+ accessBundleId: string | null;
+ accessBundleName: string | null;
+ liveAccessBundleName: string | null;
+ position: number | null;
+ }[];
+
+ const bySession = new Map<string, TAgentVaultSessionListRow>();
+ rows.forEach((row) => {
+ let session = bySession.get(row.id);
+ if (!session) {
+ session = {
+ id: row.id,
+ userId: row.userId,
+ identityId: row.identityId,
+ actorName: row.identityName ?? userDisplayName(row) ?? row.userUsername ?? row.actorName,
+ actorEmail: row.identityId ? null : (row.userUsername ?? row.actorEmail),
+ expiresAt: row.expiresAt,
+ revokedAt: row.revokedAt,
+ createdAt: row.createdAt,
+ accessBundles: []
+ };
+ bySession.set(row.id, session);
+ }
+ if (row.accessBundleName === null || row.position === null) return;
+ session.accessBundles.push({
+ id: row.accessBundleId,
+ name: row.liveAccessBundleName ?? row.accessBundleName,
+ position: row.position
+ });
+ });
+
+ return { sessions: [...bySession.values()], totalCount };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault sessions" });
+ }
+ };
+
+ // Conditional so two concurrent revokes cannot both believe they were the one that revoked it. The loser
+ // gets no row back, which is what keeps the audit trail down to a single revocation.
+ const revokeIfActive = async (id: string, revokedAt: Date, tx?: Knex) => {
+ try {
+ const [row] = (await (tx || db)(TableName.AgentVaultSession)
+ .where({ id })
+ .whereNull("revokedAt")
+ .update({ revokedAt }, "*")) as TAgentVaultSessions[];
+ return row as TAgentVaultSessions | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Revoke agent vault session" });
+ }
+ };
+
+ const pruneRetiredBefore = async (cutoff: Date, tx?: Knex) => {
+ try {
+ return await (tx || db)(TableName.AgentVaultSession)
+ .where((qb) => {
+ void qb
+ .where("revokedAt", "<", cutoff)
+ .orWhere((inner) => {
+ void inner.whereNull("revokedAt").where("expiresAt", "<", cutoff);
+ })
+ // An ownerless session stopped working the moment its actor was deleted, and nothing stamps
+ // that moment, so it goes by age: a never session would otherwise outlive the 30 days for good.
+ .orWhere((inner) => {
+ void inner.whereNull("userId").whereNull("identityId").where("createdAt", "<", cutoff);
+ });
+ })
+ .del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Prune retired Agent Vault sessions" });
+ }
+ };
+
+ return { ...orm, findByTokenHash, findForList, revokeIfActive, pruneRetiredBefore };
+};
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts
new file mode 100644
index 0000000000..522c0597dc
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts
@@ -0,0 +1,27 @@
+import crypto from "node:crypto";
+
+import { AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";
+
+export const AGENT_VAULT_SESSION_TOKEN_PREFIX = "agv_";
+
+export const hashSessionToken = (token: string) => crypto.createHash("sha256").update(token).digest("hex");
+
+/** sha256, not bcrypt: the token is the lookup key. It is never stored and comes back exactly once. */
+export const generateSessionToken = () => {
+ const token = `${AGENT_VAULT_SESSION_TOKEN_PREFIX}${crypto.randomBytes(32).toString("base64url")}`;
+ return { token, tokenHash: hashSessionToken(token) };
+};
+
+// The actor columns are SET NULL when the owner is deleted, so the row outlives them. Resolve refuses such
+// a session; the status says the same, or the list would show it Active with nobody left to revoke it.
+export const isOwnerlessSession = (session: { userId?: string | null; identityId?: string | null }) =>
+ !session.userId && !session.identityId;
+
+export const deriveSessionStatus = (
+ session: { expiresAt: Date | null; revokedAt: Date | null; userId?: string | null; identityId?: string | null },
+ now = new Date()
+): AgentVaultSessionStatus => {
+ if (session.revokedAt || isOwnerlessSession(session)) return AgentVaultSessionStatus.Revoked;
+ if (session.expiresAt && session.expiresAt <= now) return AgentVaultSessionStatus.Expired;
+ return AgentVaultSessionStatus.Active;
+};
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
new file mode 100644
index 0000000000..689e276851
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
@@ -0,0 +1,232 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionAgentVaultSessionActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { ms } from "@app/lib/ms";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+
+import { AgentVaultSessionScope } from "../agent-vault/agent-vault-enums";
+import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
+import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";
+import { TAgentVaultSessionAccessBundleDALFactory } from "./agent-vault-session-access-bundle-dal";
+import { TAgentVaultSessionDALFactory } from "./agent-vault-session-dal";
+import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";
+import { TListSessionsDTO, TMintSessionDTO, TRevokeSessionDTO } from "./agent-vault-session-types";
+
+// V1 ships one bundle per session; the junction table, `position` and the proxy matcher all handle more.
+export const AGENT_VAULT_MAX_SESSION_BUNDLES = 1;
+export const AGENT_VAULT_SESSION_DEFAULT_TTL = "7d";
+export const AGENT_VAULT_SESSION_TTL_NEVER = "never";
+// Past roughly 1e8 days the expiry overflows Date and Postgres rejects the row as a 500. A century is
+// far beyond any real lifetime and keeps the message honest; "never" exists for no expiry at all.
+export const AGENT_VAULT_SESSION_MAX_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
+
+type TAgentVaultSessionServiceFactoryDep = {
+ agentVaultSessionDAL: TAgentVaultSessionDALFactory;
+ agentVaultSessionAccessBundleDAL: TAgentVaultSessionAccessBundleDALFactory;
+ agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;
+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+};
+
+const SESSION_RETENTION_DAYS = 30;
+
+export type TAgentVaultSessionServiceFactory = ReturnType<typeof agentVaultSessionServiceFactory>;
+
+export const agentVaultSessionServiceFactory = ({
+ agentVaultSessionDAL,
+ agentVaultSessionAccessBundleDAL,
+ agentVaultAccessBundleDAL,
+ membershipDAL,
+ permissionService
+}: TAgentVaultSessionServiceFactoryDep) => {
+ const requireSessionActor = (ctx: TMintSessionDTO["ctx"]) => {
+ if (ctx.actor !== ActorType.USER && ctx.actor !== ActorType.IDENTITY) {
+ throw new BadRequestError({ message: "Only a user or machine identity can hold an Agent Vault session" });
+ }
+ return { type: ctx.actor, id: ctx.actorId };
+ };
+
+ const mintSession = async ({ projectId, ctx, accessBundles, actorName, actorEmail, ttl }: TMintSessionDTO) => {
+ const actor = requireSessionActor(ctx);
+ const { permission, accessBundleIds: reachable } = await getAgentVaultReachability(
+ { permissionService, membershipDAL },
+ { projectId, ctx }
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultSessionActions.Create,
+ ProjectPermissionSub.AgentVaultSessions
+ );
+
+ if (!accessBundles.length) {
+ throw new BadRequestError({ message: "Name the access bundle the session should carry" });
+ }
+ if (accessBundles.length > AGENT_VAULT_MAX_SESSION_BUNDLES) {
+ throw new BadRequestError({ message: "A session carries one access bundle. Name a single bundle." });
+ }
+ if (new Set(accessBundles).size !== accessBundles.length) {
+ throw new BadRequestError({ message: "The same access bundle is named more than once. Name it once." });
+ }
+
+ const bundles = await agentVaultAccessBundleDAL.find({ projectId, $in: { name: accessBundles } });
+ const bundlesByName = new Map(bundles.map((bundle) => [bundle.name, bundle]));
+
+ const unreachable = accessBundles.find((name) => {
+ const bundle = bundlesByName.get(name);
+ return !bundle || (reachable !== null && !reachable.includes(bundle.id));
+ });
+ if (unreachable) {
+ throw new BadRequestError({
+ message: `No access bundle named '${unreachable}' is granted to you. Check the name, or ask an Agent Vault admin to grant it.`
+ });
+ }
+
+ const expiresAt = ttl === AGENT_VAULT_SESSION_TTL_NEVER ? null : new Date(Date.now() + ms(ttl));
+ const { token, tokenHash } = generateSessionToken();
+
+ const session = await agentVaultSessionDAL.transaction(async (tx) => {
+ const created = await agentVaultSessionDAL.create(
+ {
+ projectId,
+ userId: actor.type === ActorType.USER ? actor.id : null,
+ identityId: actor.type === ActorType.IDENTITY ? actor.id : null,
+ actorName,
+ actorEmail,
+ tokenHash,
+ expiresAt
+ },
+ tx
+ );
+
+ await agentVaultSessionAccessBundleDAL.insertMany(
+ accessBundles.map((name, position) => ({
+ sessionId: created.id,
+ accessBundleId: bundlesByName.get(name)!.id,
+ accessBundleName: name,
+ position
+ })),
+ tx
+ );
+
+ return created;
+ });
+
+ return {
+ session: {
+ id: session.id,
+ expiresAt: session.expiresAt ?? null,
+ createdAt: session.createdAt,
+ accessBundles: accessBundles.map((name, position) => ({
+ id: bundlesByName.get(name)!.id,
+ name,
+ position
+ }))
+ },
+ token
+ };
+ };
+
+ const getSessionAuthority = async ({ projectId, ctx }: { projectId: string; ctx: TListSessionsDTO["ctx"] }) => {
+ const { permission, hasRole } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+ return { permission, isAdmin: hasRole(ProjectMembershipRole.Admin) };
+ };
+
+ const listSessions = async ({ projectId, ctx, scope, status, search, limit, offset }: TListSessionsDTO) => {
+ const { permission, isAdmin } = await getSessionAuthority({ projectId, ctx });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultSessionActions.Read,
+ ProjectPermissionSub.AgentVaultSessions
+ );
+
+ // The CASL read action alone would let any member list everyone's sessions.
+ if (scope === AgentVaultSessionScope.All && !isAdmin) {
+ throw new ForbiddenRequestError({ message: "Only an Agent Vault administrator can list everyone's sessions" });
+ }
+
+ const actor = scope === AgentVaultSessionScope.All ? undefined : requireSessionActor(ctx);
+ const { sessions, totalCount } = await agentVaultSessionDAL.findForList({
+ projectId,
+ actor,
+ status,
+ search,
+ limit,
+ offset
+ });
+
+ return {
+ sessions: sessions.map((session) => ({ ...session, status: deriveSessionStatus(session) })),
+ totalCount
+ };
+ };
+
+ const revokeSession = async ({ projectId, ctx, sessionId }: TRevokeSessionDTO) => {
+ const { permission, isAdmin } = await getSessionAuthority({ projectId, ctx });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultSessionActions.Revoke,
+ ProjectPermissionSub.AgentVaultSessions
+ );
+
+ const session = await agentVaultSessionDAL.findOne({ id: sessionId, projectId });
+ if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
+
+ // The CASL action alone would let any member revoke another member's session.
+ const isOwner =
+ (ctx.actor === ActorType.USER && session.userId === ctx.actorId) ||
+ (ctx.actor === ActorType.IDENTITY && session.identityId === ctx.actorId);
+ if (!isOwner && !isAdmin) {
+ throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
+ }
+
+ // The row type leaves nullable columns optional; the response contract does not.
+ const withStatus = (row: typeof session) => {
+ const normalized = {
+ ...row,
+ userId: row.userId ?? null,
+ identityId: row.identityId ?? null,
+ actorEmail: row.actorEmail ?? null,
+ expiresAt: row.expiresAt ?? null,
+ revokedAt: row.revokedAt ?? null
+ };
+ return { ...normalized, status: deriveSessionStatus(normalized) };
+ };
+
+ // revokedNow lets the caller audit a real revocation without auditing a repeat. Revoking twice stays a
+ // 200 with the original revokedAt, so the second caller is not the one who revoked it.
+ if (session.revokedAt) return { session: withStatus(session), revokedNow: false };
+
+ const revoked = await agentVaultSessionDAL.revokeIfActive(session.id, new Date());
+ if (revoked) return { session: withStatus(revoked), revokedNow: true };
+
+ // A concurrent revoke won. Report its timestamp rather than the one this request read.
+ const current = await agentVaultSessionDAL.findOne({ id: session.id, projectId });
+ return { session: withStatus(current ?? session), revokedNow: false };
+ };
+
+ // Expiry needs no sweep: it is enforced against the clock on every resolve and derived per row on read.
+ const sweepRetiredSessions = async () => {
+ const cutoff = new Date(Date.now() - SESSION_RETENTION_DAYS * 24 * 60 * 60 * 1000);
+ const pruned = await agentVaultSessionDAL.pruneRetiredBefore(cutoff);
+ logger.info(`agent-vault: session sweep pruned ${pruned} retired session(s)`);
+ };
+
+ return {
+ mintSession,
+ listSessions,
+ revokeSession,
+ sweepRetiredSessions
+ };
+};
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts
new file mode 100644
index 0000000000..fc5a068a10
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts
@@ -0,0 +1,27 @@
+import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";
+import { AgentVaultSessionScope, AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";
+
+export type TMintSessionDTO = {
+ projectId: string;
+ ctx: TAgentVaultActorContext;
+ accessBundles: string[];
+ actorName: string;
+ actorEmail: string | null;
+ ttl: string;
+};
+
+export type TListSessionsDTO = {
+ projectId: string;
+ ctx: TAgentVaultActorContext;
+ scope: AgentVaultSessionScope;
+ status?: AgentVaultSessionStatus;
+ limit: number;
+ offset: number;
+ search?: string;
+};
+
+export type TRevokeSessionDTO = {
+ projectId: string;
+ ctx: TAgentVaultActorContext;
+ sessionId: string;
+};
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
new file mode 100644
index 0000000000..9a6d27ab7f
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -0,0 +1,162 @@
+# Agent Vault backend
+
+Read this before touching any `agent-vault-*` service or router. It holds only what the code does not say on
+its own: the invariants that are easy to break and the decisions that are settled. Add a line when a reader
+would get something wrong from the code alone; cut anything the code already states.
+
+**Thesis.** An agent runs holding no credentials. Its HTTP traffic goes through a proxy we control, which
+attaches the real credential on the way out. What an agent may reach lives in a **session** row on our side,
+never in anything the agent holds.
+
+| Noun | What it is |
+| --- | --- |
+| **Access bundle** | A named set of services. The unit you grant |
+| **Service** | One host pattern set plus its credential |
+| **Session** | A minted token naming one actor, one of their bundles, and an expiry. The token *is* the session |
+| **Proxy** | One deployed egress node with its own CA. One row per box |
+
+```
+agent-vault/ shared: enums, host grammar, conflict detection, reachability
+agent-vault-access-bundle/ bundles, services, credential encryption, grants
+agent-vault-member/ product membership (list, add, role, remove)
+agent-vault-session/ mint, revoke, list, retention sweep
+agent-vault-project/ the per-org project's lazy bootstrap and resolver
+agent-vault-proxy/ login (enrollment), heartbeat, resolve
+```
+
+Routes: `ee/routes/v1/agent-vault-routers/`, prefix `/api/v1/agent-vault`. CLI: `packages/cmd/agent_vault*.go`
+and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-vault/`,
+`frontend/src/hooks/api/agentVault/`, `frontend/src/components/agent-vault/`.
+
+## The project
+
+- One implicit project per org, created lazily by the `injectAgentVaultProjectId` preValidation hook, so
+ `GET /agent-vault/project` creates it on first access. That REST deviation is deliberate.
+- Generic project create and delete are blocked for this type, and the project is excluded from
+ `countOfBillableOrgProjects`. Break the exclusion and every org loses a workspace slot.
+- The lazy bootstrap seeds no members (PAM's sweeps in every org admin; this one deliberately does not). Org
+ admins join through `grant-admin-access`, from the product tile or the layout's `beforeLoad` when they arrive
+ by link, and that route is where the `agent_vault_identities` meter moves for them. Only org creation seeds
+ the creator.
+- The traffic policy defaults to any-host (formerly Allow), in the DB default, the service and the dialog.
+ Deliberate: the product brokers credentials, it is not an egress firewall, and under bundle-hosts the
+ quickstart's agent could reach neither Anthropic nor npm until a bypass list exists. Settled with the
+ product owner; bundle-hosts is documented as the hardening step.
+- Wherever code branches on `ProjectType.PAM`, add the Agent Vault arm: `AgentVaultIdentities` metering emits,
+ the admin-or-member predefined roles filter, `AuditLogStreamProduct`, `grantAgentVaultAccess` on the org
+ invite. See the root `CLAUDE.md`.
+
+## Grants and reachability
+
+- A grant is a `memberships` row (`scope = resource`, `scopeResourceType = agent-vault-access-bundle`,
+ `scopeResourceId = <bundle id>`) with one `membership_roles` row, slug `consumer`. The slug is a label;
+ bundle access is decided in SQL, not CASL. Because it is the platform's table, the platform reaps grants
+ on project removal, org removal, SCIM and every FK cascade. Do not add an Agent Vault reaper.
+- `scopeResourceId` has no FK, so `deleteAccessBundle` deletes the bundle row first and then the grants in one
+ transaction, and `addMembers` locks the bundle row (`lockByIdInProject`) before inserting. Keep that order.
+- Granting is batch: one POST carries `{ userIds, identityIds, groupIds }`. That lock is what makes
+ the dedupe read inside it authoritative, so an actor who already holds the bundle is returned in
+ `skipped` rather than erroring; the unique index is only the backstop.
+- Reachability has one implementation, `findReachableAccessBundleIds` over the platform's
+ `findResourceMembershipsForActor`, and mint, member-facing reads and resolve all call it. A group's grants
+ count only while the group confers a live role (`liveGroupIdsFrom`). Write no group-expansion SQL here.
+- Reachability is a service-layer filter (`whereIn` on ids, `null` for an admin), not a CASL condition:
+ conditions can interpolate only `identity.id`, `username` and `metadata`.
+- The creator grant exists only for a creator with a direct project membership. A group-inherited admin gets
+ none, so no individual grant row ever outlives its owner's membership.
+- A cross-org or ungranted id is 404, never 403, and mint uses one message for an unknown and an ungranted
+ name, so the error never confirms a bundle exists.
+- Mint is the only endpoint addressed by bundle name; every resource path stays on ids. It is the only one a
+ human or the CLI hand-writes, and names are slugs unique per project, so the CLI posts the name straight
+ through instead of resolving it first. PAM does the same with `path: "folderName/accountName"`.
+
+## Sessions and resolve
+
+- The token is the lookup key, so it is stored as sha256 (not bcrypt) and returned exactly once.
+- V1 caps a session at one bundle: `AGENT_VAULT_MAX_SESSION_BUNDLES`, mirrored by the CLI's once-only check on
+ `--access-bundle` and the single-select Create Session sheet. The mint body stays a list, the junction table
+ keeps `position`, resolve orders by position then name, and the Go matcher breaks ties by slice order, so
+ lifting the cap is those three places plus the copy that says one (the api-docs string, the service's cap
+ message, the sheet and sessions page, the CLI help and the docs), not a migration.
+- The bundle on a session is a ceiling fixed at mint and intersected with live reachability on every resolve.
+ It can shrink and grow back, never past what was minted.
+- Grants are read fresh on every resolve. The actor's role comes through the platform's permission cache
+ (10 second marker), so a promotion or demotion can lag by that much on top of the proxy's poll.
+- Resolve requires a live session-read permission, not a membership row: a lapsed time-limited role leaves
+ its row behind, and `hasRole(Admin)` alone would fall through as member. An actor removed from the project
+ surfaces as `ProjectMembershipNotFound`, which resolve turns into a 401 so the proxy drops the session on
+ the next poll instead of riding its grace window.
+- Removing an actor from Agent Vault does not revoke their sessions. The sessions resolve to nothing while
+ the actor is out and work again if the actor is added back. Settled with the product owner.
+- Session actor columns are `SET NULL` so history survives the actor. Resolve refuses a session with neither
+ id: a null actor id reaches the membership lookups as `IS NULL`, matches user rows, and resolved as admin.
+- Status is derived from `revokedAt`, `expiresAt` and the actor columns, never stored: a session with neither
+ actor id reads as revoked in the list, the status filter and the sweep, so they agree with resolve refusing
+ it. Expiry is enforced against the clock on every resolve. `sweepRetiredSessions` exists only for the 30 day hard delete; there is no expiry audit
+ event, matching every other product.
+
+## Proxies
+
+- Infisical stores no copy of a proxy's CA, only the fingerprint and expiry. Agents fetch the CA from the
+ proxy's own unauthenticated `/_agent-vault/ca`, so the trust path has no dependency on Infisical and there
+ is deliberately no download endpoint.
+- The login route is unauthenticated (the enrollment token is the credential), so its audit event names the
+ proxy as actor explicitly, as gateway, relay and KMIP enrollment do. Otherwise it logs as `unknownUser`.
+- Health is judged against `heartbeatTTL`, the interval the proxy was running when it last checked in, not
+ the row's current `pollInterval`. A proxy learns a new interval on its next poll, so comparing against the
+ saved one would report a live proxy as unreachable until then. Gateway v2 does the same.
+- The proxy's access token is non-expiring and revoked by bumping `tokenVersion`, which the auth plugin checks
+ on every proxy request. Revoke Access goes through the shared resource-auth revoke so a pending enrollment
+ token is burned too.
+- Resolve is not audited: once per poll per session would swamp the audit table.
+
+## Host grammar
+
+`agent-vault-host-pattern.ts` is the grammar of record. The CLI matcher (`packages/agentvault/match.go`) does
+the matching at runtime and reimplements the same rules, so a change here needs the same change there.
+
+- Paths are rejected: the matcher would compare the decoded path while the upstream gets the escaped one.
+- A portless pattern means 443. An explicit port is allowed, `:80` included, so the proxy must also refuse
+ to inject over plaintext, and it does.
+- A wildcard is the leftmost label only and matches exactly one label. This is what makes every pattern pair
+ identical, contained or disjoint, which is what makes conflict detection exact. Do not loosen it.
+- Conflict detection is an intersection over individual patterns, because `hostPattern` is a comma-separated
+ set. Same bundle: hard reject. Across bundles: allowed, since a session carries one bundle they never meet.
+- Patterns are stored as typed and normalised at match time. `*.com` is accepted; settled as not a bug.
+
+## Credentials at rest
+
+- The KMS cipher pair is project-scoped (`KmsDataKey.SecretManager`) and built once per resolve.
+- `credentialType` is a column and `credentialConfig` the plaintext half (header name, prefix), so a list page
+ renders without a decrypt and a new credential type is a config entry, not a migration. For basic, the
+ username is sealed with the password: some APIs put the whole key in the username.
+- A service update is a patch. `AgentVaultCredentialUpdateSchema` makes every field optional and
+ `mergeCredential` overlays what arrived. Never reuse `AgentVaultBearerConfigSchema` on that path: its
+ `.default()`s would reset an omitted `headerName` to `Authorization`.
+- The sealed secret has three write states: a value re-seals, `null` clears it (passthrough), `undefined`
+ leaves it alone. `$decryptCredential` reads NULL as passthrough, so a bearer row that lost its secret would
+ silently stop attaching a credential.
+
+## The CLI
+
+- Trust is stateless: `agent-vault run` fetches the CA from the proxy on every run; `--ca-fingerprint` is an optional
+ pin checked before anything is written. Re-enrolling a proxy replaces its CA, so pins, mounted copies,
+ keychain entries and any agent already running through it break until updated or restarted.
+- No sandbox, nothing stripped. The agent gets the parent's whole environment plus the proxy URL (session
+ token inside) and the CA trust variables. Settled with the product owner.
+- The session flag is `--session-token`, not `--token`, so the root command's Infisical-token handling never
+ reads it. The minting identity comes from `--client-id`/`--client-secret`, the access-token env vars, or the
+ keyring login.
+- The proxy exits after two consecutive heartbeat 401s: only Revoke Access, a deleted record or a changed
+ signing secret produce one, and every session on it is dead at that point. Timeouts and 5xx ride the
+ five-poll grace window and reset the counter.
+- The enrollment dialog's Docker snippet mounts `/etc/infisical/agent-vault` (the root data dir). Without it a
+ re-created container has no CA and a spent token.
+
+## The frontend
+
+- Admin is a role check on both sides, `hasRole(ProjectMembershipRole.Admin)`, not a CASL check. It decides
+ the projected API shapes (`members` omitted from a bundle, settings omitted from a proxy) and the UI branches.
+- The service template catalog (`helpers/agentVaultTemplates.ts`) is frontend-only and never persisted; icons
+ re-derive from the stored host pattern. The backend must never learn a service name.
+- Docs links live in `pages/agent-vault/agent-vault-docs-urls.ts`; keep them pointing at existing pages.
diff --git a/backend/src/ee/services/agent-vault/agent-vault-actor-types.ts b/backend/src/ee/services/agent-vault/agent-vault-actor-types.ts
new file mode 100644
index 0000000000..1944be7d06
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-actor-types.ts
@@ -0,0 +1,8 @@
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
+export type TAgentVaultActorContext = {
+ actor: ActorType;
+ actorId: string;
+ actorOrgId: string;
+ actorAuthMethod: ActorAuthMethod;
+};
diff --git a/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.ts
new file mode 100644
index 0000000000..8fad993e67
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.ts
@@ -0,0 +1,27 @@
+import { intersectHostPatterns } from "./agent-vault-host-pattern";
+
+export type TConflictCandidate = {
+ id: string;
+ name: string;
+ hostPattern: string;
+};
+
+export type TAgentVaultConflict = {
+ serviceName: string;
+ patterns: string[];
+};
+
+// Containment is not a conflict: an exact host beats a wildcard deterministically, which is how an override is written.
+export const findHostPatternConflicts = (
+ hostPattern: string,
+ candidates: TConflictCandidate[]
+): TAgentVaultConflict[] =>
+ candidates
+ .map((candidate) => ({
+ serviceName: candidate.name,
+ patterns: intersectHostPatterns(hostPattern, candidate.hostPattern)
+ }))
+ .filter((conflict) => conflict.patterns.length > 0);
+
+export const describeConflict = (conflict: TAgentVaultConflict): string =>
+ `'${conflict.serviceName}' already covers ${conflict.patterns.join(", ")} in this access bundle.`;
diff --git a/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.test.ts b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.test.ts
new file mode 100644
index 0000000000..5ca8dfa228
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.test.ts
@@ -0,0 +1,37 @@
+import { AgentVaultBearerConfigSchema } from "./agent-vault-credential-schemas";
+
+describe("bearer credential config", () => {
+ test("Authorization and Bearer settle together when neither is given", () => {
+ expect(AgentVaultBearerConfigSchema.parse({})).toEqual({
+ headerName: "Authorization",
+ headerPrefix: "Bearer"
+ });
+ });
+
+ test("naming Authorization outright still gets the scheme it belongs to", () => {
+ expect(AgentVaultBearerConfigSchema.parse({ headerName: "authorization" })).toEqual({
+ headerName: "authorization",
+ headerPrefix: "Bearer"
+ });
+ });
+
+ // The scheme is RFC 6750's for Authorization. A key in its own header is not a bearer token in that
+ // sense, and an API given "Bearer abc" where it wanted "abc" rejects the request.
+ test("a header of the caller's own gets no scheme they did not ask for", () => {
+ expect(AgentVaultBearerConfigSchema.parse({ headerName: "X-Api-Key" })).toEqual({
+ headerName: "X-Api-Key",
+ headerPrefix: ""
+ });
+ });
+
+ test("an explicit prefix is kept, on any header", () => {
+ expect(AgentVaultBearerConfigSchema.parse({ headerName: "X-Api-Key", headerPrefix: "Token" })).toEqual({
+ headerName: "X-Api-Key",
+ headerPrefix: "Token"
+ });
+ expect(AgentVaultBearerConfigSchema.parse({ headerPrefix: "" })).toEqual({
+ headerName: "Authorization",
+ headerPrefix: ""
+ });
+ });
+});
diff --git a/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts
new file mode 100644
index 0000000000..f3aaaa91cf
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts
@@ -0,0 +1,80 @@
+import { z } from "zod";
+
+import { AgentVaultCredentialType } from "./agent-vault-enums";
+
+// credentialConfig is plaintext jsonb, read on the list page without a decrypt; encryptedCredential is
+// the KMS-sealed secret, NULL exactly when the type is passthrough. The discriminator is a column rather
+// than a field inside the blob, so a new credential type needs no migration.
+
+// The characters RFC 7230 allows. Go's HTTP client refuses to send anything else, so a name saved
+// without this check 502s every request through the service.
+export const AGENT_VAULT_HEADER_NAME_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
+
+export const AGENT_VAULT_HEADER_NAME_MESSAGE =
+ "A header name can't contain spaces or colons. Use letters, digits and dashes, as in X-API-Key.";
+
+// A NUL is rejected by the jsonb write and 500s; a CR or LF saves fine and then makes Go refuse to send
+// the header, so the credential silently never goes out. Both usually arrive by pasting.
+// eslint-disable-next-line no-control-regex
+export const AGENT_VAULT_NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;
+
+export const AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE =
+ "This can't contain line breaks or other control characters. Check for a stray newline if you pasted it.";
+
+const AGENT_VAULT_DEFAULT_HEADER_NAME = "Authorization";
+const AGENT_VAULT_DEFAULT_HEADER_PREFIX = "Bearer";
+
+const bearerHeaderName = z
+ .string()
+ .trim()
+ .min(1)
+ .max(128)
+ .regex(AGENT_VAULT_HEADER_NAME_RE, AGENT_VAULT_HEADER_NAME_MESSAGE);
+
+// The shape a stored bearer config has, where both halves are already settled.
+export const AgentVaultBearerConfigFields = {
+ headerName: bearerHeaderName.default(AGENT_VAULT_DEFAULT_HEADER_NAME),
+ headerPrefix: z.string().trim().max(64).default("")
+};
+
+// Bearer is the scheme RFC 6750 defines for Authorization, so the two settle together on the way in.
+// Naming another header leaves that scheme behind, and filling one in there would send a word the
+// caller never asked for.
+export const AgentVaultBearerConfigSchema = z
+ .object({
+ headerName: bearerHeaderName.default(AGENT_VAULT_DEFAULT_HEADER_NAME),
+ headerPrefix: z.string().trim().max(64).optional()
+ })
+ .transform(({ headerName, headerPrefix }) => ({
+ headerName,
+ headerPrefix:
+ headerPrefix ??
+ (headerName.toLowerCase() === AGENT_VAULT_DEFAULT_HEADER_NAME.toLowerCase()
+ ? AGENT_VAULT_DEFAULT_HEADER_PREFIX
+ : "")
+ }));
+
+// Nothing plaintext: the username is sealed with the password, since for some services (Stripe, Postmark)
+// the username is the key.
+export const AgentVaultBasicConfigSchema = z.object({});
+
+export const AgentVaultPassthroughConfigSchema = z.object({});
+
+export const AgentVaultCredentialConfigSchema = z.discriminatedUnion("type", [
+ z.object({ ...AgentVaultBearerConfigFields, type: z.literal(AgentVaultCredentialType.Bearer) }),
+ AgentVaultBasicConfigSchema.extend({ type: z.literal(AgentVaultCredentialType.Basic) }),
+ AgentVaultPassthroughConfigSchema.extend({ type: z.literal(AgentVaultCredentialType.Passthrough) })
+]);
+
+export type TAgentVaultCredentialConfig = z.infer<typeof AgentVaultCredentialConfigSchema>;
+
+export const AgentVaultSecretSchema = z.discriminatedUnion("type", [
+ z.object({ type: z.literal(AgentVaultCredentialType.Bearer), value: z.string().min(1).max(8192) }),
+ z.object({
+ type: z.literal(AgentVaultCredentialType.Basic),
+ username: z.string().max(256),
+ password: z.string().max(8192)
+ })
+]);
+
+export type TAgentVaultSecret = z.infer<typeof AgentVaultSecretSchema>;
diff --git a/backend/src/ee/services/agent-vault/agent-vault-db-error-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-db-error-fns.ts
new file mode 100644
index 0000000000..2edab44f7f
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-db-error-fns.ts
@@ -0,0 +1,9 @@
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { DatabaseError } from "@app/lib/errors";
+
+/**
+ * Every name in Agent Vault is unique per scope in the database, and the pre-checks in the services can
+ * always lose a race to a concurrent request. The loser would otherwise surface as a bare 500.
+ */
+export const isUniqueViolation = (err: unknown) =>
+ err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation;
diff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.ts
new file mode 100644
index 0000000000..b17f1a58c7
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts
@@ -0,0 +1,25 @@
+export enum AgentVaultCredentialType {
+ Bearer = "bearer",
+ Basic = "basic",
+ Passthrough = "passthrough"
+}
+
+export enum AgentVaultResourceRole {
+ Consumer = "consumer"
+}
+
+export enum AgentVaultTrafficPolicy {
+ AnyHost = "any-host",
+ BundleHosts = "bundle-hosts"
+}
+
+export enum AgentVaultSessionStatus {
+ Active = "active",
+ Revoked = "revoked",
+ Expired = "expired"
+}
+
+export enum AgentVaultSessionScope {
+ Mine = "mine",
+ All = "all"
+}
diff --git a/backend/src/ee/services/agent-vault/agent-vault-host-pattern.test.ts b/backend/src/ee/services/agent-vault/agent-vault-host-pattern.test.ts
new file mode 100644
index 0000000000..bb7a9b9d28
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-host-pattern.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ AgentVaultPatternRelation,
+ hostPatternSchema,
+ intersectHostPatterns,
+ matchesHost,
+ parseHostPatterns,
+ relateHostPatterns
+} from "./agent-vault-host-pattern";
+
+const parseOne = (raw: string) => {
+ const { patterns, errors } = parseHostPatterns(raw);
+ expect(errors).toEqual([]);
+ expect(patterns).toHaveLength(1);
+ return patterns[0];
+};
+
+describe("matching a pattern against a concrete host", () => {
+ test.each([
+ { pattern: "api.github.com", host: "api.github.com", port: "443", expected: true, why: "exact host, default port" },
+ { pattern: "api.github.com", host: "API.GitHub.com", port: "443", expected: true, why: "case-insensitive" },
+ { pattern: "api.github.com", host: "api.github.com.", port: "443", expected: true, why: "trailing dot" },
+ { pattern: "api.github.com", host: "api.github.com", port: "80", expected: false, why: "portless means 443" },
+ { pattern: "api.github.com", host: "api.github.com", port: "8443", expected: false, why: "443 is concrete" },
+ { pattern: "api.github.com:8443", host: "api.github.com", port: "8443", expected: true, why: "explicit port" },
+ { pattern: "api.github.com", host: "other.github.com", port: "443", expected: false, why: "not a sibling" },
+ { pattern: "*.github.com", host: "api.github.com", port: "443", expected: true, why: "one label" },
+ { pattern: "*.github.com", host: "a.b.github.com", port: "443", expected: false, why: "not any depth" },
+ { pattern: "*.github.com", host: "github.com", port: "443", expected: false, why: "a label is required" },
+ { pattern: "*.github.com", host: "evilgithub.com", port: "443", expected: false, why: "the dot matters" },
+ { pattern: "*.bar.foo.com", host: "api.foo.com", port: "443", expected: false, why: "label counts differ" },
+ { pattern: "[::1]", host: "0:0:0:0:0:0:0:1", port: "443", expected: true, why: "IPv6 expanded" },
+ { pattern: "[0:0:0:0:0:0:0:1]:8200", host: "::1", port: "8200", expected: true, why: "written the long way" },
+ { pattern: "[2001:db8::1]", host: "2001:db8::2", port: "443", expected: false, why: "different addresses" },
+ { pattern: "10.0.1.5:8200", host: "10.0.1.5", port: "8200", expected: true, why: "IPv4 literal" },
+ { pattern: "[::ffff:192.0.2.1]", host: "192.0.2.1", port: "443", expected: true, why: "IPv4-mapped IPv6" },
+ { pattern: "192.0.2.1", host: "::ffff:192.0.2.1", port: "443", expected: true, why: "and the other way round" },
+ {
+ pattern: "api.github.com, registry.npmjs.org",
+ host: "registry.npmjs.org",
+ port: "443",
+ expected: true,
+ why: "a column is a set"
+ }
+ ])("$pattern vs $host:$port -> $expected ($why)", ({ pattern, host, port, expected }) => {
+ const { patterns, errors } = parseHostPatterns(pattern);
+ expect(errors).toEqual([]);
+ expect(patterns.some((candidate) => matchesHost(candidate, host, port))).toBe(expected);
+ });
+});
+
+describe("the grammar", () => {
+ test.each([
+ { pattern: "https://api.github.com", why: "a scheme is not part of the grammar" },
+ { pattern: "api.github.com/v1/safe", why: "the matcher sees the decoded path, the upstream the escaped one" },
+ { pattern: "api.github.com/", why: "a bare trailing slash is still a path" },
+ { pattern: "*", why: "a credential is always limited to specific hosts" },
+ { pattern: "api.github.com:0", why: "port out of range" },
+ { pattern: "api.github.com:70000", why: "port out of range" },
+ { pattern: "api.github.com:https", why: "port must be numeric" },
+ { pattern: "api.github.com:0443", why: "a leading zero is kept as typed and would match nothing" },
+ { pattern: "[::1", why: "unclosed IPv6 bracket" },
+ { pattern: "[not-an-address]", why: "brackets must hold a valid IPv6 address" },
+ { pattern: "api.*.github.com", why: "a wildcard is the leftmost label only" },
+ { pattern: "api-*.github.com", why: "no mid-label globs; conflict detection depends on it" },
+ { pattern: "api.github.com,", why: "an empty entry is a typo, not an empty set" },
+ { pattern: "api.github.com, api.github.com:443", why: "the same normalized pattern twice" }
+ ])("rejects $pattern ($why)", ({ pattern }) => {
+ expect(hostPatternSchema.safeParse(pattern).success).toBe(false);
+ });
+
+ test.each([
+ { pattern: "API.GitHub.com", normalized: "api.github.com:443" },
+ { pattern: "api.github.com.", normalized: "api.github.com:443" },
+ {
+ pattern: " api.github.com , registry.npmjs.org:8443 ",
+ normalized: "api.github.com:443,registry.npmjs.org:8443"
+ },
+ { pattern: "[::1]", normalized: "[0000:0000:0000:0000:0000:0000:0000:0001]:443" },
+ { pattern: "[::ffff:10.0.1.5]:8200", normalized: "10.0.1.5:8200" }
+ ])("derives the canonical key for $pattern", ({ pattern, normalized }) => {
+ expect(
+ parseHostPatterns(pattern)
+ .patterns.map((candidate) => candidate.key)
+ .join(",")
+ ).toBe(normalized);
+ });
+});
+
+describe("how two patterns relate", () => {
+ test.each([
+ { a: "api.foo.com", b: "api.foo.com", relation: "identical" },
+ { a: "api.foo.com", b: "api.foo.com:443", relation: "identical" },
+ { a: "api.foo.com", b: "*.foo.com", relation: "contained" },
+ { a: "*.foo.com", b: "api.foo.com", relation: "contained" },
+ { a: "*.foo.com", b: "*.bar.foo.com", relation: "disjoint" },
+ { a: "api.foo.com:443", b: "api.foo.com:8443", relation: "disjoint" },
+ { a: "*.foo.com", b: "api.foo.com:8443", relation: "disjoint" },
+ { a: "api.foo.com", b: "api.bar.com", relation: "disjoint" }
+ ])("$a vs $b is $relation", ({ a, b, relation }) => {
+ expect(relateHostPatterns(parseOne(a), parseOne(b))).toBe(relation as AgentVaultPatternRelation);
+ });
+});
+
+describe("overlap detection", () => {
+ test("is an intersection, not set equality", () => {
+ expect(intersectHostPatterns("api.foo.com, api.bar.com", "api.foo.com")).toEqual(["api.foo.com:443"]);
+ });
+
+ test("normalizes both sides before comparing", () => {
+ expect(intersectHostPatterns("API.Foo.com.", "api.foo.com:443")).toEqual(["api.foo.com:443"]);
+ expect(intersectHostPatterns("[::1]:8200", "[0:0:0:0:0:0:0:1]:8200")).toEqual([
+ "[0000:0000:0000:0000:0000:0000:0000:0001]:8200"
+ ]);
+ });
+
+ test("containment is not an intersection, so an override is allowed", () => {
+ expect(intersectHostPatterns("*.foo.com", "api.foo.com")).toEqual([]);
+ });
+
+ test("a differing port is not an intersection", () => {
+ expect(intersectHostPatterns("api.foo.com:443", "api.foo.com:8443")).toEqual([]);
+ });
+});
+
+describe("errors name the offending entry", () => {
+ test("a path says what to remove", () => {
+ const { errors } = parseHostPatterns("api.github.com/v1/safe");
+ expect(errors[0]).toContain("must not include a path");
+ expect(errors[0]).toContain("api.github.com/v1/safe");
+ });
+
+ test("one bad entry does not hide the others", () => {
+ const { patterns, errors } = parseHostPatterns("api.github.com, https://bad.com, *");
+ expect(patterns.map((pattern) => pattern.key)).toEqual(["api.github.com:443"]);
+ expect(errors).toHaveLength(2);
+ });
+
+ test.each([{ raw: "" }, { raw: "," }, { raw: " , " }])(
+ "an empty value is one error, not several ($raw)",
+ ({ raw }) => {
+ expect(parseHostPatterns(raw).errors).toEqual(["Host pattern is required"]);
+ }
+ );
+
+ test("the message names the field being edited", () => {
+ expect(parseHostPatterns("*", "service").errors[0]).toContain("A service must name specific hosts");
+ expect(parseHostPatterns("*", "host exception").errors[0]).toContain("A host exception must name specific hosts");
+ });
+});
diff --git a/backend/src/ee/services/agent-vault/agent-vault-host-pattern.ts b/backend/src/ee/services/agent-vault/agent-vault-host-pattern.ts
new file mode 100644
index 0000000000..f152d4d418
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-host-pattern.ts
@@ -0,0 +1,235 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+// Copied from proxied-service-schemas.ts rather than imported, so that module stays independently deletable.
+// Two deliberate divergences: paths are rejected outright (the Go matcher compares the decoded path while
+// the upstream receives the escaped one), and a portless pattern defaults to 443 rather than any port,
+// which had let plaintext port 80 match and the credential go out unencrypted.
+//
+// The grammar is mirrored in the CLI (packages/agentvault/match.go), which does the matching at runtime.
+// A change to the rules here needs the same change there.
+
+const HOST_LABELS_RE = new RE2(/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/i);
+const PORT_RE = new RE2(/^\d+$/);
+const IPV4_RE = new RE2(/^\d{1,3}(?:\.\d{1,3}){3}$/);
+const IPV6_SCHEMA = z.string().ip({ version: "v6" });
+
+export const AGENT_VAULT_DEFAULT_PORT = "443";
+export const AGENT_VAULT_MAX_HOST_PATTERN_LENGTH = 1024;
+
+export type TAgentVaultHostPattern = {
+ host: string;
+ port: string;
+ isWildcard: boolean;
+ key: string;
+};
+
+// String(Number(...)) rejects a leading zero. The pattern keeps the port as typed and the Go matcher
+// compares it as text, so ":0443" would be disjoint from ":443" and quietly match no traffic at all.
+const isValidPort = (portStr: string) => {
+ const port = Number(portStr);
+ return PORT_RE.test(portStr) && String(port) === portStr && port >= 1 && port <= 65535;
+};
+
+// Full eight-group lowercase form, so `[::1]` and `[0:0:0:0:0:0:0:1]` compare equal.
+const expandIpv6 = (address: string): string => {
+ const [withoutZone] = address.split("%");
+
+ let head = withoutZone;
+ let tail = "";
+ const doubleColonIdx = withoutZone.indexOf("::");
+ if (doubleColonIdx !== -1) {
+ head = withoutZone.slice(0, doubleColonIdx);
+ tail = withoutZone.slice(doubleColonIdx + 2);
+ }
+
+ const split = (part: string) => (part === "" ? [] : part.split(":"));
+ const headGroups = split(head);
+ const tailGroups = split(tail);
+
+ const last = tailGroups.length ? tailGroups[tailGroups.length - 1] : headGroups[headGroups.length - 1];
+ if (last && IPV4_RE.test(last)) {
+ const octets = last.split(".").map(Number);
+ const asGroups = [(octets[0] * 256 + octets[1]).toString(16), (octets[2] * 256 + octets[3]).toString(16)];
+ if (tailGroups.length) tailGroups.splice(-1, 1, ...asGroups);
+ else headGroups.splice(-1, 1, ...asGroups);
+ }
+
+ const fill = new Array(8 - headGroups.length - tailGroups.length).fill("0") as string[];
+ return [...headGroups, ...(doubleColonIdx === -1 ? [] : fill), ...tailGroups]
+ .map((group) => group.toLowerCase().padStart(4, "0"))
+ .join(":");
+};
+
+// An IPv4-mapped IPv6 address is compared as the IPv4 host it names, as Go's net.ParseIP does.
+const MAPPED_IPV4_PREFIX = "0000:0000:0000:0000:0000:ffff:";
+
+const collapseMappedIpv4 = (expanded: string): string | null => {
+ if (!expanded.startsWith(MAPPED_IPV4_PREFIX)) return null;
+ const [high, low] = expanded
+ .slice(MAPPED_IPV4_PREFIX.length)
+ .split(":")
+ .map((group) => parseInt(group, 16));
+ return [Math.floor(high / 256), high % 256, Math.floor(low / 256), low % 256].join(".");
+};
+
+const EMPTY_ENTRY_ERROR = "Host pattern has an empty entry";
+const REQUIRED_ERROR = "Host pattern is required";
+
+type TParseResult = { pattern: TAgentVaultHostPattern } | { error: string };
+
+const parseSegment = (segment: string, subject: string): TParseResult => {
+ const raw = segment.trim();
+ if (raw === "") return { error: EMPTY_ENTRY_ERROR };
+ if (raw.includes("://")) return { error: `"${raw}" must not include a scheme (e.g. https://)` };
+ if (raw.includes("/")) {
+ return {
+ error: `"${raw}" must not include a path. A ${subject} covers a whole host, so remove everything from the first "/".`
+ };
+ }
+
+ let host: string;
+ let port = "";
+ let isIpv6 = false;
+
+ if (raw.startsWith("[")) {
+ const closingIdx = raw.indexOf("]");
+ if (closingIdx === -1) return { error: `"${raw}" has an unclosed IPv6 bracket` };
+
+ const inner = raw.slice(1, closingIdx);
+ if (!IPV6_SCHEMA.safeParse(inner).success) return { error: `"${raw}" is not a valid IPv6 address` };
+
+ host = expandIpv6(inner);
+ const mappedIpv4 = collapseMappedIpv4(host);
+ if (mappedIpv4) host = mappedIpv4;
+ else isIpv6 = true;
+
+ const afterBracket = raw.slice(closingIdx + 1);
+ if (afterBracket) {
+ if (!afterBracket.startsWith(":") || !isValidPort(afterBracket.slice(1))) {
+ return { error: `"${raw}" has an invalid port. A port is 1 to 65535, with no leading zeros.` };
+ }
+ port = afterBracket.slice(1);
+ }
+ } else {
+ host = raw;
+ const colonIdx = raw.lastIndexOf(":");
+ if (colonIdx !== -1) {
+ host = raw.slice(0, colonIdx);
+ const portStr = raw.slice(colonIdx + 1);
+ if (!isValidPort(portStr))
+ return { error: `"${raw}" has an invalid port. A port is 1 to 65535, with no leading zeros.` };
+ port = portStr;
+ }
+
+ host = host.replace(/\.$/, "");
+
+ if (host === "*") {
+ return { error: `"${raw}" is too broad. A ${subject} must name specific hosts.` };
+ }
+
+ if (!HOST_LABELS_RE.test(host)) return { error: `"${raw}" is not a valid host pattern` };
+ host = host.toLowerCase();
+ }
+
+ const resolvedPort = port || AGENT_VAULT_DEFAULT_PORT;
+ return {
+ pattern: {
+ host,
+ port: resolvedPort,
+ isWildcard: host.startsWith("*."),
+ key: isIpv6 ? `[${host}]:${resolvedPort}` : `${host}:${resolvedPort}`
+ }
+ };
+};
+
+export const parseHostPatterns = (
+ raw: string,
+ subject = "service"
+): { patterns: TAgentVaultHostPattern[]; errors: string[] } => {
+ const patterns: TAgentVaultHostPattern[] = [];
+ const errors: string[] = [];
+
+ raw.split(",").forEach((segment) => {
+ const result = parseSegment(segment, subject);
+ if ("error" in result) {
+ errors.push(result.error);
+ return;
+ }
+ if (patterns.some((existing) => existing.key === result.pattern.key)) {
+ errors.push(`"${result.pattern.key}" is listed more than once`);
+ return;
+ }
+ patterns.push(result.pattern);
+ });
+
+ // An empty or comma-only value is one problem, not one per segment plus a summary.
+ if (!patterns.length && errors.every((error) => error === EMPTY_ENTRY_ERROR)) {
+ return { patterns, errors: [REQUIRED_ERROR] };
+ }
+ return { patterns, errors };
+};
+
+// Stored as typed, not rewritten: normalising grows the string (`[::1]` becomes 45 characters) and could
+// overflow the column after the length check had passed.
+export const buildHostPatternSchema = (subject: string) =>
+ z
+ .string()
+ .trim()
+ .max(AGENT_VAULT_MAX_HOST_PATTERN_LENGTH)
+ .superRefine((raw, ctx) => {
+ parseHostPatterns(raw, subject).errors.forEach((message) => {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message });
+ });
+ });
+
+export const hostPatternSchema = buildHostPatternSchema("service");
+
+export const matchesHost = (pattern: TAgentVaultHostPattern, host: string, port: string): boolean => {
+ if (pattern.port !== port) return false;
+
+ let candidate = host.trim().replace(/\.$/, "").toLowerCase();
+ if (candidate.startsWith("[") && candidate.endsWith("]")) candidate = candidate.slice(1, -1);
+ if (IPV6_SCHEMA.safeParse(candidate).success) {
+ candidate = expandIpv6(candidate);
+ candidate = collapseMappedIpv4(candidate) ?? candidate;
+ }
+
+ if (!pattern.isWildcard) return pattern.host === candidate;
+
+ const suffix = pattern.host.slice(1);
+ if (!candidate.endsWith(suffix)) return false;
+ const prefix = candidate.slice(0, candidate.length - suffix.length);
+ return prefix !== "" && !prefix.includes(".");
+};
+
+export enum AgentVaultPatternRelation {
+ Identical = "identical",
+ Contained = "contained",
+ Disjoint = "disjoint"
+}
+
+// A wildcard is leftmost-only and matches exactly one label, so two patterns stand in exactly one of
+// these three relations. There is no partial overlap, which is what makes conflict detection exact.
+export const relateHostPatterns = (a: TAgentVaultHostPattern, b: TAgentVaultHostPattern): AgentVaultPatternRelation => {
+ if (a.port !== b.port) return AgentVaultPatternRelation.Disjoint;
+ if (a.host === b.host) return AgentVaultPatternRelation.Identical;
+
+ const covers = (wildcard: TAgentVaultHostPattern, exact: TAgentVaultHostPattern) => {
+ if (!wildcard.isWildcard || exact.isWildcard) return false;
+ const suffix = wildcard.host.slice(1);
+ if (!exact.host.endsWith(suffix)) return false;
+ const prefix = exact.host.slice(0, exact.host.length - suffix.length);
+ return prefix !== "" && !prefix.includes(".");
+ };
+
+ if (covers(a, b) || covers(b, a)) return AgentVaultPatternRelation.Contained;
+ return AgentVaultPatternRelation.Disjoint;
+};
+
+export const intersectHostPatterns = (a: string, b: string): string[] => {
+ const bKeys = new Set(parseHostPatterns(b).patterns.map((pattern) => pattern.key));
+ return parseHostPatterns(a)
+ .patterns.map((pattern) => pattern.key)
+ .filter((key) => bKeys.has(key));
+};
diff --git a/backend/src/ee/services/agent-vault/agent-vault-permission.ts b/backend/src/ee/services/agent-vault/agent-vault-permission.ts
new file mode 100644
index 0000000000..7b7718afc8
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-permission.ts
@@ -0,0 +1,87 @@
+import { Knex } from "knex";
+
+import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
+import { isActiveRole } from "@app/ee/services/permission/permission-fns";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+
+import { TAgentVaultActorContext } from "./agent-vault-actor-types";
+
+type TProjectPermissionResult = Awaited<ReturnType<TPermissionServiceFactory["getProjectPermission"]>>;
+
+export type TAgentVaultReachability = {
+ permission: TProjectPermissionResult["permission"];
+ isAdmin: boolean;
+ accessBundleIds: string[] | null;
+};
+
+export type TAgentVaultGrantActor = {
+ type: ActorType.USER | ActorType.IDENTITY;
+ id: string;
+};
+
+type TPermissionDep = Pick<TPermissionServiceFactory, "getProjectPermission">;
+type TMembershipDep = Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+type TProjectMemberships = TProjectPermissionResult["memberships"];
+
+// A group's grants count only while the group confers a live Agent Vault role.
+export const liveGroupIdsFrom = (memberships: TProjectMemberships): string[] =>
+ memberships.filter((m) => m.actorGroupId && m.roles.some((role) => isActiveRole(role))).map((m) => m.actorGroupId!);
+
+export const findReachableAccessBundleIds = async (
+ membershipDAL: TMembershipDep,
+ { projectId, actor, groupIds }: { projectId: string; actor: TAgentVaultGrantActor; groupIds: string[] },
+ tx?: Knex
+): Promise<string[]> => {
+ const rows = await membershipDAL.findResourceMembershipsForActor(
+ {
+ projectId,
+ resourceType: ResourceType.AgentVaultAccessBundle,
+ actorType: actor.type,
+ actorId: actor.id
+ },
+ tx
+ );
+
+ const liveGroups = new Set(groupIds);
+ const reachable = rows.filter((row) => {
+ if (!row.isActive) return false;
+ if (row.actorGroupId) return liveGroups.has(row.actorGroupId);
+ return true;
+ });
+
+ return [...new Set(reachable.map((row) => row.scopeResourceId!))];
+};
+
+// A service-layer filter rather than a CASL condition: conditions interpolate only identity.id,
+// username and metadata.
+export const getAgentVaultReachability = async (
+ { permissionService, membershipDAL }: { permissionService: TPermissionDep; membershipDAL: TMembershipDep },
+ { projectId, ctx }: { projectId: string; ctx: TAgentVaultActorContext },
+ tx?: Knex
+): Promise<TAgentVaultReachability> => {
+ const { permission, hasRole, memberships } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+
+ const isAdmin = hasRole(ProjectMembershipRole.Admin);
+ if (isAdmin) return { isAdmin, accessBundleIds: null, permission };
+
+ if (ctx.actor !== ActorType.USER && ctx.actor !== ActorType.IDENTITY) {
+ return { isAdmin: false, accessBundleIds: [], permission };
+ }
+
+ const accessBundleIds = await findReachableAccessBundleIds(
+ membershipDAL,
+ { projectId, actor: { type: ctx.actor, id: ctx.actorId }, groupIds: liveGroupIdsFrom(memberships) },
+ tx
+ );
+
+ return { isAdmin: false, accessBundleIds, permission };
+};
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts
index 599c18c2fe..bd73105645 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts
@@ -26,6 +26,7 @@ export enum AuditLogStreamProduct {
KMS = "kms",
SecretScanning = "secret-scanning",
PAM = "pam",
+ AgentVault = "agent-vault",
// Org-level events (no associated project), e.g. SSO, org settings, user/identity management.
Organization = "organization"
}
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 9df2a0d992..2465c7d2de 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -99,7 +99,8 @@ export type TCreateAuditLogDTO = {
| ScepAccountActor
| GatewayActor
| RelayActor
- | KmipServerActor;
+ | KmipServerActor
+ | AgentVaultProxyActor;
orgId?: string;
projectId?: string;
} & BaseAuthData;
@@ -754,6 +755,25 @@ export enum EventType {
PAM_ACCESS_REQUEST_REVIEW = "pam-access-request-review",
PAM_ACCESS_GRANT_REVOKE = "pam-access-grant-revoke",
PAM_APPROVAL_CONFIG_UPDATE = "pam-approval-config-update",
+ AGENT_VAULT_ACCESS_BUNDLE_CREATE = "agent-vault-access-bundle-create",
+ AGENT_VAULT_ACCESS_BUNDLE_UPDATE = "agent-vault-access-bundle-update",
+ AGENT_VAULT_ACCESS_BUNDLE_DELETE = "agent-vault-access-bundle-delete",
+ AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",
+ AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",
+ AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",
+ AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",
+ AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",
+ AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",
+ AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD = "agent-vault-access-bundle-member-add",
+ AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",
+ AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",
+ AGENT_VAULT_SESSION_REVOKE = "agent-vault-session-revoke",
+ AGENT_VAULT_PROXY_REGISTER = "agent-vault-proxy-register",
+ AGENT_VAULT_PROXY_TOKEN_REISSUE = "agent-vault-proxy-token-reissue",
+ AGENT_VAULT_PROXY_ENROLL = "agent-vault-proxy-enroll",
+ AGENT_VAULT_PROXY_UPDATE = "agent-vault-proxy-update",
+ AGENT_VAULT_PROXY_REVOKE = "agent-vault-proxy-revoke",
+ AGENT_VAULT_PROXY_DELETE = "agent-vault-proxy-delete",
APPROVAL_POLICY_CREATE = "approval-policy-create",
APPROVAL_POLICY_UPDATE = "approval-policy-update",
APPROVAL_POLICY_DELETE = "approval-policy-delete",
@@ -932,7 +952,8 @@ export const ACTOR_TYPE_TO_METADATA_ID_KEY: Partial<Record<ActorType, string>> =
[ActorType.SCEP_ACCOUNT]: "profileId",
[ActorType.GATEWAY]: "gatewayId",
[ActorType.RELAY]: "relayId",
- [ActorType.KMIP_SERVER]: "kmipServerId"
+ [ActorType.KMIP_SERVER]: "kmipServerId",
+ [ActorType.AGENT_VAULT_PROXY]: "agentVaultProxyId"
};
export const filterableSecretEvents: EventType[] = [
@@ -1009,6 +1030,10 @@ interface KmipServerActorMetadata {
kmipServerId: string;
}
+interface AgentVaultProxyActorMetadata {
+ agentVaultProxyId: string;
+}
+
export interface UserActor {
type: ActorType.USER;
metadata: UserActorMetadata;
@@ -1078,6 +1103,11 @@ export interface KmipServerActor {
metadata: KmipServerActorMetadata;
}
+export interface AgentVaultProxyActor {
+ type: ActorType.AGENT_VAULT_PROXY;
+ metadata: AgentVaultProxyActorMetadata;
+}
+
export type Actor =
| UserActor
| ServiceActor
@@ -1091,7 +1121,8 @@ export type Actor =
| ScepAccountActor
| GatewayActor
| RelayActor
- | KmipServerActor;
+ | KmipServerActor
+ | AgentVaultProxyActor;
interface GetSecretsEvent {
type: EventType.GET_SECRETS;
@@ -6079,6 +6110,197 @@ interface PamWebAccessSessionTicketCreatedEvent {
};
}
+interface AgentVaultProxyRegisterEvent {
+ type: EventType.AGENT_VAULT_PROXY_REGISTER;
+ metadata: {
+ proxyId: string;
+ name: string;
+ };
+}
+
+interface AgentVaultProxyTokenReissueEvent {
+ type: EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE;
+ metadata: {
+ proxyId: string;
+ name: string;
+ };
+}
+
+interface AgentVaultProxyEnrollEvent {
+ type: EventType.AGENT_VAULT_PROXY_ENROLL;
+ metadata: {
+ proxyId: string;
+ name: string;
+ rootCaFingerprint: string;
+ replacedExistingCa: boolean;
+ };
+}
+
+interface AgentVaultProxyUpdateEvent {
+ type: EventType.AGENT_VAULT_PROXY_UPDATE;
+ metadata: {
+ proxyId: string;
+ name?: string;
+ trafficPolicy?: string;
+ allowedHosts?: string | null;
+ pollInterval?: number;
+ };
+}
+
+interface AgentVaultProxyRevokeEvent {
+ type: EventType.AGENT_VAULT_PROXY_REVOKE;
+ metadata: {
+ proxyId: string;
+ name: string;
+ };
+}
+
+interface AgentVaultProxyDeleteEvent {
+ type: EventType.AGENT_VAULT_PROXY_DELETE;
+ metadata: {
+ proxyId: string;
+ name: string;
+ };
+}
+
+interface AgentVaultAccessBundleCreateEvent {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_CREATE;
+ metadata: {
+ accessBundleId: string;
+ name: string;
+ description?: string | null;
+ };
+}
+
+interface AgentVaultAccessBundleUpdateEvent {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_UPDATE;
+ metadata: {
+ accessBundleId: string;
+ name?: string;
+ description?: string | null;
+ };
+}
+
+interface AgentVaultAccessBundleDeleteEvent {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_DELETE;
+ metadata: {
+ accessBundleId: string;
+ name: string;
+ };
+}
+
+interface AgentVaultServiceCreateEvent {
+ type: EventType.AGENT_VAULT_SERVICE_CREATE;
+ metadata: {
+ accessBundleId: string;
+ serviceId: string;
+ name: string;
+ hostPattern: string;
+ credentialType: string;
+ headerName?: string;
+ headerPrefix?: string;
+ };
+}
+
+interface AgentVaultServiceUpdateEvent {
+ type: EventType.AGENT_VAULT_SERVICE_UPDATE;
+ metadata: {
+ accessBundleId: string;
+ serviceId: string;
+ name?: string;
+ hostPattern?: string;
+ credentialType?: string;
+ headerName?: string;
+ headerPrefix?: string;
+ credentialReplaced: boolean;
+ };
+}
+
+interface AgentVaultServiceDeleteEvent {
+ type: EventType.AGENT_VAULT_SERVICE_DELETE;
+ metadata: {
+ accessBundleId: string;
+ serviceId: string;
+ name: string;
+ };
+}
+
+interface AgentVaultProductMemberAddEvent {
+ type: EventType.AGENT_VAULT_MEMBER_ADD;
+ metadata: {
+ userId?: string;
+ userName?: string;
+ groupId?: string;
+ groupName?: string;
+ identityId?: string;
+ identityName?: string;
+ role: string;
+ };
+}
+
+interface AgentVaultProductMemberUpdateEvent {
+ type: EventType.AGENT_VAULT_MEMBER_UPDATE;
+ metadata: {
+ userId?: string;
+ userName?: string;
+ groupId?: string;
+ groupName?: string;
+ identityId?: string;
+ identityName?: string;
+ role: string;
+ };
+}
+
+interface AgentVaultProductMemberRemoveEvent {
+ type: EventType.AGENT_VAULT_MEMBER_REMOVE;
+ metadata: {
+ userId?: string;
+ userName?: string;
+ groupId?: string;
+ groupName?: string;
+ identityId?: string;
+ identityName?: string;
+ };
+}
+
+interface AgentVaultAccessBundleMemberAddEvent {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD;
+ metadata: {
+ accessBundleId: string;
+ accessBundleName: string;
+ memberId: string;
+ userId?: string;
+ identityId?: string;
+ groupId?: string;
+ };
+}
+
+interface AgentVaultAccessBundleMemberRemoveEvent {
+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE;
+ metadata: {
+ accessBundleId: string;
+ accessBundleName: string;
+ memberId: string;
+ };
+}
+
+interface AgentVaultSessionMintEvent {
+ type: EventType.AGENT_VAULT_SESSION_MINT;
+ metadata: {
+ sessionId: string;
+ accessBundleId: string;
+ accessBundleName: string;
+ expiresAt: string | null;
+ };
+}
+
+interface AgentVaultSessionRevokeEvent {
+ type: EventType.AGENT_VAULT_SESSION_REVOKE;
+ metadata: {
+ sessionId: string;
+ };
+}
+
interface PamAccountCreateEvent {
type: EventType.PAM_ACCOUNT_CREATE;
metadata: {
@@ -7876,6 +8098,25 @@ export type Event =
| PamAccountMemberRemoveEvent
| PamAccountAccessEvent
| PamWebAccessSessionTicketCreatedEvent
+ | AgentVaultAccessBundleCreateEvent
+ | AgentVaultAccessBundleUpdateEvent
+ | AgentVaultAccessBundleDeleteEvent
+ | AgentVaultServiceCreateEvent
+ | AgentVaultServiceUpdateEvent
+ | AgentVaultServiceDeleteEvent
+ | AgentVaultProductMemberAddEvent
+ | AgentVaultProductMemberUpdateEvent
+ | AgentVaultProductMemberRemoveEvent
+ | AgentVaultAccessBundleMemberAddEvent
+ | AgentVaultAccessBundleMemberRemoveEvent
+ | AgentVaultSessionMintEvent
+ | AgentVaultSessionRevokeEvent
+ | AgentVaultProxyRegisterEvent
+ | AgentVaultProxyTokenReissueEvent
+ | AgentVaultProxyEnrollEvent
+ | AgentVaultProxyUpdateEvent
+ | AgentVaultProxyRevokeEvent
+ | AgentVaultProxyDeleteEvent
| PamAccountCreateEvent
| PamAccountUpdateEvent
| PamAccountDeleteEvent
diff --git a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts b/backend/src/ee/services/github-org-sync/github-org-sync-service.ts
index 01435c436c..4904186785 100644
--- a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts
+++ b/backend/src/ee/services/github-org-sync/github-org-sync-service.ts
@@ -14,7 +14,7 @@ import { retryWithBackoff } from "@app/lib/retry";
import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
@@ -781,6 +781,7 @@ export const githubOrgSyncServiceFactory = ({
// Group membership changes cascade into the group-expanded project identity meters.
usageMeteringService.emit(orgId, SecretIdentities.key);
usageMeteringService.emit(orgId, PamIdentities.key);
+ usageMeteringService.emit(orgId, AgentVaultIdentities.key);
}
};
@@ -1201,6 +1202,7 @@ export const githubOrgSyncServiceFactory = ({
// Team membership changes cascade into the group-expanded project identity meters.
usageMeteringService.emit(orgPermission.orgId, SecretIdentities.key);
usageMeteringService.emit(orgPermission.orgId, PamIdentities.key);
+ usageMeteringService.emit(orgPermission.orgId, AgentVaultIdentities.key);
}
if (unmatchedGithubUsers.size) {
diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.ts
index 61bdd5c989..80c7c6ccfd 100644
--- a/backend/src/ee/services/group/group-fns.ts
+++ b/backend/src/ee/services/group/group-fns.ts
@@ -5,7 +5,7 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, ScimRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import {
TAddIdentitiesToGroup,
@@ -307,6 +307,7 @@ export const addUsersToGroupByUserIds = async ({
// These users may now be in a secret-manager or PAM project through this group.
usageMeteringService?.emit(group.orgId, SecretIdentities.key);
usageMeteringService?.emit(group.orgId, PamIdentities.key);
+ usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
return membersToAddToGroupNonPending.concat(membersToAddToGroupPending);
};
@@ -382,6 +383,7 @@ export const addIdentitiesToGroup = async ({
// These identities may now be in a secret-manager or PAM project through this group.
usageMeteringService?.emit(group.orgId, SecretIdentities.key);
usageMeteringService?.emit(group.orgId, PamIdentities.key);
+ usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
return identityIdsArray.map((identityId) => ({ id: identityId }));
});
};
@@ -581,6 +583,7 @@ export const removeUsersFromGroupByUserIds = async ({
// These users may have left a secret-manager or PAM project they only reached through this group.
usageMeteringService?.emit(group.orgId, SecretIdentities.key);
usageMeteringService?.emit(group.orgId, PamIdentities.key);
+ usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
return membersToRemoveFromGroupNonPending.concat(membersToRemoveFromGroupPending);
};
@@ -704,6 +707,7 @@ export const removeIdentitiesFromGroup = async ({
// These identities may have left a secret-manager or PAM project they only reached through this group.
usageMeteringService?.emit(group.orgId, SecretIdentities.key);
usageMeteringService?.emit(group.orgId, PamIdentities.key);
+ usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
return identityIdsArray.map((identityId) => ({ id: identityId }));
});
};
diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts
index 740a8fe34a..dda8a153cc 100644
--- a/backend/src/ee/services/group/group-service.ts
+++ b/backend/src/ee/services/group/group-service.ts
@@ -29,7 +29,7 @@ import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-chan
import { prepareDeletedGroupAlertRecipientCleanup } from "@app/services/alert/alert-recipient-cleanup-fns";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TIdentityAccessTokenServiceFactory } from "@app/services/identity-access-token/identity-access-token-service";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { resolveMembershipRoleSlugs } from "@app/services/membership/membership-fns";
@@ -750,6 +750,7 @@ export const groupServiceFactory = ({
// Removing the group drops its members from any project it was on.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
+ usageMeteringService.emit(actorOrgId, AgentVaultIdentities.key);
return { group: unlinkedGroup, isUnlinked: true };
}
@@ -757,6 +758,7 @@ export const groupServiceFactory = ({
// Deleting the group drops its members from any project it was on.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
+ usageMeteringService.emit(actorOrgId, AgentVaultIdentities.key);
return { group: deletedGroup, isUnlinked: false };
};
@@ -1100,6 +1102,7 @@ export const groupServiceFactory = ({
// The user may now be in a secret-manager or PAM project through this group.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
+ usageMeteringService.emit(actorOrgId, AgentVaultIdentities.key);
return { user: users[0], group: groupMembership.group };
};
@@ -1210,6 +1213,7 @@ export const groupServiceFactory = ({
// The identity may now be in a secret-manager or PAM project through this group.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
+ usageMeteringService.emit(actorOrgId, AgentVaultIdentities.key);
return { identity: identities[0], group: groupMembership.group };
};
@@ -1305,6 +1309,7 @@ export const groupServiceFactory = ({
// The user may have left a secret-manager or PAM project it only reached through this group.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
+ usageMeteringService.emit(actorOrgId, AgentVaultIdentities.key);
return { user: users[0], group: groupMembership.group };
};
@@ -1398,6 +1403,7 @@ export const groupServiceFactory = ({
// The identity may have left a secret-manager or PAM project it only reached through this group.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
+ usageMeteringService.emit(actorOrgId, AgentVaultIdentities.key);
return { identity: identities[0], group: groupMembership.group };
};
diff --git a/backend/src/ee/services/permission/agent-vault-project-roles.test.ts b/backend/src/ee/services/permission/agent-vault-project-roles.test.ts
new file mode 100644
index 0000000000..5e49e61033
--- /dev/null
+++ b/backend/src/ee/services/permission/agent-vault-project-roles.test.ts
@@ -0,0 +1,126 @@
+import { createMongoAbility } from "@casl/ability";
+import { packRules } from "@casl/ability/extra";
+import { describe, expect, test } from "vitest";
+
+import { ProjectMembershipRole, ProjectType, ResourceMembershipRole, ResourceType } from "@app/db/schemas";
+import { AgentVaultResourceRole } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { PamResourceRole } from "@app/ee/services/pam/pam-enums";
+import { NotFoundError } from "@app/lib/errors";
+
+import {
+ agentVaultProjectAdminPermissions,
+ applicationAuditorPermissions,
+ pamResourceAdminPermissions,
+ signerOperatorPermissions
+} from "./default-roles";
+import { buildProjectPermissionRules, resolveResourceRoleRules } from "./permission-service";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionAgentVaultProxyActions,
+ ProjectPermissionAgentVaultSessionActions,
+ ProjectPermissionCmekActions,
+ ProjectPermissionGroupActions,
+ ProjectPermissionIdentityActions,
+ ProjectPermissionMemberActions,
+ ProjectPermissionSecretSyncActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "./project-permission";
+
+const abilityFor = (role: string, permissions?: unknown) =>
+ createMongoAbility<ProjectPermissionSet>(
+ buildProjectPermissionRules(
+ [{ role, permissions }] as Parameters<typeof buildProjectPermissionRules>[0],
+ ProjectType.AgentVault
+ ) as never
+ );
+
+describe("agent vault project roles", () => {
+ test("the admin set is written out, not aliased to the generic project admin", () => {
+ const admin = abilityFor(ProjectMembershipRole.Admin);
+
+ expect(
+ admin.can(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ )
+ ).toBe(true);
+ expect(admin.can(ProjectPermissionAgentVaultProxyActions.Revoke, ProjectPermissionSub.AgentVaultProxies)).toBe(
+ true
+ );
+ expect(admin.can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project)).toBe(true);
+
+ expect(admin.can(ProjectPermissionCmekActions.Rotate, ProjectPermissionSub.Cmek)).toBe(false);
+ expect(admin.can(ProjectPermissionSecretSyncActions.Create, ProjectPermissionSub.SecretSyncs)).toBe(false);
+ expect(admin.can(ProjectPermissionActions.Create, ProjectPermissionSub.ServiceTokens)).toBe(false);
+ });
+
+ test("a member can mint and revoke sessions and read a proxy fingerprint, and nothing more", () => {
+ const member = abilityFor(ProjectMembershipRole.Member);
+
+ expect(member.can(ProjectPermissionAgentVaultSessionActions.Create, ProjectPermissionSub.AgentVaultSessions)).toBe(
+ true
+ );
+ expect(member.can(ProjectPermissionAgentVaultSessionActions.Revoke, ProjectPermissionSub.AgentVaultSessions)).toBe(
+ true
+ );
+ expect(member.can(ProjectPermissionAgentVaultProxyActions.Read, ProjectPermissionSub.AgentVaultProxies)).toBe(true);
+
+ expect(member.can(ProjectPermissionAgentVaultProxyActions.Create, ProjectPermissionSub.AgentVaultProxies)).toBe(
+ false
+ );
+ expect(
+ member.can(ProjectPermissionAgentVaultAccessBundleActions.Create, ProjectPermissionSub.AgentVaultAccessBundles)
+ ).toBe(false);
+ expect(
+ member.can(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ )
+ ).toBe(false);
+ expect(member.can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project)).toBe(false);
+
+ expect(member.can(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member)).toBe(false);
+ expect(member.can(ProjectPermissionGroupActions.Read, ProjectPermissionSub.Groups)).toBe(false);
+ expect(member.can(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity)).toBe(false);
+ });
+
+ test("a custom role carrying the full admin rules still resolves to the member set", () => {
+ const custom = abilityFor(ProjectMembershipRole.Custom, packRules(agentVaultProjectAdminPermissions as never));
+
+ expect(
+ custom.can(ProjectPermissionAgentVaultAccessBundleActions.Read, ProjectPermissionSub.AgentVaultAccessBundles)
+ ).toBe(true);
+ expect(
+ custom.can(ProjectPermissionAgentVaultAccessBundleActions.Delete, ProjectPermissionSub.AgentVaultAccessBundles)
+ ).toBe(false);
+ expect(
+ custom.can(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ )
+ ).toBe(false);
+ expect(custom.can(ProjectPermissionAgentVaultProxyActions.Delete, ProjectPermissionSub.AgentVaultProxies)).toBe(
+ false
+ );
+ expect(custom.can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project)).toBe(false);
+ });
+});
+
+describe("resource role dispatch", () => {
+ test("an agent vault consumer carries no rules, and an unknown slug fails loudly", () => {
+ expect(resolveResourceRoleRules(ResourceType.AgentVaultAccessBundle, AgentVaultResourceRole.Consumer)).toEqual([]);
+ expect(() => resolveResourceRoleRules(ResourceType.AgentVaultAccessBundle, "admin")).toThrow(NotFoundError);
+ });
+
+ test("the other products' arms are untouched", () => {
+ expect(resolveResourceRoleRules(ResourceType.PamFolder, PamResourceRole.Admin)).toBe(pamResourceAdminPermissions);
+ expect(resolveResourceRoleRules(ResourceType.Signer, ResourceMembershipRole.Operator)).toBe(
+ signerOperatorPermissions
+ );
+ expect(resolveResourceRoleRules(ResourceType.CertificateApplication, ResourceMembershipRole.Auditor)).toBe(
+ applicationAuditorPermissions
+ );
+ });
+});
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index fff38d43bc..5a6ef153dd 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -2,6 +2,9 @@ import { AbilityBuilder, createMongoAbility, MongoAbility } from "@casl/ability"
import {
ProjectPermissionActions,
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionAgentVaultProxyActions,
+ ProjectPermissionAgentVaultSessionActions,
ProjectPermissionAppConnectionActions,
ProjectPermissionApplicationActions,
ProjectPermissionApprovalRequestActions,
@@ -792,6 +795,126 @@ const buildPamProjectMemberPermissionRules = () => {
return rules;
};
+// The admin set is written out rather than aliased to projectAdminPermissions: an Agent Vault admin has
+// no business rotating CMEKs or minting service tokens.
+const buildAgentVaultProjectAdminPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
+
+ can(
+ [
+ ProjectPermissionAgentVaultAccessBundleActions.Read,
+ ProjectPermissionAgentVaultAccessBundleActions.Create,
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionAgentVaultAccessBundleActions.Delete,
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers
+ ],
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+
+ can(
+ [
+ ProjectPermissionAgentVaultSessionActions.Read,
+ ProjectPermissionAgentVaultSessionActions.Create,
+ ProjectPermissionAgentVaultSessionActions.Revoke
+ ],
+ ProjectPermissionSub.AgentVaultSessions
+ );
+
+ can(
+ [
+ ProjectPermissionAgentVaultProxyActions.Read,
+ ProjectPermissionAgentVaultProxyActions.Create,
+ ProjectPermissionAgentVaultProxyActions.Edit,
+ ProjectPermissionAgentVaultProxyActions.Delete,
+ ProjectPermissionAgentVaultProxyActions.IssueToken,
+ ProjectPermissionAgentVaultProxyActions.Revoke
+ ],
+ ProjectPermissionSub.AgentVaultProxies
+ );
+
+ can(
+ [
+ ProjectPermissionMemberActions.Create,
+ ProjectPermissionMemberActions.Edit,
+ ProjectPermissionMemberActions.Delete,
+ ProjectPermissionMemberActions.Read,
+ ProjectPermissionMemberActions.GrantPrivileges,
+ ProjectPermissionMemberActions.AssignRole,
+ ProjectPermissionMemberActions.AssignAdditionalPrivileges,
+ ProjectPermissionMemberActions.AssumePrivileges
+ ],
+ ProjectPermissionSub.Member
+ );
+
+ can(
+ [
+ ProjectPermissionGroupActions.Create,
+ ProjectPermissionGroupActions.Edit,
+ ProjectPermissionGroupActions.Delete,
+ ProjectPermissionGroupActions.Read,
+ ProjectPermissionGroupActions.GrantPrivileges,
+ ProjectPermissionGroupActions.AssignRole
+ ],
+ ProjectPermissionSub.Groups
+ );
+
+ can(
+ [
+ ProjectPermissionIdentityActions.Create,
+ ProjectPermissionIdentityActions.Edit,
+ ProjectPermissionIdentityActions.Delete,
+ ProjectPermissionIdentityActions.Read,
+ ProjectPermissionIdentityActions.GrantPrivileges,
+ ProjectPermissionIdentityActions.AssignRole,
+ ProjectPermissionIdentityActions.AssignAdditionalPrivileges,
+ ProjectPermissionIdentityActions.AssumePrivileges,
+ ProjectPermissionIdentityActions.GetToken,
+ ProjectPermissionIdentityActions.CreateToken,
+ ProjectPermissionIdentityActions.DeleteToken,
+ ProjectPermissionIdentityActions.RevokeAuth,
+ ProjectPermissionIdentityActions.EditAuth
+ ],
+ ProjectPermissionSub.Identity
+ );
+
+ [ProjectPermissionSub.Role, ProjectPermissionSub.Settings].forEach((subject) => {
+ can(
+ [
+ ProjectPermissionActions.Read,
+ ProjectPermissionActions.Edit,
+ ProjectPermissionActions.Create,
+ ProjectPermissionActions.Delete
+ ],
+ subject
+ );
+ });
+
+ can([ProjectPermissionActions.Edit, ProjectPermissionActions.Delete], ProjectPermissionSub.Project);
+
+ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
+
+ return rules;
+};
+
+// Deliberately narrower than PAM's member set: no directory reads, or any member could enumerate every
+// person, group and machine identity in the product.
+const buildAgentVaultProjectMemberPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
+
+ can([ProjectPermissionAgentVaultAccessBundleActions.Read], ProjectPermissionSub.AgentVaultAccessBundles);
+ can(
+ [
+ ProjectPermissionAgentVaultSessionActions.Read,
+ ProjectPermissionAgentVaultSessionActions.Create,
+ ProjectPermissionAgentVaultSessionActions.Revoke
+ ],
+ ProjectPermissionSub.AgentVaultSessions
+ );
+ can([ProjectPermissionAgentVaultProxyActions.Read], ProjectPermissionSub.AgentVaultProxies);
+
+ return rules;
+};
+
const buildCryptographicOperatorPermissionRules = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
@@ -1181,6 +1304,8 @@ const buildPamResourceAuditorPermissionRules = () => {
// The product admin owns the PAM project, so it keeps the full project Admin ability it has always had.
export const pamProjectAdminPermissions = projectAdminPermissions;
+export const agentVaultProjectAdminPermissions = buildAgentVaultProjectAdminPermissionRules();
+export const agentVaultProjectMemberPermissions = buildAgentVaultProjectMemberPermissionRules();
export const pamProjectMemberPermissions = buildPamProjectMemberPermissionRules();
export const pamResourceAdminPermissions = buildPamResourceAdminPermissionRules();
export const pamResourceOperatorPermissions = buildPamResourceOperatorPermissionRules();
diff --git a/backend/src/ee/services/permission/permission-service-types.ts b/backend/src/ee/services/permission/permission-service-types.ts
index fbeba9b91a..87d97cf27a 100644
--- a/backend/src/ee/services/permission/permission-service-types.ts
+++ b/backend/src/ee/services/permission/permission-service-types.ts
@@ -120,7 +120,16 @@ export type TPermissionServiceFactory = {
}>;
getProjectPermission: (arg: TGetProjectPermissionArg) => Promise<{
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
- memberships: Array<TMemberships & { roles: { role: string; customRoleSlug?: string | null }[] }>;
+ memberships: Array<
+ TMemberships & {
+ roles: {
+ role: string;
+ customRoleSlug?: string | null;
+ isTemporary?: boolean;
+ temporaryAccessEndTime?: Date | null;
+ }[];
+ }
+ >;
hasRole: (role: string) => boolean;
hasProjectEnforcement: (check: "enforceEncryptedSecretManagerSecretMetadata") => boolean;
folderScopedPrivileges: TProjectFolderScopedPrivilege[];
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index 1838e00b63..f52055cca5 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -14,9 +14,12 @@ import {
ServiceTokenScopes,
TProjects
} from "@app/db/schemas";
+import { AgentVaultResourceRole } from "@app/ee/services/agent-vault/agent-vault-enums";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { PamResourceRole } from "@app/ee/services/pam/pam-enums";
import {
+ agentVaultProjectAdminPermissions,
+ agentVaultProjectMemberPermissions,
applicationAdminPermissions,
applicationAuditorPermissions,
applicationOperatorPermissions,
@@ -141,6 +144,9 @@ const buildOrgPermissionRules = (orgUserRoles: TBuildOrgPermissionDTO) => {
const resolvePamProjectRoleRules = (role: string) =>
role === ProjectMembershipRole.Admin ? pamProjectAdminPermissions : pamProjectMemberPermissions;
+const resolveAgentVaultProjectRoleRules = (role: string) =>
+ role === ProjectMembershipRole.Admin ? agentVaultProjectAdminPermissions : agentVaultProjectMemberPermissions;
+
export const buildProjectPermissionRules = (
projectUserRoles: TBuildProjectPermissionDTO,
projectType?: string,
@@ -150,6 +156,7 @@ export const buildProjectPermissionRules = (
projectUserRoles
.map(({ role, permissions }) => {
if (projectType === ProjectType.PAM) return resolvePamProjectRoleRules(role);
+ if (projectType === ProjectType.AgentVault) return resolveAgentVaultProjectRoleRules(role);
switch (role) {
case ProjectMembershipRole.Admin:
@@ -220,6 +227,12 @@ export const resolveResourceRoleRules = (resourceType: ResourceType, role: strin
}
}
+ // The arm exists so this switch never reads an Agent Vault row as a cert-manager application.
+ if (resourceType === ResourceType.AgentVaultAccessBundle) {
+ if (role === AgentVaultResourceRole.Consumer) return [];
+ throw new NotFoundError({ name: "AgentVaultRoleInvalid", message: `Agent Vault role '${role}' not found` });
+ }
+
switch (role) {
case ResourceMembershipRole.Admin:
return applicationAdminPermissions;
@@ -246,9 +259,16 @@ const buildResourcePermissionRules = (appUserRoles: TBuildProjectPermissionDTO,
return rules;
};
+const resolveResourceActionProjectType = (resourceType: ResourceType) => {
+ if (resourceType === ResourceType.PamFolder || resourceType === ResourceType.PamAccount) return ActionProjectType.PAM;
+ if (resourceType === ResourceType.AgentVaultAccessBundle) return ActionProjectType.AgentVault;
+ return ActionProjectType.CertificateManager;
+};
+
const resolveResourceProjectAdminFallback = (resourceType: ResourceType) => {
if (resourceType === ResourceType.Signer) return projectAdminSignerFallbackPermissions;
if (resourceType === ResourceType.PamFolder || resourceType === ResourceType.PamAccount) return [];
+ if (resourceType === ResourceType.AgentVaultAccessBundle) return [];
return projectAdminApplicationFallbackPermissions;
};
@@ -852,10 +872,7 @@ export const permissionServiceFactory = ({
projectId,
actorAuthMethod,
actorOrgId,
- actionProjectType:
- resourceType === ResourceType.PamFolder || resourceType === ResourceType.PamAccount
- ? ActionProjectType.PAM
- : ActionProjectType.CertificateManager
+ actionProjectType: resolveResourceActionProjectType(resourceType)
});
isProjectAdmin = projectPerm.hasRole(ProjectMembershipRole.Admin);
isProjectMember = true;
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 18c4f4aa46..213ee5e877 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -298,6 +298,30 @@ export enum ProjectPermissionProxiedServiceActions {
ReportUsage = "report-usage"
}
+export enum ProjectPermissionAgentVaultAccessBundleActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ ManageMembers = "manage-members"
+}
+
+export enum ProjectPermissionAgentVaultSessionActions {
+ Read = "read",
+ Create = "create",
+ Revoke = "revoke"
+}
+
+export enum ProjectPermissionAgentVaultProxyActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ // Issuing a replacement enrollment token mints a credential that enrolls a new box, so it is not Edit.
+ IssueToken = "issue-token",
+ Revoke = "revoke"
+}
+
export enum ProjectPermissionApprovalRequestActions {
Read = "read",
Create = "create"
@@ -374,6 +398,9 @@ export enum ProjectPermissionSub {
ProjectFolderGrant = "project-folder-grant",
HoneyTokens = "honey-tokens",
ProxiedServices = "proxied-services",
+ AgentVaultAccessBundles = "agent-vault-access-bundles",
+ AgentVaultSessions = "agent-vault-sessions",
+ AgentVaultProxies = "agent-vault-proxies",
Insights = "insights"
}
@@ -692,6 +719,9 @@ export type ProjectPermissionSet =
| (ForcedSubject<ProjectPermissionSub.ProxiedServices> & ProxiedServiceSubjectFields)
)
]
+ | [ProjectPermissionAgentVaultAccessBundleActions, ProjectPermissionSub.AgentVaultAccessBundles]
+ | [ProjectPermissionAgentVaultSessionActions, ProjectPermissionSub.AgentVaultSessions]
+ | [ProjectPermissionAgentVaultProxyActions, ProjectPermissionSub.AgentVaultProxies]
| [
ProjectPermissionCertificateProfileActions,
(
@@ -1623,6 +1653,29 @@ const GeneralPermissionSchema = [
"When specified, only matching conditions will be allowed to access given resource."
).optional()
}),
+ z.object({
+ subject: z
+ .literal(ProjectPermissionSub.AgentVaultAccessBundles)
+ .describe("The entity this permission pertains to."),
+ inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionAgentVaultAccessBundleActions).describe(
+ "Describe what action an entity can take."
+ )
+ }),
+ z.object({
+ subject: z.literal(ProjectPermissionSub.AgentVaultSessions).describe("The entity this permission pertains to."),
+ inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionAgentVaultSessionActions).describe(
+ "Describe what action an entity can take."
+ )
+ }),
+ z.object({
+ subject: z.literal(ProjectPermissionSub.AgentVaultProxies).describe("The entity this permission pertains to."),
+ inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionAgentVaultProxyActions).describe(
+ "Describe what action an entity can take."
+ )
+ }),
z.object({
subject: z.literal(ProjectPermissionSub.ApprovalRequests).describe("The entity this permission pertains to."),
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionApprovalRequestActions).describe(
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts
index f22b8439cb..9cb41ed74c 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts
@@ -80,14 +80,41 @@ export const mintKmipServerJwt = ({
);
};
+/** Non-expiring like the other resource tokens: the tokenVersion check in inject-identity is the only kill switch. */
+export const mintAgentVaultProxyJwt = ({
+ agentVaultProxyId,
+ orgId,
+ tokenVersion,
+ accessTokenTTL
+}: {
+ agentVaultProxyId: string;
+ orgId: string;
+ tokenVersion: number;
+ accessTokenTTL: number;
+}) => {
+ const appCfg = getConfig();
+ return crypto.jwt().sign(
+ {
+ agentVaultProxyId,
+ orgId,
+ authTokenType: AuthTokenType.AGENT_VAULT_PROXY_ACCESS_TOKEN,
+ tokenVersion
+ },
+ appCfg.AUTH_SECRET,
+ accessTokenTTL === 0 ? undefined : { expiresIn: accessTokenTTL }
+ );
+};
+
export type ResourceRef =
| { type: "gateway"; id: string }
| { type: "relay"; id: string }
- | { type: "kmip"; id: string };
+ | { type: "kmip"; id: string }
+ | { type: "agentVaultProxy"; id: string };
export const RESOURCE_TYPE_GATEWAY = "gateway" as const;
export const RESOURCE_TYPE_RELAY = "relay" as const;
export const RESOURCE_TYPE_KMIP = "kmip" as const;
+export const RESOURCE_TYPE_AGENT_VAULT_PROXY = "agentVaultProxy" as const;
export const assertGatewayResource = (resource: { type: string }, methodName: string) => {
if (resource.type !== RESOURCE_TYPE_GATEWAY) {
@@ -113,6 +140,14 @@ export const assertKmipServerResource = (resource: { type: string }, methodName:
}
};
+export const assertAgentVaultProxyResource = (resource: { type: string }, methodName: string) => {
+ if (resource.type !== RESOURCE_TYPE_AGENT_VAULT_PROXY) {
+ throw new BadRequestError({
+ message: `Resource type "${resource.type}" not supported for ${methodName} auth`
+ });
+ }
+};
+
// All auth method values surfaced anywhere in the system.
//
// - 'aws' / 'kubernetes' / 'token': stored in resource_auth_methods.method and settable
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
index b4a3c46ad0..5e37e4e8c7 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
@@ -1,7 +1,7 @@
import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
-import { OrganizationActionScope } from "@app/db/schemas";
+import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
@@ -9,6 +9,7 @@ import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TAgentVaultProxyDALFactory } from "../agent-vault-proxy/agent-vault-proxy-dal";
import { TGatewayPoolDALFactory } from "../gateway-pool/gateway-pool-dal";
import { TGatewayPoolMembershipDALFactory } from "../gateway-pool/gateway-pool-membership-dal";
import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
@@ -22,6 +23,7 @@ import {
OrgPermissionSubjects
} from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
+import { ProjectPermissionAgentVaultProxyActions, ProjectPermissionSub } from "../permission/project-permission";
import { TRelayDALFactory } from "../relay/relay-dal";
import { TResourceAwsAuthDALFactory } from "./aws-auth-dal";
import { validateAllowlists, verifyStsAndExtractCaller } from "./aws-auth-fns";
@@ -42,9 +44,11 @@ import {
assertKmipServerResource,
assertRelayResource,
KubernetesTokenReviewMode,
+ mintAgentVaultProxyJwt,
mintGatewayJwt,
mintKmipServerJwt,
mintRelayJwt,
+ RESOURCE_TYPE_AGENT_VAULT_PROXY,
RESOURCE_TYPE_GATEWAY,
RESOURCE_TYPE_KMIP,
RESOURCE_TYPE_RELAY,
@@ -72,8 +76,15 @@ const ENROLLMENT_TOKEN_TTL_SECONDS = 3600;
// Bounds the reviewer chain walk; nobody legitimately chains proxies this deep.
const MAX_PROXY_CHAIN_DEPTH = 10;
-const $generateEnrollmentToken = () => {
- const plainToken = `gwe_${crypto.randomBytes(32).toString("base64url")}`;
+const ENROLLMENT_TOKEN_PREFIX: Record<ResourceRef["type"], string> = {
+ [RESOURCE_TYPE_GATEWAY]: "gwe_",
+ [RESOURCE_TYPE_RELAY]: "gwe_",
+ [RESOURCE_TYPE_KMIP]: "gwe_",
+ [RESOURCE_TYPE_AGENT_VAULT_PROXY]: "avp_"
+};
+
+const $generateEnrollmentToken = (prefix: string) => {
+ const plainToken = `${prefix}${crypto.randomBytes(32).toString("base64url")}`;
const tokenHash = crypto.nativeCrypto.createHash("sha256").update(plainToken).digest("hex");
const expiresAt = new Date(Date.now() + ENROLLMENT_TOKEN_TTL_SECONDS * 1000);
return { plainToken, tokenHash, expiresAt };
@@ -90,8 +101,9 @@ type TResourceAuthMethodServiceFactoryDep = {
gatewayPoolMembershipDAL: Pick<TGatewayPoolMembershipDALFactory, "find">;
relayDAL: Pick<TRelayDALFactory, "findById" | "updateById">;
kmipServerDAL: Pick<TKmipServerDALFactory, "findById" | "updateById">;
+ agentVaultProxyDAL: Pick<TAgentVaultProxyDALFactory, "findByIdWithOrg" | "updateById">;
identityDAL: Pick<TIdentityDALFactory, "findById">;
- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
gatewayProxyRegistry: TGatewayProxyRegistry;
};
@@ -102,27 +114,44 @@ export type TResourceAuthMethodServiceFactory = ReturnType<typeof resourceAuthMe
const GATEWAY_PERMISSION_MAP = {
list: OrgPermissionGatewayActions.ListGateways,
edit: OrgPermissionGatewayActions.EditGateways,
+ create: OrgPermissionGatewayActions.EditGateways,
+ issue: OrgPermissionGatewayActions.EditGateways,
revoke: OrgPermissionGatewayActions.RevokeGatewayAccess
} as const;
const RELAY_PERMISSION_MAP = {
list: OrgPermissionRelayActions.ListRelays,
edit: OrgPermissionRelayActions.EditRelays,
+ create: OrgPermissionRelayActions.EditRelays,
+ issue: OrgPermissionRelayActions.EditRelays,
revoke: OrgPermissionRelayActions.RevokeRelayAccess
} as const;
+// create and issue exist for products that gate them separately; these three keep them on edit, which
+// is the action that has always covered minting here.
const KMIP_SERVER_PERMISSION_MAP = {
list: OrgPermissionKmipServerActions.ListKmipServers,
edit: OrgPermissionKmipServerActions.EditKmipServers,
+ create: OrgPermissionKmipServerActions.EditKmipServers,
+ issue: OrgPermissionKmipServerActions.EditKmipServers,
revoke: OrgPermissionKmipServerActions.RevokeKmipServerAccess
} as const;
const RESOURCE_LABEL: Record<ResourceRef["type"], string> = {
[RESOURCE_TYPE_GATEWAY]: "Gateway",
[RESOURCE_TYPE_RELAY]: "Relay",
- [RESOURCE_TYPE_KMIP]: "KMIP server"
+ [RESOURCE_TYPE_KMIP]: "KMIP server",
+ [RESOURCE_TYPE_AGENT_VAULT_PROXY]: "Agent Vault proxy"
};
+const AGENT_VAULT_PROXY_PERMISSION_MAP = {
+ list: ProjectPermissionAgentVaultProxyActions.Read,
+ edit: ProjectPermissionAgentVaultProxyActions.Edit,
+ create: ProjectPermissionAgentVaultProxyActions.Create,
+ issue: ProjectPermissionAgentVaultProxyActions.IssueToken,
+ revoke: ProjectPermissionAgentVaultProxyActions.Revoke
+} as const;
+
type TBasicResource = { id: string; name: string; orgId: string | null; identityId: string | null };
export const resourceAuthMethodServiceFactory = ({
@@ -136,6 +165,7 @@ export const resourceAuthMethodServiceFactory = ({
gatewayPoolMembershipDAL,
relayDAL,
kmipServerDAL,
+ agentVaultProxyDAL,
identityDAL,
permissionService,
licenseService,
@@ -145,6 +175,7 @@ export const resourceAuthMethodServiceFactory = ({
const $registryFilter = (resource: ResourceRef) => {
if (resource.type === RESOURCE_TYPE_GATEWAY) return { gatewayId: resource.id };
if (resource.type === RESOURCE_TYPE_RELAY) return { relayId: resource.id };
+ if (resource.type === RESOURCE_TYPE_AGENT_VAULT_PROXY) return { agentVaultProxyId: resource.id };
return { kmipServerId: resource.id };
};
@@ -164,6 +195,11 @@ export const resourceAuthMethodServiceFactory = ({
? { id: relay.id, name: relay.name, orgId: relay.orgId ?? null, identityId: relay.identityId ?? null }
: null;
}
+ if (resource.type === RESOURCE_TYPE_AGENT_VAULT_PROXY) {
+ const proxy = await agentVaultProxyDAL.findByIdWithOrg(resource.id, tx);
+ return proxy ? { id: proxy.id, name: proxy.name, orgId: proxy.orgId, identityId: null } : null;
+ }
+ // Unmatched types load as a KMIP server rather than failing, so a new resource type needs its own arm above.
const kmipServer = await kmipServerDAL.findById(resource.id, tx);
return kmipServer ? { id: kmipServer.id, name: kmipServer.name, orgId: kmipServer.orgId, identityId: null } : null;
};
@@ -182,6 +218,14 @@ export const resourceAuthMethodServiceFactory = ({
const refreshed = await relayDAL.updateById(resource.id, { $incr: { tokenVersion: 1 }, heartbeat: null }, tx);
return refreshed.tokenVersion;
}
+ if (resource.type === RESOURCE_TYPE_AGENT_VAULT_PROXY) {
+ const refreshed = await agentVaultProxyDAL.updateById(
+ resource.id,
+ { $incr: { tokenVersion: 1 }, heartbeat: null, heartbeatTTL: null },
+ tx
+ );
+ return refreshed.tokenVersion;
+ }
const refreshed = await kmipServerDAL.updateById(resource.id, { $incr: { tokenVersion: 1 } }, tx);
return refreshed.tokenVersion;
};
@@ -193,14 +237,43 @@ export const resourceAuthMethodServiceFactory = ({
if (resource.type === RESOURCE_TYPE_RELAY) {
return mintRelayJwt({ relayId: resource.id, orgId, tokenVersion, accessTokenTTL: 0 });
}
+ if (resource.type === RESOURCE_TYPE_AGENT_VAULT_PROXY) {
+ return mintAgentVaultProxyJwt({ agentVaultProxyId: resource.id, orgId, tokenVersion, accessTokenTTL: 0 });
+ }
return mintKmipServerJwt({ kmipServerId: resource.id, orgId, tokenVersion, accessTokenTTL: 0 });
};
const $checkPermission = async (
actor: TSetAuthMethodDTO["actor"],
- intent: "list" | "edit" | "revoke",
- resourceType: ResourceRef["type"]
+ intent: "list" | "edit" | "create" | "issue" | "revoke",
+ resourceType: ResourceRef["type"],
+ resourceId?: string
) => {
+ // A project subject, not an org one: the else branch below would reintroduce the org-admin fallback
+ // the product forbids.
+ if (resourceType === RESOURCE_TYPE_AGENT_VAULT_PROXY) {
+ if (!resourceId) {
+ throw new BadRequestError({ message: "Agent Vault proxy permission check requires the proxy id" });
+ }
+ const proxy = await agentVaultProxyDAL.findByIdWithOrg(resourceId);
+ if (!proxy || proxy.orgId !== actor.orgId) {
+ throw new NotFoundError({ message: `Agent Vault proxy ${resourceId} not found` });
+ }
+ const { permission: projectPermission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: proxy.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+ ForbiddenError.from(projectPermission).throwUnlessCan(
+ AGENT_VAULT_PROXY_PERMISSION_MAP[intent],
+ ProjectPermissionSub.AgentVaultProxies
+ );
+ return;
+ }
+
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor: actor.type,
@@ -707,7 +780,7 @@ export const resourceAuthMethodServiceFactory = ({
// tokenVersion is intentionally NOT bumped on method change — running resources keep
// their JWT until the next restart, avoiding forced downtime. Use revoke for that.
const setMethod = async ({ resource, authMethod, actor }: TSetAuthMethodDTO): Promise<TAuthMethodView> => {
- await $checkPermission(actor, "edit", resource.type);
+ await $checkPermission(actor, "edit", resource.type, resource.id);
const resourceLabel = RESOURCE_LABEL[resource.type];
const loaded = await $loadResource(resource);
@@ -907,8 +980,8 @@ export const resourceAuthMethodServiceFactory = ({
// Non-destructive: minting a new token does NOT bump tokenVersion or clear heartbeat,
// so a running resource keeps working. The next login (with the new token) does the bump.
- const mintToken = async ({ resource, actor }: TMintTokenDTO) => {
- await $checkPermission(actor, "edit", resource.type);
+ const mintToken = async ({ resource, actor, intent = "issue" }: TMintTokenDTO) => {
+ await $checkPermission(actor, intent, resource.type, resource.id);
const resourceLabel = RESOURCE_LABEL[resource.type];
const loaded = await $loadResource(resource);
@@ -923,7 +996,7 @@ export const resourceAuthMethodServiceFactory = ({
});
}
- const generated = $generateEnrollmentToken();
+ const generated = $generateEnrollmentToken(ENROLLMENT_TOKEN_PREFIX[resource.type]);
const record = await resourceTokenAuthDAL.transaction(async (tx) => {
await resourceTokenAuthDAL.delete({ authMethodId: registry.id }, tx);
@@ -948,7 +1021,7 @@ export const resourceAuthMethodServiceFactory = ({
};
const revokeAccess = async ({ resource, actor }: TRevokeTokenDTO) => {
- await $checkPermission(actor, "revoke", resource.type);
+ await $checkPermission(actor, "revoke", resource.type, resource.id);
const resourceLabel = RESOURCE_LABEL[resource.type];
const loaded = await $loadResource(resource);
@@ -1170,7 +1243,8 @@ export const resourceAuthMethodServiceFactory = ({
}
// Determine resource type from which FK is set on the registry row — exactly one must be set.
- const linkedResourceId = registry.gatewayId ?? registry.relayId ?? registry.kmipServerId;
+ const linkedResourceId =
+ registry.gatewayId ?? registry.relayId ?? registry.kmipServerId ?? registry.agentVaultProxyId;
if (!linkedResourceId) {
throw new BadRequestError({ message: "Enrollment token is not linked to a resource" });
}
@@ -1178,6 +1252,7 @@ export const resourceAuthMethodServiceFactory = ({
let actualResourceType: ResourceRef["type"];
if (registry.gatewayId) actualResourceType = RESOURCE_TYPE_GATEWAY;
else if (registry.relayId) actualResourceType = RESOURCE_TYPE_RELAY;
+ else if (registry.agentVaultProxyId) actualResourceType = RESOURCE_TYPE_AGENT_VAULT_PROXY;
else actualResourceType = RESOURCE_TYPE_KMIP;
if (actualResourceType !== expectedResourceType) {
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts
index 90fa03b200..c9d43746fe 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts
@@ -62,7 +62,9 @@ export type TGetAuthMethodDTO = {
actor: OrgServiceActor;
};
-export type TMintTokenDTO = TGetAuthMethodDTO;
+// Minting happens both when a resource is created and when its token is replaced later. Those are
+// different permissions on a product that separates them, so the caller says which one it is.
+export type TMintTokenDTO = TGetAuthMethodDTO & { intent?: "create" | "issue" };
export type TRevokeTokenDTO = TGetAuthMethodDTO;
export type TLoginWithAwsDTO = {
@@ -79,7 +81,7 @@ export type TLoginWithKubernetesDTO = {
export type TLoginWithTokenDTO = {
token: string;
- expectedResourceType: "gateway" | "relay" | "kmip";
+ expectedResourceType: "gateway" | "relay" | "kmip" | "agentVaultProxy";
};
export type TAuthMethodView =
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index b5e141e9ca..c50171ba90 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -39,7 +39,7 @@ import { prepareDeletedGroupAlertRecipientCleanup } from "@app/services/alert/al
import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
import { AuthTokenType } from "@app/services/auth/auth-type";
import { TExternalGroupOrgRoleMappingDALFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-dal";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
@@ -1011,6 +1011,7 @@ export const scimServiceFactory = ({
// Deprovisioning cascades the user's project + group memberships, changing the identity meters.
usageMeteringService.emit(membership.scopeOrgId, SecretIdentities.key);
usageMeteringService.emit(membership.scopeOrgId, PamIdentities.key);
+ usageMeteringService.emit(membership.scopeOrgId, AgentVaultIdentities.key);
await scimEventsDAL.create({
orgId,
diff --git a/backend/src/ee/services/sub-org/sub-org-service.ts b/backend/src/ee/services/sub-org/sub-org-service.ts
index 903e858ac8..f44f3a5cce 100644
--- a/backend/src/ee/services/sub-org/sub-org-service.ts
+++ b/backend/src/ee/services/sub-org/sub-org-service.ts
@@ -2,12 +2,13 @@ import { ForbiddenError } from "@casl/ability";
import slugify from "@sindresorhus/slugify";
import { AccessScope, OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus } from "@app/db/schemas";
+import { bootstrapAgentVaultProject } from "@app/ee/services/agent-vault-project/agent-vault-project-bootstrap";
import { bootstrapPamProject } from "@app/ee/services/pam-project/pam-project-bootstrap";
import { BadRequestError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type";
import { bootstrapCertManagerProject } from "@app/services/cert-manager-instance/cert-manager-project-bootstrap";
import { TCertificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";
-import { PamIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
@@ -121,11 +122,21 @@ export const subOrgServiceFactory = ({
tx
);
+ await bootstrapAgentVaultProject(
+ {
+ orgId: org.id,
+ adminUserIds: permission.type === ActorType.USER ? [permission.id] : [],
+ adminIdentityIds: permission.type === ActorType.IDENTITY ? [permission.id] : []
+ },
+ { projectDAL, membershipDAL, membershipRoleDAL },
+ tx
+ );
+
return org;
});
- // The PAM bootstrap seeds the creator as a project member, which changes the pam_identities meter.
usageMeteringService.emit(organization.id, PamIdentities.key);
+ usageMeteringService.emit(organization.id, AgentVaultIdentities.key);
return {
organization
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a04df5a307..a3d8072b1b 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -37,7 +37,8 @@ export const PgSqlLock = {
KmsProjectKeyCreation: (projectId: string) => pgAdvisoryLockHashText(`kms-project-key:${projectId}`),
KmsProjectDataKeyCreation: (projectId: string) => pgAdvisoryLockHashText(`kms-project-data-key:${projectId}`),
ScimGroupUpdate: (groupId: string) => pgAdvisoryLockHashText(`scim-group-update:${groupId}`),
- LastAdminGuard: (scope: "org", scopeId: string) => pgAdvisoryLockHashText(`last-admin-guard:${scope}:${scopeId}`),
+ LastAdminGuard: (scope: "org" | "project", scopeId: string) =>
+ pgAdvisoryLockHashText(`last-admin-guard:${scope}:${scopeId}`),
AuditReportRequest: (projectId: string) => pgAdvisoryLockHashText(`audit-report-request:${projectId}`),
OrgAuditReportRequest: (orgId: string) => pgAdvisoryLockHashText(`audit-report-request:org:${orgId}`),
OrgAgentProxyConfigInit: (orgId: string) => pgAdvisoryLockHashText(`org-agent-proxy-config-init:${orgId}`)
@@ -158,6 +159,7 @@ export const KeyStorePrefixes = {
PamAwsIamAccessKeyId: (sessionId: string) => `pam-aws-iam-access-key-id:${sessionId}` as const,
PamDefaultProject: (orgId: string) => `pam-default-project:${orgId}` as const,
+ AgentVaultDefaultProject: (orgId: string) => `agent-vault-default-project:${orgId}` as const,
CertDashboardStats: (projectId: string) => `cert-dashboard-stats:${projectId}` as const,
CertActivityTrend: (projectId: string, range: string) => `cert-activity-trend:${projectId}:${range}` as const,
@@ -256,6 +258,7 @@ export const KeyStoreTtls = {
AuditLogMigrationAlertInSeconds: 604800, // 7 days
LicenseCloudPlanInSeconds: 900, // 15 minutes
PamDefaultProjectInSeconds: 300, // 5 minutes
+ AgentVaultDefaultProjectInSeconds: 300, // 5 minutes
// How long reads stay in stale-while-revalidate mode after a billing mutation (covers Stripe reconciliation).
LicenseCachePassThroughInSeconds: 180, // 3 minutes
// Longer window for redirect-to-Stripe-checkout paths, where the purchase applies via webhook only
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index aef689061c..820ff14658 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -101,6 +101,11 @@ export enum ApiDocsTags {
PamMemberships = "PAM Memberships",
PamRoles = "PAM Roles",
PamDiscovery = "PAM Discovery",
+ AgentVault = "Agent Vault",
+ AgentVaultAccessBundles = "Agent Vault Access Bundles",
+ AgentVaultSessions = "Agent Vault Sessions",
+ AgentVaultProxies = "Agent Vault Proxies",
+ AgentVaultMemberships = "Agent Vault Memberships",
KmipServers = "KMIP Servers"
}
@@ -4183,3 +4188,78 @@ export const ENCRYPTION_KEY_ROTATION = {
"Remove the key even though an instance started on it recently. This overrides only that check: a label that does not match the key currently held still fails. Any instance still using that key will fail its next restart until it is given the new one."
}
};
+
+export const AGENT_VAULT = {
+ ACCESS_BUNDLE: {
+ accessBundleId: "The ID of the access bundle.",
+ name: "The name of the access bundle.",
+ description: "A description of what this access bundle is for.",
+ serviceCount: "How many services the access bundle holds.",
+ memberCount: "How many users, machine identities and groups can reach the access bundle.",
+ hostPatterns: "Every host pattern the access bundle's services cover."
+ },
+ SERVICE: {
+ serviceId: "The ID of the service.",
+ name: "The name of the service.",
+ hostPattern:
+ "A comma-separated set of hosts this service covers, each optionally with a port (defaults to 443). A leading '*.' wildcard matches exactly one label. Paths are not supported.",
+ credentialType: "How the credential is attached to the request: bearer, basic or passthrough.",
+ headerName: "The header the credential is written to. Defaults to Authorization.",
+ headerPrefix:
+ "Written before the credential value, separated by one space. Leave empty for a header that carries the value alone, such as DD-API-KEY. On update a field left out keeps its stored value, so send an empty string to clear the prefix when changing the header.",
+ username:
+ "The username half of the basic credential. May be empty if a password is set. Never returned once saved, since some APIs put the whole key here.",
+ updateUsername:
+ "The username half of the basic credential. Omit to keep the stored username; send an empty string to remove it, which requires a password.",
+ updateValue: "The secret. Omit to keep the stored secret.",
+ updatePassword:
+ "The password half of the basic credential. Omit to keep the stored password; send an empty string to remove it, which requires a username.",
+ createdAt: "When the service was added to the access bundle.",
+ value: "The secret. Never returned once saved.",
+ password:
+ "The password half of the basic credential. May be empty if a username is set, for APIs that carry the whole key in the username. Never returned once saved."
+ },
+ MEMBER: {
+ memberId: "The ID of the access bundle membership.",
+ userId: "The ID of the user to grant the access bundle to.",
+ identityId: "The ID of the machine identity to grant the access bundle to.",
+ groupId: "The ID of the group to grant the access bundle to.",
+ userIds: "The IDs of the users to grant the access bundle to.",
+ identityIds: "The IDs of the machine identities to grant the access bundle to.",
+ groupIds: "The IDs of the groups to grant the access bundle to.",
+ skipped: "The IDs of the requested grantees who already had the access bundle and were left as they were."
+ },
+ MEMBERSHIP: {
+ role: "The Agent Vault role: admin or member."
+ },
+ PROXY: {
+ proxyId: "The ID of the proxy.",
+ name: "The name of the proxy.",
+ heartbeat: "When the proxy last checked in, or null if it never has.",
+ isHealthy: "Whether the proxy has checked in recently enough to be considered up.",
+ enrollmentToken: "A one-time token the proxy enrolls with. Shown once, and valid for one hour.",
+ rootCaCertificate:
+ "The proxy's own certificate authority, in PEM form. Sent once at enrollment so Infisical can check it is a real certificate authority and record its fingerprint; the certificate itself is not stored.",
+ rootCaFingerprint:
+ "The SHA-256 fingerprint of the proxy's certificate authority. Pin this if you want to verify the proxy an agent connects to.",
+ rootCaExpiresAt: "When the proxy's certificate authority expires.",
+ trafficPolicy:
+ "Which hosts an agent may reach through this proxy. 'any-host' lets every request out; 'bundle-hosts' allows only hosts an access bundle covers, plus anything in allowedHosts, and refuses the rest with a 403.",
+ allowedHosts:
+ "Hosts that stay reachable under the 'bundle-hosts' traffic policy even though no access bundle covers them. Still intercepted, and given no credential.",
+ pollInterval: "How often, in seconds, the proxy refreshes its sessions and settings. Between 10 and 300.",
+ sessionToken: "The session an agent is running with. A selector, not a second credential."
+ },
+ SESSION: {
+ sessionId: "The ID of the session.",
+ accessBundles: "The access bundle this session carries, by name. A list that accepts exactly one name.",
+ ttl: "How long the session lasts: a duration such as 30m, 8h or 7d (at least 1m), or never. Defaults to 7d.",
+ token: "The session token. Returned once, at mint, and never again.",
+ expiresAt: "When the session expires, or null when it never does.",
+ scope: "Whose sessions to list: your own (mine) or everyone's (all, administrators only).",
+ status: "Filter by session status: active, revoked or expired.",
+ search: "Match sessions by actor name, actor email or access bundle name.",
+ limit: "The maximum number of sessions to return.",
+ offset: "How many sessions to skip."
+ }
+};
diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.ts
index 8331a6a92a..b3ce5b45b4 100644
--- a/backend/src/server/config/rateLimiter.ts
+++ b/backend/src/server/config/rateLimiter.ts
@@ -53,6 +53,31 @@ export const gatewayMetricsReportLimit: RateLimitOptions = {
}
};
+// Keyed on the proxy identity, not the source IP, so many proxies behind one NAT do not share a bucket.
+// One resolve per live session per poll, so this covers 4,200 sessions at the default 60s poll and 700 at
+// the 10s floor. Deliberate: a proxy serving that many agents is far past what we expect, and a runaway
+// one blows through any budget. A throttled proxy reads a 429 as "Infisical unreachable" and drops its
+// sessions after five polls, so raise this rather than the poll floor if a real deployment ever nears it.
+export const agentVaultResolveLimit: RateLimitOptions = {
+ timeWindow: 60 * 1000,
+ hook: "preValidation",
+ max: 4200,
+ keyGenerator: (req) => {
+ const actorId = (req as { permission?: { id?: string } }).permission?.id;
+ return actorId ? `agent-vault-resolve:${actorId}` : req.realIp;
+ }
+};
+
+export const agentVaultHeartbeatLimit: RateLimitOptions = {
+ timeWindow: 60 * 1000,
+ hook: "preValidation",
+ max: 30,
+ keyGenerator: (req) => {
+ const actorId = (req as { permission?: { id?: string } }).permission?.id;
+ return actorId ? `agent-vault-heartbeat:${actorId}` : req.realIp;
+ }
+};
+
// special endpoints
export const secretsLimit: RateLimitOptions = {
// secrets, folders, secret imports
diff --git a/backend/src/server/lib/telemetry.ts b/backend/src/server/lib/telemetry.ts
index 9d04d0357e..18cc5b639e 100644
--- a/backend/src/server/lib/telemetry.ts
+++ b/backend/src/server/lib/telemetry.ts
@@ -1,6 +1,9 @@
import { FastifyRequest } from "fastify";
+import { UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { ActorType } from "@app/services/auth/auth-type";
+import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
+import { TAgentVaultActorPostHogEvent, TPostHogEvent } from "@app/services/telemetry/telemetry-types";
// this is a unique id for sending posthog event
export const getTelemetryDistinctId = (req: FastifyRequest) => {
@@ -15,3 +18,30 @@ export const getTelemetryDistinctId = (req: FastifyRequest) => {
}
return "unknown-auth-data";
};
+
+type TAgentVaultEventInput<T extends TAgentVaultActorPostHogEvent = TAgentVaultActorPostHogEvent> = T extends {
+ event: infer E;
+ properties: infer P;
+}
+ ? { event: E; properties: Omit<P, "orgId" | "channel" | "actorType"> }
+ : never;
+
+export const emitAgentVaultTelemetry = (
+ telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">,
+ req: FastifyRequest & { permission: { orgId: string; type: ActorType } },
+ event: TAgentVaultEventInput
+) => {
+ const payload = {
+ event: event.event,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ ...event.properties,
+ orgId: req.permission.orgId,
+ channel: req.auditLogInfo.userAgentType ?? UserAgentType.OTHER,
+ actorType: req.permission.type
+ }
+ } as TPostHogEvent;
+
+ void telemetryService.sendPostHogEvents(payload).catch(() => {});
+};
diff --git a/backend/src/server/plugins/audit-log.ts b/backend/src/server/plugins/audit-log.ts
index dec39d85cc..f92f519b90 100644
--- a/backend/src/server/plugins/audit-log.ts
+++ b/backend/src/server/plugins/audit-log.ts
@@ -114,6 +114,13 @@ export const injectAuditLogInfo = fp(async (server: FastifyZodProvider) => {
kmipServerId: req.permission.id
}
};
+ } else if (req.auth.actor === ActorType.AGENT_VAULT_PROXY) {
+ payload.actor = {
+ type: ActorType.AGENT_VAULT_PROXY,
+ metadata: {
+ agentVaultProxyId: req.permission.id
+ }
+ };
} else {
throw new BadRequestError({ message: "Invalid actor type provided" });
}
diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.ts
index 4982b61165..2bce1eb839 100644
--- a/backend/src/server/plugins/auth/inject-identity.ts
+++ b/backend/src/server/plugins/auth/inject-identity.ts
@@ -16,6 +16,7 @@ import {
AuthModeJwtTokenPayload,
AuthTokenType,
MfaMethod,
+ TAgentVaultProxyAccessTokenJwtPayload,
TGatewayAccessTokenJwtPayload,
TKmipServerAccessTokenJwtPayload,
TRelayAccessTokenJwtPayload
@@ -112,6 +113,16 @@ export type TAuthMode =
parentOrgId: string;
authMethod: null;
token: TKmipServerAccessTokenJwtPayload;
+ }
+ | {
+ authMode: AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN;
+ actor: ActorType.AGENT_VAULT_PROXY;
+ agentVaultProxyId: string;
+ orgId: string;
+ rootOrgId: string;
+ parentOrgId: string;
+ authMethod: null;
+ token: TAgentVaultProxyAccessTokenJwtPayload;
};
// A first-party session and a delegated OAuth token have the same auth shape, so a handler that only
@@ -200,6 +211,12 @@ export const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {
token: decodedToken as TKmipServerAccessTokenJwtPayload,
actor: ActorType.KMIP_SERVER
} as const;
+ case AuthTokenType.AGENT_VAULT_PROXY_ACCESS_TOKEN:
+ return {
+ authMode: AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN,
+ token: decodedToken as TAgentVaultProxyAccessTokenJwtPayload,
+ actor: ActorType.AGENT_VAULT_PROXY
+ } as const;
default:
return { authMode: null, token: null } as const;
}
@@ -504,6 +521,38 @@ export const injectIdentity = fp(
};
break;
}
+ case AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN: {
+ const proxy = await server.services.agentVaultProxy.getProxyForAuth(token.agentVaultProxyId);
+
+ // The tokenVersion check is the only kill switch for an issued proxy token, so no proxy route may skip it.
+ if (!proxy || proxy.tokenVersion !== token.tokenVersion) {
+ throw new UnauthorizedError({
+ name: "ProxyTokenRejected",
+ message: "Agent Vault proxy token has been revoked"
+ });
+ }
+
+ if (proxy.orgId !== token.orgId) {
+ throw new UnauthorizedError({
+ name: "ProxyTokenRejected",
+ message: "Agent Vault proxy token org mismatch"
+ });
+ }
+
+ requestContext.set(RequestContextKey.OrgId, token.orgId);
+
+ req.auth = {
+ authMode: AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN,
+ actor,
+ agentVaultProxyId: token.agentVaultProxyId,
+ orgId: token.orgId,
+ rootOrgId: token.orgId,
+ parentOrgId: token.orgId,
+ authMethod: null,
+ token
+ };
+ break;
+ }
default:
throw new BadRequestError({ message: "Invalid token strategy provided" });
}
diff --git a/backend/src/server/plugins/auth/inject-permission.ts b/backend/src/server/plugins/auth/inject-permission.ts
index 5c1cd742c7..7b401067a1 100644
--- a/backend/src/server/plugins/auth/inject-permission.ts
+++ b/backend/src/server/plugins/auth/inject-permission.ts
@@ -100,6 +100,20 @@ export const injectPermission = fp(async (server) => {
logger.info(
`injectPermission: Injecting permissions for [permissionsForKmipServer=${req.auth.kmipServerId}] [type=${ActorType.KMIP_SERVER}]`
);
+ } else if (req.auth.actor === ActorType.AGENT_VAULT_PROXY) {
+ // Without this the proxy routes' rate-limit keyGenerator falls back to source IP.
+ req.permission = {
+ type: ActorType.AGENT_VAULT_PROXY,
+ id: req.auth.agentVaultProxyId,
+ orgId: req.auth.orgId,
+ rootOrgId: req.auth.rootOrgId,
+ parentOrgId: req.auth.parentOrgId,
+ authMethod: null
+ };
+
+ logger.info(
+ `injectPermission: Injecting permissions for [permissionsForAgentVaultProxy=${req.auth.agentVaultProxyId}] [type=${ActorType.AGENT_VAULT_PROXY}]`
+ );
}
});
});
diff --git a/backend/src/server/plugins/inject-agent-vault-project-id.ts b/backend/src/server/plugins/inject-agent-vault-project-id.ts
new file mode 100644
index 0000000000..df331705b0
--- /dev/null
+++ b/backend/src/server/plugins/inject-agent-vault-project-id.ts
@@ -0,0 +1,24 @@
+import { FastifyPluginAsync } from "fastify";
+import fp from "fastify-plugin";
+
+import { ActorType } from "@app/services/auth/auth-type";
+
+const AGENT_VAULT_PREFIX = "/api/v1/agent-vault/";
+
+export const injectAgentVaultProjectId: FastifyPluginAsync = fp(async (server) => {
+ server.decorateRequest("internalAgentVaultProjectId", "");
+
+ server.addHook("preValidation", async (req) => {
+ if (!req.permission?.orgId) return;
+
+ // The proxy's own routes sit under this prefix but take their project from the proxy row or the
+ // session, so resolving it here would be a Redis GET per heartbeat and per session resolve for a
+ // value no handler reads. A proxy route that ever needs it has to resolve it itself.
+ if (req.auth?.actor === ActorType.AGENT_VAULT_PROXY) return;
+
+ const routePath = req.routeOptions.url ?? "";
+ if (!routePath.startsWith(AGENT_VAULT_PREFIX)) return;
+
+ req.internalAgentVaultProjectId = await server.services.agentVaultProjectResolver.resolve(req.permission.orgId);
+ });
+});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3920be5880..bfdc88c906 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -25,6 +25,17 @@ import { accessApprovalRequestReviewerDALFactory } from "@app/ee/services/access
import { accessApprovalRequestServiceFactory } from "@app/ee/services/access-approval-request/access-approval-request-service";
import { agentProxyCaServiceFactory } from "@app/ee/services/agent-proxy-ca/agent-proxy-ca-service";
import { orgAgentProxyConfigDALFactory } from "@app/ee/services/agent-proxy-ca/org-agent-proxy-config-dal";
+import { agentVaultAccessBundleDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal";
+import { agentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";
+import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";
+import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";
+import { agentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";
+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 { assumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-service";
import { clickhouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";
import { auditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";
@@ -545,6 +556,7 @@ import { injectPermission } from "../plugins/auth/inject-permission";
import { goSidecarPlugin } from "../plugins/go-sidecar";
// import { forwardToGoSidecar } from "../plugins/go-sidecar-forwarding";
import { shadowToGoSidecar } from "../plugins/go-sidecar-shadowing";
+import { injectAgentVaultProjectId } from "../plugins/inject-agent-vault-project-id";
import { injectPamProjectId } from "../plugins/inject-pam-project-id";
import { injectRateLimits } from "../plugins/inject-rate-limits";
import { forwardWritesToPrimary } from "../plugins/primary-forwarding-mode";
@@ -1580,7 +1592,8 @@ export const registerRoutes = async (
notificationService,
membershipRoleDAL,
membershipUserDAL,
- projectMembershipDAL
+ projectMembershipDAL,
+ usageMeteringService
});
const rateLimitService = rateLimitServiceFactory({
@@ -1793,6 +1806,53 @@ export const registerRoutes = async (
projectDAL
});
+ const agentVaultAccessBundleDAL = agentVaultAccessBundleDALFactory(db);
+ const agentVaultServiceDAL = agentVaultServiceDALFactory(db);
+ const agentVaultSessionDAL = agentVaultSessionDALFactory(db);
+ const agentVaultSessionAccessBundleDAL = agentVaultSessionAccessBundleDALFactory(db);
+ const agentVaultProxyDAL = agentVaultProxyDALFactory(db);
+ const agentVaultResolveDAL = agentVaultResolveDALFactory(db);
+
+ const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({
+ agentVaultAccessBundleDAL,
+ agentVaultServiceDAL,
+ permissionService,
+ kmsService,
+ membershipDAL,
+ membershipRoleDAL,
+ userGroupMembershipDAL,
+ identityGroupMembershipDAL
+ });
+
+ const agentVaultSessionService = agentVaultSessionServiceFactory({
+ agentVaultSessionDAL,
+ agentVaultSessionAccessBundleDAL,
+ agentVaultAccessBundleDAL,
+ membershipDAL,
+ permissionService
+ });
+
+ const agentVaultProjectResolver = agentVaultProjectResolverFactory({
+ db,
+ projectDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ keyStore
+ });
+
+ const agentVaultMembershipService = agentVaultMembershipServiceFactory({
+ membershipDAL,
+ identityDAL,
+ membershipRoleDAL,
+ groupDAL,
+ projectAccessRequestDAL,
+ userDAL,
+ userAliasDAL,
+ orgDAL,
+ permissionService,
+ usageMeteringService
+ });
+
const pamProjectResolver = pamProjectResolverFactory({
db,
projectDAL,
@@ -1872,12 +1932,24 @@ export const registerRoutes = async (
gatewayPoolMembershipDAL,
relayDAL,
kmipServerDAL,
+ agentVaultProxyDAL,
identityDAL,
permissionService,
licenseService,
gatewayProxyRegistry
});
+ const agentVaultProxyService = agentVaultProxyServiceFactory({
+ agentVaultProxyDAL,
+ agentVaultResolveDAL,
+ agentVaultSessionDAL,
+ membershipDAL,
+ orgDAL,
+ permissionService,
+ kmsService,
+ resourceAuthMethodService
+ });
+
const relayService = relayServiceFactory({
instanceRelayConfigDAL,
orgRelayConfigDAL,
@@ -2918,7 +2990,8 @@ export const registerRoutes = async (
approvalRequestDAL,
approvalRequestGrantsDAL,
certificateRequestDAL,
- scepTransactionDAL
+ scepTransactionDAL,
+ agentVaultSessionService
});
const healthAlert = healthAlertServiceFactory({
@@ -4159,6 +4232,11 @@ export const registerRoutes = async (
pkiApplicationEnrollment: pkiApplicationEnrollmentService,
certManagerProjectResolver,
pamProjectResolver,
+ agentVaultProjectResolver,
+ agentVaultAccessBundle: agentVaultAccessBundleService,
+ agentVaultProxy: agentVaultProxyService,
+ agentVaultSession: agentVaultSessionService,
+ agentVaultMembership: agentVaultMembershipService,
pamAccountTemplate: pamAccountTemplateService,
pamFolder: pamFolderService,
pamAccount: pamAccountService,
@@ -4344,6 +4422,7 @@ export const registerRoutes = async (
await server.register(injectAssumePrivilege);
await server.register(injectPermission);
await server.register(injectPamProjectId);
+ await server.register(injectAgentVaultProjectId);
await server.register(injectRateLimits);
await server.register(injectAuditLogInfo);
diff --git a/backend/src/server/routes/v1/invite-org-router.ts b/backend/src/server/routes/v1/invite-org-router.ts
index 6089fd8ac6..20ca21d992 100644
--- a/backend/src/server/routes/v1/invite-org-router.ts
+++ b/backend/src/server/routes/v1/invite-org-router.ts
@@ -1,13 +1,15 @@
import { z } from "zod";
-import { AccessScope, OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";
+import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { PamProductRole } from "@app/ee/services/pam/pam-enums";
+import { ForbiddenRequestError } from "@app/lib/errors";
import { unique } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { sanitizeEmail } from "@app/lib/validator";
import { inviteUserRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
-import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { emitAgentVaultTelemetry, getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -34,7 +36,8 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
// Signup-created projects the invitees get member access to.
projectIds: z.string().trim().array().max(5).optional(),
// Grants membership on the org's consolidated PAM project (PAM has no signup-created project).
- grantPamAccess: z.boolean().optional()
+ grantPamAccess: z.boolean().optional(),
+ grantAgentVaultAccess: z.boolean().optional()
}),
response: {
200: z.object({
@@ -51,7 +54,8 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
grantFailures: z
.object({
projectIds: z.string().array(),
- pamAccess: z.boolean()
+ pamAccess: z.boolean(),
+ agentVaultAccess: z.boolean()
})
.optional()
})
@@ -77,6 +81,7 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
// the request. Failures are still reported back so the client can tell the inviter.
const failedProjectIds: string[] = [];
let pamAccessFailed = false;
+ let agentVaultAccessFailed = false;
if (req.body.projectIds?.length) {
for await (const projectId of req.body.projectIds) {
@@ -157,6 +162,84 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
}
}
+ if (req.body.grantAgentVaultAccess) {
+ try {
+ const agentVaultProjectId = await server.services.agentVaultProjectResolver.resolve(req.permission.orgId);
+
+ // Agent Vault seeds no members, so an org admin who has never opened it is not a member and the
+ // grant below would refuse them. Opening the product joins them (layout.tsx); inviting with access
+ // is the same intent, so join them the same way. Only a missing membership qualifies: an existing
+ // member keeps whatever role they were given, and grantProjectAdminAccess refuses anyone without
+ // AccessAllProjects, which lands in the catch as a grant failure like before.
+ try {
+ await server.services.permission.getProjectPermission({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ projectId: agentVaultProjectId,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ actionProjectType: ActionProjectType.AgentVault
+ });
+ } catch (err) {
+ if (!(err instanceof ForbiddenRequestError) || err.name !== "ProjectMembershipNotFound") throw err;
+ await server.services.orgAdmin.grantProjectAdminAccess({
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ projectId: agentVaultProjectId
+ });
+ if (isUserSessionAuth(req.auth)) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: agentVaultProjectId,
+ event: {
+ type: EventType.ORG_ADMIN_ACCESS_PROJECT,
+ metadata: {
+ projectId: agentVaultProjectId,
+ username: req.auth.user.username,
+ email: req.auth.user.email || "",
+ userId: req.auth.userId
+ }
+ }
+ });
+ }
+ }
+
+ const { memberships } = await server.services.agentVaultMembership.addProductUserMembers({
+ projectId: agentVaultProjectId,
+ ctx: {
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ },
+ userIds: [],
+ emails: req.body.inviteeEmails,
+ role: ProjectMembershipRole.Member
+ });
+
+ for await (const membership of memberships) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: agentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_MEMBER_ADD,
+ metadata: { userId: membership.userId, userName: membership.userName, role: membership.role }
+ }
+ });
+ emitAgentVaultTelemetry(server.services.telemetry, req, {
+ event: PostHogEventTypes.AgentVaultProductMemberAdded,
+ properties: { memberType: "user", role: membership.role }
+ });
+ }
+ } catch (err) {
+ logger.error(err, "Failed to grant invitees Agent Vault access");
+ agentVaultAccessFailed = true;
+ }
+ }
+
await server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.UserOrgInvitation,
distinctId: getTelemetryDistinctId(req),
@@ -168,11 +251,19 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
}
});
- const hasGrantFailures = failedProjectIds.length > 0 || pamAccessFailed;
+ const hasGrantFailures = failedProjectIds.length > 0 || pamAccessFailed || agentVaultAccessFailed;
return {
completeInviteLinks,
message: `Send an invite link to ${req.body.inviteeEmails.join(", ")}`,
- ...(hasGrantFailures ? { grantFailures: { projectIds: failedProjectIds, pamAccess: pamAccessFailed } } : {})
+ ...(hasGrantFailures
+ ? {
+ grantFailures: {
+ projectIds: failedProjectIds,
+ pamAccess: pamAccessFailed,
+ agentVaultAccess: agentVaultAccessFailed
+ }
+ }
+ : {})
};
}
});
diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.ts
index 57e832d099..2e96bf6b99 100644
--- a/backend/src/server/routes/v1/organization-router.ts
+++ b/backend/src/server/routes/v1/organization-router.ts
@@ -94,7 +94,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
organization: sanitizedOrganizationSchema.extend({
- pamProjectId: z.string().nullable()
+ pamProjectId: z.string().nullable(),
+ agentVaultProjectId: z.string().nullable()
})
})
}
@@ -713,6 +714,11 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
accountsCount: z.number(),
accountTemplatesCount: z.number(),
foldersCount: z.number()
+ }),
+ agentVault: z.object({
+ accessBundlesCount: z.number(),
+ servicesCount: z.number(),
+ proxiesCount: z.number()
})
})
}
diff --git a/backend/src/server/routes/v3/signup-router.ts b/backend/src/server/routes/v3/signup-router.ts
index 9ee45fd0d1..39f815687c 100644
--- a/backend/src/server/routes/v3/signup-router.ts
+++ b/backend/src/server/routes/v3/signup-router.ts
@@ -240,16 +240,24 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
operationId: "recordSignupOnboardingV3",
body: z.object({
selectedProduct: z
- .enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam", "exploring"])
+ .enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam", "agent-vault", "exploring"])
.optional(),
// An empty array means "just exploring".
selectedProducts: z
- .enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam"])
+ .enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam", "agent-vault"])
.array()
- .max(5)
+ .max(6)
.optional(),
launchDestination: z
- .enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam", "organization-overview"])
+ .enum([
+ "secret-manager",
+ "cert-manager",
+ "kms",
+ "secret-scanning",
+ "pam",
+ "agent-vault",
+ "organization-overview"
+ ])
.optional(),
attributionSource: z.string().trim().max(512).optional()
}),
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
index 401b7885a0..850fd618cb 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -105,6 +105,8 @@ export const identityCredentialAlertProviderFactory = ({
return `${siteUrl}/organizations/${orgId}/projects/secret-management/${projectId}`;
case ProjectType.PAM:
return `${siteUrl}/organizations/${orgId}/pam`;
+ case ProjectType.AgentVault:
+ return `${siteUrl}/organizations/${orgId}/agent-vault`;
default:
return `${siteUrl}/organizations/${orgId}/projects/${projectType}/${projectId}`;
}
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index 0862861bd8..f406d616cd 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -445,6 +445,8 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {
return false;
case ProjectType.PAM:
return false;
+ case ProjectType.AgentVault:
+ return false;
default:
return true;
}
diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.ts
index ba2ef5597e..d961396924 100644
--- a/backend/src/services/auth/auth-type.ts
+++ b/backend/src/services/auth/auth-type.ts
@@ -25,6 +25,7 @@ export enum AuthTokenType {
GATEWAY_ACCESS_TOKEN = "gatewayAccessToken",
RELAY_ACCESS_TOKEN = "relayAccessToken",
KMIP_SERVER_ACCESS_TOKEN = "kmipServerAccessToken",
+ AGENT_VAULT_PROXY_ACCESS_TOKEN = "agentVaultProxyAccessToken",
ACCOUNT_RECOVERY_TOKEN = "accountRecoveryToken"
}
@@ -47,7 +48,8 @@ export enum AuthMode {
OAUTH = "oauth",
GATEWAY_ACCESS_TOKEN = "gatewayAccessToken",
RELAY_ACCESS_TOKEN = "relayAccessToken",
- KMIP_SERVER_ACCESS_TOKEN = "kmipServerAccessToken"
+ KMIP_SERVER_ACCESS_TOKEN = "kmipServerAccessToken",
+ AGENT_VAULT_PROXY_ACCESS_TOKEN = "agentVaultProxyAccessToken"
}
export enum ActorType { // would extend to AWS, Azure, ...
@@ -64,7 +66,8 @@ export enum ActorType { // would extend to AWS, Azure, ...
UNKNOWN_USER = "unknownUser",
GATEWAY = "gateway",
RELAY = "relay",
- KMIP_SERVER = "kmipServer"
+ KMIP_SERVER = "kmipServer",
+ AGENT_VAULT_PROXY = "agentVaultProxy"
}
export type TGatewayAccessTokenJwtPayload = {
@@ -88,6 +91,13 @@ export type TKmipServerAccessTokenJwtPayload = {
tokenVersion: number;
};
+export type TAgentVaultProxyAccessTokenJwtPayload = {
+ authTokenType: AuthTokenType.AGENT_VAULT_PROXY_ACCESS_TOKEN;
+ agentVaultProxyId: string;
+ orgId: string;
+ tokenVersion: number;
+};
+
// This will be null unless the token-type is JWT
export type ActorAuthMethod = AuthMethod | null;
diff --git a/backend/src/services/identity-v2/identity-service.ts b/backend/src/services/identity-v2/identity-service.ts
index 37a04f3365..7d72ff4c45 100644
--- a/backend/src/services/identity-v2/identity-service.ts
+++ b/backend/src/services/identity-v2/identity-service.ts
@@ -1,6 +1,7 @@
import {
AccessScope,
ActionProjectType,
+ getAdminMemberOnlyProductLabel,
OrganizationActionScope,
OrgMembershipRole,
ProjectMembershipRole,
@@ -33,7 +34,7 @@ import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TAlertServiceFactory } from "@app/services/alert/alert-service";
import { IDENTITY_AUTHENTICATION_RESOURCE_TYPE } from "@app/services/alert/providers/identity-credential-alert-provider";
-import { IdentitiesMeter, PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, IdentitiesMeter, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -155,13 +156,14 @@ export const identityV2ServiceFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scopeData.projectId), () =>
projectDAL.findById(scopeData.projectId)
);
- if (project?.type === ProjectType.CertificateManager || project?.type === ProjectType.PAM) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: `${project.type === ProjectType.PAM ? "PAM" : "Certificate Manager"} only supports Admin and Member roles.`
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
});
}
}
@@ -245,8 +247,11 @@ export const identityV2ServiceFactory = ({
let projectMemberRole = ProjectMembershipRole.NoAccess as string;
if (scopeData.scope === AccessScope.Project && !resolvedRoleDocs) {
const project = await projectDAL.findById(scopeData.projectId);
- // PAM's project membership IS its product membership, so NoAccess would be meaningless there
- if (project?.type === ProjectType.CertificateManager || project?.type === ProjectType.PAM) {
+ if (
+ project?.type === ProjectType.CertificateManager ||
+ project?.type === ProjectType.PAM ||
+ project?.type === ProjectType.AgentVault
+ ) {
projectMemberRole = ProjectMembershipRole.Member;
}
}
@@ -319,6 +324,7 @@ export const identityV2ServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
}
return { identity };
@@ -341,8 +347,10 @@ export const identityV2ServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(dto.selector.identityId, dto.isActorSuperAdmin);
const identity = await identityDAL.transaction(async (tx) => {
+ // Compared against undefined: `hasDeleteProtection: false` is a real update, and a truthiness check
+ // could never turn the flag off.
const updatedIdentity =
- data?.name || data?.hasDeleteProtection
+ data?.name !== undefined || data?.hasDeleteProtection !== undefined
? await identityDAL.updateById(
dto.selector.identityId,
{ name: data.name, hasDeleteProtection: data.hasDeleteProtection },
@@ -421,6 +429,7 @@ export const identityV2ServiceFactory = ({
usageMeteringService.emit(scopeData.orgId, IdentitiesMeter.key);
usageMeteringService.emit(scopeData.orgId, SecretIdentities.key);
usageMeteringService.emit(scopeData.orgId, PamIdentities.key);
+ usageMeteringService.emit(scopeData.orgId, AgentVaultIdentities.key);
return { identity: deletedIdentity };
};
diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.ts
index 82e45a340b..6d4f354ff5 100644
--- a/backend/src/services/identity/identity-service.ts
+++ b/backend/src/services/identity/identity-service.ts
@@ -17,7 +17,7 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TAlertServiceFactory } from "@app/services/alert/alert-service";
import { IDENTITY_AUTHENTICATION_RESOURCE_TYPE } from "@app/services/alert/providers/identity-credential-alert-provider";
import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
-import { IdentitiesMeter, PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, IdentitiesMeter, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
@@ -436,6 +436,7 @@ export const identityServiceFactory = ({
usageMeteringService.emit(identityOrgMembership.scopeOrgId, IdentitiesMeter.key);
usageMeteringService.emit(identityOrgMembership.scopeOrgId, SecretIdentities.key);
usageMeteringService.emit(identityOrgMembership.scopeOrgId, PamIdentities.key);
+ usageMeteringService.emit(identityOrgMembership.scopeOrgId, AgentVaultIdentities.key);
return { ...deletedIdentity, orgId: identityOrgMembership.scopeOrgId };
}
@@ -488,6 +489,7 @@ export const identityServiceFactory = ({
// identity meters change too.
usageMeteringService.emit(identityOrgMembership.scopeOrgId, SecretIdentities.key);
usageMeteringService.emit(identityOrgMembership.scopeOrgId, PamIdentities.key);
+ usageMeteringService.emit(identityOrgMembership.scopeOrgId, AgentVaultIdentities.key);
return { ...deletedIdentity, orgId: identityOrgMembership.scopeOrgId };
};
diff --git a/backend/src/services/license-client/features.ts b/backend/src/services/license-client/features.ts
index b9eb92c544..d6d97162bd 100644
--- a/backend/src/services/license-client/features.ts
+++ b/backend/src/services/license-client/features.ts
@@ -12,5 +12,6 @@ export const ActiveCerts = defineLimitFeature("active_certs", 0);
export const WildcardCerts = defineLimitFeature("wildcard_certs", 0);
export const SecretIdentities = defineLimitFeature("secret_identities", 0);
export const PamIdentities = defineLimitFeature("pam_identities", 0);
+export const AgentVaultIdentities = defineLimitFeature("agent_vault_identities", 0);
// Human users (org members), excluding machine identities. For legacy per-user plans that count seats.
export const UserIdentities = defineLimitFeature("user_identities", 0);
diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.ts
index 64a23caa24..50e5660b0f 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -252,6 +252,14 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
+ const countAgentVaultIdentities = async (orgId?: string): Promise<number> => {
+ try {
+ return await countProjectIdentities(ProjectType.AgentVault, orgId);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count Agent Vault identities for usage" });
+ }
+ };
+
return {
countInternalCas,
resolveRootOrgId,
@@ -259,6 +267,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
isCertificateQuotaKeyActiveInOrg,
countPamResources,
countSecretManagementIdentities,
- countPamIdentities
+ countPamIdentities,
+ countAgentVaultIdentities
};
};
diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.ts
index 4043041b34..fa3c67cf7e 100644
--- a/backend/src/services/license-client/usage/usage-counters.ts
+++ b/backend/src/services/license-client/usage/usage-counters.ts
@@ -3,6 +3,7 @@ import { TLicenseDALFactory } from "@app/ee/services/license/license-dal";
import { TFeatureCounterFn, TLimitFeatureDescriptor } from "../feature";
import {
ActiveCerts,
+ AgentVaultIdentities,
IdentitiesMeter,
InternalCas,
PamIdentities,
@@ -30,6 +31,7 @@ export const METERED_DIMENSION_KEYS: string[] = [
WildcardCerts,
SecretIdentities,
PamIdentities,
+ AgentVaultIdentities,
UserIdentities
].map((feature) => feature.key);
@@ -79,6 +81,10 @@ export const buildMeteredFeatures = ({
feature: PamIdentities,
count: (orgId) => usageCounterDAL.countPamIdentities(isCloud ? orgId : undefined)
},
+ {
+ feature: AgentVaultIdentities,
+ count: (orgId) => usageCounterDAL.countAgentVaultIdentities(isCloud ? orgId : undefined)
+ },
{
// Human users only (org members), never machine identities. Legacy per-user plans.
feature: UserIdentities,
diff --git a/backend/src/services/license-client/usage/usage-metering.test.ts b/backend/src/services/license-client/usage/usage-metering.test.ts
index a7fb6629b8..1b559cd429 100644
--- a/backend/src/services/license-client/usage/usage-metering.test.ts
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -5,6 +5,7 @@ import { QueueJobs, QueueName } from "@app/queue";
import { featureReaderFactory } from "../feature-reader";
import {
ActiveCerts,
+ AgentVaultIdentities,
IdentitiesMeter,
InternalCas,
PamIdentities,
@@ -242,7 +243,8 @@ describe("buildMeteredFeatures", () => {
isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false),
countPamResources: vi.fn(async () => 3),
countSecretManagementIdentities: vi.fn(async () => 4),
- countPamIdentities: vi.fn(async () => 5)
+ countPamIdentities: vi.fn(async () => 5),
+ countAgentVaultIdentities: vi.fn(async () => 6)
};
const metered = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: true });
@@ -255,6 +257,7 @@ describe("buildMeteredFeatures", () => {
WildcardCerts.key,
SecretIdentities.key,
PamIdentities.key,
+ AgentVaultIdentities.key,
UserIdentities.key
].sort()
);
@@ -268,11 +271,13 @@ describe("buildMeteredFeatures", () => {
expect(await byKey[WildcardCerts.key](ORG_ID)).toBe(1);
expect(await byKey[SecretIdentities.key](ORG_ID)).toBe(4);
expect(await byKey[PamIdentities.key](ORG_ID)).toBe(5);
+ expect(await byKey[AgentVaultIdentities.key](ORG_ID)).toBe(6);
expect(await byKey[UserIdentities.key](ORG_ID)).toBe(8);
expect(licenseDAL.countOrgUsersAndIdentities).toHaveBeenCalledWith(ORG_ID);
// Cloud scopes the identity meters to the org.
expect(usageCounterDAL.countSecretManagementIdentities).toHaveBeenCalledWith(ORG_ID);
expect(usageCounterDAL.countPamIdentities).toHaveBeenCalledWith(ORG_ID);
+ expect(usageCounterDAL.countAgentVaultIdentities).toHaveBeenCalledWith(ORG_ID);
expect(licenseDAL.countOfOrgMembers).toHaveBeenCalledWith(ORG_ID);
});
@@ -290,7 +295,8 @@ describe("buildMeteredFeatures", () => {
isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false),
countPamResources: vi.fn(async () => 0),
countSecretManagementIdentities: vi.fn(async () => 0),
- countPamIdentities: vi.fn(async () => 0)
+ countPamIdentities: vi.fn(async () => 0),
+ countAgentVaultIdentities: vi.fn(async () => 0)
};
const metered = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: false });
const byKey = Object.fromEntries(metered.map((m) => [m.feature.key, m.count]));
@@ -316,7 +322,8 @@ describe("buildMeteredFeatures", () => {
isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false),
countPamResources: vi.fn(async () => 0),
countSecretManagementIdentities: vi.fn(async () => 9),
- countPamIdentities: vi.fn(async () => 6)
+ countPamIdentities: vi.fn(async () => 6),
+ countAgentVaultIdentities: vi.fn(async () => 0)
};
const metered = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: false });
const secret = metered.find((m) => m.feature.key === SecretIdentities.key);
@@ -564,7 +571,8 @@ describe("canUse enforcement (using the framework from a call site)", () => {
isCertificateQuotaKeyActiveInOrg: async () => false,
countPamResources: async () => 0,
countSecretManagementIdentities: async () => 0,
- countPamIdentities: async () => 0
+ countPamIdentities: async () => 0,
+ countAgentVaultIdentities: async () => 0
};
buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: true }).forEach(({ feature, count }) =>
reader.registerCounter(feature, count)
diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.ts
index 3d0d5132e0..aa4f9e7aa7 100644
--- a/backend/src/services/membership-group/membership-group-service.ts
+++ b/backend/src/services/membership-group/membership-group-service.ts
@@ -20,13 +20,13 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { ms } from "@app/lib/ms";
import { SearchResourceOperators } from "@app/lib/search-resource/search";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";
import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";
-import { assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
+import { assertProductWillRetainAdmin, assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TOrgDALFactory } from "../org/org-dal";
import { ApplicationMemberKind } from "../pki-application/pki-application-types";
@@ -226,6 +226,7 @@ export const membershipGroupServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
}
return { membership, group };
};
@@ -301,6 +302,17 @@ export const membershipGroupServiceFactory = ({
const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug);
const membershipDoc = await membershipGroupDAL.transaction(async (tx) => {
+ const newRolesHavePermanentAdmin = data.roles.some(
+ (r) => r.role === ProjectMembershipRole.Admin && !r.isTemporary
+ );
+ if (!newRolesHavePermanentAdmin && scopeData.scope === AccessScope.Project) {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(scopeData.projectId, tx),
+ excludeMembershipIds: [existingMembership.id],
+ tx
+ });
+ }
+
const doc =
typeof data?.isActive === "undefined"
? existingMembership
@@ -422,6 +434,12 @@ export const membershipGroupServiceFactory = ({
const performDelete = async (tx: Knex) => {
if (scopeData.scope === AccessScope.Project && existingMembership.scopeProjectId) {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(existingMembership.scopeProjectId, tx),
+ excludeMembershipIds: [existingMembership.id],
+ tx
+ });
+
await applicationMembershipCleanupService.cleanupActorApplicationMemberships(
{
projectId: existingMembership.scopeProjectId,
@@ -483,6 +501,7 @@ export const membershipGroupServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
}
return { membership: membershipDoc, group };
};
diff --git a/backend/src/services/membership-group/project/project-membership-group-factory.ts b/backend/src/services/membership-group/project/project-membership-group-factory.ts
index be84c0ffb9..86ba89a553 100644
--- a/backend/src/services/membership-group/project/project-membership-group-factory.ts
+++ b/backend/src/services/membership-group/project/project-membership-group-factory.ts
@@ -1,6 +1,6 @@
import { ForbiddenError } from "@casl/ability";
-import { AccessScope, ActionProjectType, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
+import { AccessScope, ActionProjectType, getAdminMemberOnlyProductLabel, ProjectMembershipRole } from "@app/db/schemas";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import {
assertRoleSetBoundary,
@@ -72,13 +72,20 @@ export const newProjectMembershipGroupFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scope.value), () =>
projectDAL.findById(scope.value)
);
- if (project?.type === ProjectType.CertificateManager) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = dto.data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: "Certificate Manager only supports Admin and Member roles."
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
+ });
+ }
+ // One role per membership: the product routes write exactly one, and their member lists read one.
+ if (dto.data.roles.length > 1) {
+ throw new BadRequestError({
+ message: `${adminMemberOnlyLabel} memberships hold a single role.`
});
}
}
@@ -142,13 +149,20 @@ export const newProjectMembershipGroupFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scope.value), () =>
projectDAL.findById(scope.value)
);
- if (project?.type === ProjectType.CertificateManager) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = dto.data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: "Certificate Manager only supports Admin and Member roles."
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
+ });
+ }
+ // One role per membership: the product routes write exactly one, and their member lists read one.
+ if (dto.data.roles.length > 1) {
+ throw new BadRequestError({
+ message: `${adminMemberOnlyLabel} memberships hold a single role.`
});
}
}
diff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.ts
index 3e763a599f..882177b1c6 100644
--- a/backend/src/services/membership-identity/membership-identity-service.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.ts
@@ -11,14 +11,14 @@ import { SearchResourceOperators } from "@app/lib/search-resource/search";
import { TAlertServiceFactory } from "@app/services/alert/alert-service";
import { IDENTITY_AUTHENTICATION_RESOURCE_TYPE } from "@app/services/alert/providers/identity-credential-alert-provider";
import { getIdentityActiveLockoutAuthMethods } from "@app/services/identity/identity-fns";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { TIdentityDALFactory } from "../identity/identity-dal";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";
-import { assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
+import { assertProductWillRetainAdmin, assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TOrgDALFactory } from "../org/org-dal";
import { ApplicationMemberKind } from "../pki-application/pki-application-types";
@@ -231,6 +231,7 @@ export const membershipIdentityServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
}
return { membership };
};
@@ -309,6 +310,18 @@ export const membershipIdentityServiceFactory = ({
let shouldRestoreOrgTokens = false;
const membershipDoc = await membershipIdentityDAL.transaction(async (tx) => {
+ // The project advisory lock before the row lock, the order every other caller takes: a product-route
+ // change holding the advisory lock needs KEY SHARE on this row, so the reverse order deadlocks.
+ const newRolesHavePermanentAdmin = data.roles.some(
+ (r) => r.role === ProjectMembershipRole.Admin && !r.isTemporary
+ );
+ if (!newRolesHavePermanentAdmin && scopeData.scope === AccessScope.Project) {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(scopeData.projectId, tx),
+ excludeMembershipIds: [existingMembership.id],
+ tx
+ });
+ }
const currentMembership = await membershipIdentityDAL.findByIdForUpdate(existingMembership.id, tx);
if (!currentMembership) {
throw new BadRequestError({ message: "Identity doesn't have membership" });
@@ -416,6 +429,14 @@ export const membershipIdentityServiceFactory = ({
});
const performDelete = async (tx: Knex) => {
+ if (scopeData.scope === AccessScope.Project) {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(scopeData.projectId, tx),
+ excludeMembershipIds: [existingMembership.id],
+ tx
+ });
+ }
+
await additionalPrivilegeDAL.delete(
{
actorIdentityId: dto.selector.identityId,
@@ -479,9 +500,11 @@ export const membershipIdentityServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
} else {
usageMeteringService.emit(scopeData.orgId, SecretIdentities.key);
usageMeteringService.emit(scopeData.orgId, PamIdentities.key);
+ usageMeteringService.emit(scopeData.orgId, AgentVaultIdentities.key);
}
if (needsRevocationBump && externalTx) {
diff --git a/backend/src/services/membership-identity/project/project-membership-identity-factory.ts b/backend/src/services/membership-identity/project/project-membership-identity-factory.ts
index d620612ce3..4333995a25 100644
--- a/backend/src/services/membership-identity/project/project-membership-identity-factory.ts
+++ b/backend/src/services/membership-identity/project/project-membership-identity-factory.ts
@@ -1,6 +1,6 @@
import { ForbiddenError, subject } from "@casl/ability";
-import { AccessScope, ActionProjectType, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
+import { AccessScope, ActionProjectType, getAdminMemberOnlyProductLabel, ProjectMembershipRole } from "@app/db/schemas";
import {
assertRoleSetBoundary,
constructPermissionErrorMessage,
@@ -79,13 +79,20 @@ export const newProjectMembershipIdentityFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scope.value), () =>
projectDAL.findById(scope.value)
);
- if (project?.type === ProjectType.CertificateManager) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = dto.data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: "Certificate Manager only supports Admin and Member roles."
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
+ });
+ }
+ // One role per membership: the product routes write exactly one, and their member lists read one.
+ if (dto.data.roles.length > 1) {
+ throw new BadRequestError({
+ message: `${adminMemberOnlyLabel} memberships hold a single role.`
});
}
}
@@ -160,13 +167,20 @@ export const newProjectMembershipIdentityFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scope.value), () =>
projectDAL.findById(scope.value)
);
- if (project?.type === ProjectType.CertificateManager) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = dto.data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: "Certificate Manager only supports Admin and Member roles."
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
+ });
+ }
+ // One role per membership: the product routes write exactly one, and their member lists read one.
+ if (dto.data.roles.length > 1) {
+ throw new BadRequestError({
+ message: `${adminMemberOnlyLabel} memberships hold a single role.`
});
}
}
diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.ts
index fc5b8356cd..63ba9ba02d 100644
--- a/backend/src/services/membership-user/membership-user-service.ts
+++ b/backend/src/services/membership-user/membership-user-service.ts
@@ -22,7 +22,7 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { SearchResourceOperators } from "@app/lib/search-resource/search";
import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";
import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
@@ -30,7 +30,7 @@ import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-da
import { AuthMethod } from "../auth/auth-type";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";
-import { assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
+import { assertProductWillRetainAdmin, assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TOrgDALFactory } from "../org/org-dal";
import { deleteOrgMembershipsFn } from "../org/org-fns";
@@ -412,6 +412,7 @@ export const membershipUserServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
}
return { memberships: membershipDoc, signUpTokens };
};
@@ -499,6 +500,13 @@ export const membershipUserServiceFactory = ({
tx
});
}
+ if (!newRolesHavePermanentAdmin && scopeData.scope === AccessScope.Project) {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(scopeData.projectId, tx),
+ excludeMembershipIds: [existingMembership.id],
+ tx
+ });
+ }
const doc =
typeof data?.isActive === "undefined"
@@ -598,6 +606,12 @@ export const membershipUserServiceFactory = ({
}
if (dto.scopeData.scope === AccessScope.Project) {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(dto.scopeData.projectId, tx),
+ excludeMembershipIds: [existingMembership.id],
+ tx
+ });
+
await additionalPrivilegeDAL.delete(
{
actorUserId: dto.selector.userId,
@@ -635,9 +649,11 @@ export const membershipUserServiceFactory = ({
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
usageMeteringService.emitForProject(scopeData.projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(scopeData.projectId, AgentVaultIdentities.key);
} else {
usageMeteringService.emit(scopeData.orgId, SecretIdentities.key);
usageMeteringService.emit(scopeData.orgId, PamIdentities.key);
+ usageMeteringService.emit(scopeData.orgId, AgentVaultIdentities.key);
}
return { membership: membershipDoc };
};
diff --git a/backend/src/services/membership-user/project/admin-member-only-role-guard.test.ts b/backend/src/services/membership-user/project/admin-member-only-role-guard.test.ts
new file mode 100644
index 0000000000..99fab7d6cf
--- /dev/null
+++ b/backend/src/services/membership-user/project/admin-member-only-role-guard.test.ts
@@ -0,0 +1,124 @@
+import { createMongoAbility } from "@casl/ability";
+import { describe, expect, test, vi } from "vitest";
+
+import { AccessScope, getAdminMemberOnlyProductLabel, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
+import { newProjectMembershipGroupFactory } from "@app/services/membership-group/project/project-membership-group-factory";
+import { newProjectMembershipIdentityFactory } from "@app/services/membership-identity/project/project-membership-identity-factory";
+
+import { newProjectMembershipUserFactory } from "./project-membership-user-factory";
+
+const PROJECT_ID = "project-1";
+
+// Only the collaborators reached before the role check; anything later is left undefined so a guard
+// that fails to reject shows up as a crash rather than a silent pass.
+const buildDeps = (projectType: ProjectType) => ({
+ permissionService: {
+ getProjectPermission: vi
+ .fn()
+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) })
+ },
+ projectDAL: { findById: vi.fn().mockResolvedValue({ id: PROJECT_ID, type: projectType }) },
+ orgDAL: {},
+ groupDAL: {},
+ membershipGroupDAL: {},
+ membershipUserDAL: {},
+ membershipIdentityDAL: {},
+ userDAL: {},
+ identityDAL: {},
+ additionalPrivilegeDAL: {},
+ projectKeyDAL: {},
+ projectBotDAL: {},
+ smtpService: {},
+ licenseService: {}
+});
+
+const dto = (role: string) => ({
+ scopeData: { scope: AccessScope.Project, projectId: PROJECT_ID },
+ permission: { type: "user", id: "actor-1", authMethod: undefined, orgId: "org-1" },
+ data: { roles: [{ role }], groupId: "group-1", identityId: "identity-1", username: "user-1" },
+ selector: { username: "user-1" }
+});
+
+type Guard = (guardDto: unknown) => Promise<unknown>;
+
+const guards: { name: string; build: (projectType: ProjectType) => Guard }[] = [
+ {
+ name: "user",
+ build: (projectType) =>
+ newProjectMembershipUserFactory(
+ buildDeps(projectType) as unknown as Parameters<typeof newProjectMembershipUserFactory>[0]
+ ).onUpdateMembershipUserGuard as unknown as Guard
+ },
+ {
+ name: "identity",
+ build: (projectType) =>
+ newProjectMembershipIdentityFactory(
+ buildDeps(projectType) as unknown as Parameters<typeof newProjectMembershipIdentityFactory>[0]
+ ).onUpdateMembershipIdentityGuard as unknown as Guard
+ },
+ {
+ name: "group",
+ build: (projectType) =>
+ newProjectMembershipGroupFactory(
+ buildDeps(projectType) as unknown as Parameters<typeof newProjectMembershipGroupFactory>[0]
+ ).onUpdateMembershipGroupGuard as unknown as Guard
+ }
+];
+
+describe("getAdminMemberOnlyProductLabel", () => {
+ // The set is the whole contract: a product missing from it silently accepts a role that its
+ // permission resolver then upgrades to the member rule set.
+ test.each([
+ [ProjectType.CertificateManager, "Certificate Manager"],
+ [ProjectType.PAM, "Privileged Access Manager"],
+ [ProjectType.AgentVault, "Agent Vault"]
+ ])("covers %s", (type, label) => {
+ expect(getAdminMemberOnlyProductLabel(type)).toBe(label);
+ });
+
+ test.each([[ProjectType.SecretManager], [ProjectType.KMS], [ProjectType.SecretScanning]])(
+ "leaves %s alone",
+ (type) => {
+ expect(getAdminMemberOnlyProductLabel(type)).toBeUndefined();
+ }
+ );
+
+ test("tolerates a missing project", () => {
+ expect(getAdminMemberOnlyProductLabel(undefined)).toBeUndefined();
+ expect(getAdminMemberOnlyProductLabel(null)).toBeUndefined();
+ });
+});
+
+describe.each(guards)("$name membership guard", ({ build }) => {
+ test.each([[ProjectType.AgentVault], [ProjectType.PAM], [ProjectType.CertificateManager]])(
+ "refuses a viewer role on %s",
+ async (type) => {
+ await expect(build(type)(dto(ProjectMembershipRole.Viewer))).rejects.toThrow(
+ "only supports Admin and Member roles"
+ );
+ }
+ );
+
+ test("refuses a custom role slug too", async () => {
+ await expect(build(ProjectType.AgentVault)(dto("some-custom-role"))).rejects.toThrow(
+ "only supports Admin and Member roles"
+ );
+ });
+
+ test.each([[ProjectMembershipRole.Admin], [ProjectMembershipRole.Member]])(
+ "allows %s past the check",
+ async (role) => {
+ // The guard runs before the rest of the collaborators, which are undefined here, so getting past
+ // it surfaces as some other failure rather than the role message.
+ await expect(build(ProjectType.AgentVault)(dto(role))).rejects.not.toThrow(
+ "only supports Admin and Member roles"
+ );
+ }
+ );
+
+ test("does not apply to Secrets Management", async () => {
+ await expect(build(ProjectType.SecretManager)(dto(ProjectMembershipRole.Viewer))).rejects.not.toThrow(
+ "only supports Admin and Member roles"
+ );
+ });
+});
diff --git a/backend/src/services/membership-user/project/project-membership-user-factory.ts b/backend/src/services/membership-user/project/project-membership-user-factory.ts
index 91c7c63525..78ad72c81a 100644
--- a/backend/src/services/membership-user/project/project-membership-user-factory.ts
+++ b/backend/src/services/membership-user/project/project-membership-user-factory.ts
@@ -3,9 +3,9 @@ import { ForbiddenError } from "@casl/ability";
import {
AccessScope,
ActionProjectType,
+ getAdminMemberOnlyProductLabel,
OrgMembershipStatus,
- ProjectMembershipRole,
- ProjectType
+ ProjectMembershipRole
} from "@app/db/schemas";
import {
assertRoleSetBoundary,
@@ -103,13 +103,20 @@ export const newProjectMembershipUserFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scope.value), () =>
projectDAL.findById(scope.value)
);
- if (project?.type === ProjectType.CertificateManager) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = dto.data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: "Certificate Manager only supports Admin and Member roles."
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
+ });
+ }
+ // One role per membership: the product routes write exactly one, and their member lists read one.
+ if (dto.data.roles.length > 1) {
+ throw new BadRequestError({
+ message: `${adminMemberOnlyLabel} memberships hold a single role.`
});
}
}
@@ -215,13 +222,20 @@ export const newProjectMembershipUserFactory = ({
const project = await requestMemoize(requestMemoKeys.projectFindById(scope.value), () =>
projectDAL.findById(scope.value)
);
- if (project?.type === ProjectType.CertificateManager) {
+ const adminMemberOnlyLabel = getAdminMemberOnlyProductLabel(project?.type);
+ if (adminMemberOnlyLabel) {
const invalidRoles = dto.data.roles.filter(
(r) => r.role !== ProjectMembershipRole.Admin && r.role !== ProjectMembershipRole.Member
);
if (invalidRoles.length > 0) {
throw new BadRequestError({
- message: "Certificate Manager only supports Admin and Member roles."
+ message: `${adminMemberOnlyLabel} only supports Admin and Member roles.`
+ });
+ }
+ // One role per membership: the product routes write exactly one, and their member lists read one.
+ if (dto.data.roles.length > 1) {
+ throw new BadRequestError({
+ message: `${adminMemberOnlyLabel} memberships hold a single role.`
});
}
}
diff --git a/backend/src/services/membership/membership-fns.ts b/backend/src/services/membership/membership-fns.ts
index 7dfac28d6c..e05c98708c 100644
--- a/backend/src/services/membership/membership-fns.ts
+++ b/backend/src/services/membership/membership-fns.ts
@@ -1,6 +1,16 @@
-import { AccessScope, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
+import { Knex } from "knex";
+
+import {
+ AccessScope,
+ getAdminMemberOnlyProductLabel,
+ OrgMembershipRole,
+ ProjectMembershipRole,
+ ProjectType,
+ TableName
+} from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { isActiveRole } from "@app/ee/services/permission/permission-fns";
+import { PgSqlLock } from "@app/keystore/keystore";
import { BadRequestError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -67,3 +77,60 @@ export const resolveMembershipRoleSlugs = (roles: TMembershipRole[]) => [
.filter((slug) => slug !== OrgMembershipRole.NoAccess && slug !== ProjectMembershipRole.NoAccess)
)
];
+
+type TAssertWillRetainProjectAdminArg = {
+ scopeProjectId: string;
+ excludeMembershipIds: string[];
+ productLabel: string;
+ tx: Knex;
+};
+
+// Must run inside the same transaction as the membership mutation, like assertWillRetainOrgAdmin: the
+// advisory lock serializes admin mutations per project so two concurrent demotions cannot both pass the
+// count and leave none. Every actor kind counts, since a group or machine identity holding the admin role
+// can still administer the product, and a lapsed temporary role confers nothing so it is not counted.
+export const assertWillRetainProjectAdmin = async ({
+ scopeProjectId,
+ excludeMembershipIds,
+ productLabel,
+ tx
+}: TAssertWillRetainProjectAdminArg) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.LastAdminGuard("project", scopeProjectId)]);
+
+ const query = tx(TableName.Membership)
+ .join(TableName.MembershipRole, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)
+ .where(`${TableName.Membership}.scope`, AccessScope.Project)
+ .where(`${TableName.Membership}.scopeProjectId`, scopeProjectId)
+ .where(`${TableName.Membership}.isActive`, true)
+ .where(`${TableName.MembershipRole}.role`, ProjectMembershipRole.Admin)
+ .where((qb) => {
+ void qb
+ .where(`${TableName.MembershipRole}.isTemporary`, false)
+ .orWhere(`${TableName.MembershipRole}.temporaryAccessEndTime`, ">", new Date());
+ });
+ if (excludeMembershipIds.length) {
+ void query.whereNotIn(`${TableName.Membership}.id`, excludeMembershipIds);
+ }
+
+ const result = await query.countDistinct<{ count: string }[]>(`${TableName.Membership}.id as count`).first();
+ if (Number(result?.count ?? 0) < 1) {
+ throw new BadRequestError({ message: `${productLabel} must keep at least one admin` });
+ }
+};
+
+// The org-scoped products refuse to lose their last admin on their own routes; the generic project
+// membership routes reach the same rows, so they run the same check when the project is one of those.
+export const assertProductWillRetainAdmin = async ({
+ project,
+ excludeMembershipIds,
+ tx
+}: {
+ project: { id: string; type?: string | null } | undefined | null;
+ excludeMembershipIds: string[];
+ tx: Knex;
+}) => {
+ if (project?.type !== ProjectType.AgentVault) return;
+ const productLabel = getAdminMemberOnlyProductLabel(project.type);
+ if (!productLabel) return;
+ await assertWillRetainProjectAdmin({ scopeProjectId: project.id, excludeMembershipIds, productLabel, tx });
+};
diff --git a/backend/src/services/org-admin/org-admin-service.ts b/backend/src/services/org-admin/org-admin-service.ts
index 4182538c6a..936ce4b7ec 100644
--- a/backend/src/services/org-admin/org-admin-service.ts
+++ b/backend/src/services/org-admin/org-admin-service.ts
@@ -1,9 +1,11 @@
import { ForbiddenError } from "@casl/ability";
-import { AccessScope, OrganizationActionScope, ProjectMembershipRole } from "@app/db/schemas";
+import { AccessScope, OrganizationActionScope, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
import { OrgPermissionAdminConsoleAction, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { NotFoundError } from "@app/lib/errors";
+import { AgentVaultIdentities } from "@app/services/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
@@ -22,6 +24,7 @@ type TOrgAdminServiceFactoryDep = {
membershipRoleDAL: TMembershipRoleDALFactory;
smtpService: Pick<TSmtpService, "sendMail">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
};
export type TOrgAdminServiceFactory = ReturnType<typeof orgAdminServiceFactory>;
@@ -33,7 +36,8 @@ export const orgAdminServiceFactory = ({
smtpService,
notificationService,
membershipUserDAL,
- membershipRoleDAL
+ membershipRoleDAL,
+ usageMeteringService
}: TOrgAdminServiceFactoryDep) => {
const listOrgProjects = async ({
actor,
@@ -125,6 +129,11 @@ export const orgAdminServiceFactory = ({
return { isExistingMember: true, membership: updatedMembership };
}
+ // Agent Vault's project starts empty and admins join through here, so this is where its seat count moves.
+ if (project.type === ProjectType.AgentVault) {
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
+ }
+
const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
const projectAdmins = projectMembers.filter(
(member) => member.roles.some((role) => role.role === ProjectMembershipRole.Admin) && member.userId !== actorId
diff --git a/backend/src/services/org-product-stats/org-product-stats-dal.ts b/backend/src/services/org-product-stats/org-product-stats-dal.ts
index 3e04420b9c..ef2347c2a2 100644
--- a/backend/src/services/org-product-stats/org-product-stats-dal.ts
+++ b/backend/src/services/org-product-stats/org-product-stats-dal.ts
@@ -176,6 +176,59 @@ export const orgProductStatsDALFactory = (db: TDbClient) => {
}
};
+ const countAgentVaultAccessBundlesForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.AgentVaultAccessBundle)
+ .join(TableName.Project, `${TableName.AgentVaultAccessBundle}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.Project}.type`, ProjectType.AgentVault)
+ .count(`${TableName.AgentVaultAccessBundle}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountAgentVaultAccessBundlesForOrg" });
+ }
+ };
+
+ const countAgentVaultServicesForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.AgentVaultService)
+ .join(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultService}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ )
+ .join(TableName.Project, `${TableName.AgentVaultAccessBundle}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.Project}.type`, ProjectType.AgentVault)
+ .count(`${TableName.AgentVaultService}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountAgentVaultServicesForOrg" });
+ }
+ };
+
+ const countAgentVaultProxiesForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.AgentVaultProxy)
+ .join(TableName.Project, `${TableName.AgentVaultProxy}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.Project}.type`, ProjectType.AgentVault)
+ .count(`${TableName.AgentVaultProxy}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountAgentVaultProxiesForOrg" });
+ }
+ };
+
const countPamAccountTemplatesForOrg = async (orgId: string, tx?: Knex) => {
try {
const result = (await (tx || db.replicaNode())(TableName.PamAccountTemplate)
@@ -242,6 +295,9 @@ export const orgProductStatsDALFactory = (db: TDbClient) => {
countPamAccountsForOrg,
countPamAccountTemplatesForOrg,
countPamFoldersForOrg,
+ countAgentVaultAccessBundlesForOrg,
+ countAgentVaultServicesForOrg,
+ countAgentVaultProxiesForOrg,
countProjectsByTypeForOrg
};
};
diff --git a/backend/src/services/org-product-stats/org-product-stats-service.ts b/backend/src/services/org-product-stats/org-product-stats-service.ts
index 2aa658ce49..b9378ccc67 100644
--- a/backend/src/services/org-product-stats/org-product-stats-service.ts
+++ b/backend/src/services/org-product-stats/org-product-stats-service.ts
@@ -24,6 +24,9 @@ export const orgProductStatsServiceFactory = ({ orgProductStatsDAL }: TOrgProduc
accountsCount,
accountTemplatesCount,
foldersCount,
+ accessBundlesCount,
+ servicesCount,
+ proxiesCount,
projectCounts
] = await Promise.all([
orgProductStatsDAL.countSecretsForOrg(actorOrgId),
@@ -38,6 +41,9 @@ export const orgProductStatsServiceFactory = ({ orgProductStatsDAL }: TOrgProduc
orgProductStatsDAL.countPamAccountsForOrg(actorOrgId),
orgProductStatsDAL.countPamAccountTemplatesForOrg(actorOrgId),
orgProductStatsDAL.countPamFoldersForOrg(actorOrgId),
+ orgProductStatsDAL.countAgentVaultAccessBundlesForOrg(actorOrgId),
+ orgProductStatsDAL.countAgentVaultServicesForOrg(actorOrgId),
+ orgProductStatsDAL.countAgentVaultProxiesForOrg(actorOrgId),
orgProductStatsDAL.countProjectsByTypeForOrg(actorOrgId)
]);
@@ -66,6 +72,11 @@ export const orgProductStatsServiceFactory = ({ orgProductStatsDAL }: TOrgProduc
accountsCount,
accountTemplatesCount,
foldersCount
+ },
+ agentVault: {
+ accessBundlesCount,
+ servicesCount,
+ proxiesCount
}
};
};
diff --git a/backend/src/services/org-product-stats/org-product-stats-types.ts b/backend/src/services/org-product-stats/org-product-stats-types.ts
index c9aaa0399f..e660d0ef53 100644
--- a/backend/src/services/org-product-stats/org-product-stats-types.ts
+++ b/backend/src/services/org-product-stats/org-product-stats-types.ts
@@ -28,4 +28,9 @@ export type TOrgProductStats = {
accountTemplatesCount: number;
foldersCount: number;
};
+ agentVault: {
+ accessBundlesCount: number;
+ servicesCount: number;
+ proxiesCount: number;
+ };
};
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index dab663ff5e..7bf1c1d059 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -12,6 +12,7 @@ import {
TOidcConfigs,
TSamlConfigs
} from "@app/db/schemas";
+import { bootstrapAgentVaultProject } from "@app/ee/services/agent-vault-project/agent-vault-project-bootstrap";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TLdapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dal";
@@ -39,7 +40,7 @@ import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { getDefaultOrgMembershipRoleForUpdateOrg } from "@app/services/org/org-role-fns";
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
@@ -218,10 +219,16 @@ export const orgServiceFactory = ({
{ sort: [["createdAt", "desc"]], limit: 1 }
);
+ const agentVaultProjects = await projectDAL.find(
+ { orgId: data.id, type: ProjectType.AgentVault },
+ { sort: [["createdAt", "desc"]], limit: 1 }
+ );
+
return {
...data,
userTokenExpiration: data.userTokenExpiration || appCfg.JWT_REFRESH_LIFETIME,
- pamProjectId: pamProjects[0]?.id ?? null
+ pamProjectId: pamProjects[0]?.id ?? null,
+ agentVaultProjectId: agentVaultProjects[0]?.id ?? null
};
};
@@ -722,6 +729,15 @@ export const orgServiceFactory = ({
tx
);
+ await bootstrapAgentVaultProject(
+ {
+ orgId: org.id,
+ adminUserIds: userId ? [userId] : []
+ },
+ { projectDAL, membershipDAL, membershipRoleDAL },
+ tx
+ );
+
return org;
};
@@ -729,8 +745,8 @@ export const orgServiceFactory = ({
await licenseService.updateSubscriptionOrgMemberCount(organization.id, trx);
- // The PAM bootstrap above seeds the creator as a project member, which changes the pam_identities meter.
usageMeteringService.emit(organization.id, PamIdentities.key);
+ usageMeteringService.emit(organization.id, AgentVaultIdentities.key);
return organization;
};
@@ -1290,6 +1306,7 @@ export const orgServiceFactory = ({
// Removing an org member cascades their project + group memberships, changing the identity meters.
usageMeteringService.emit(orgId, SecretIdentities.key);
usageMeteringService.emit(orgId, PamIdentities.key);
+ usageMeteringService.emit(orgId, AgentVaultIdentities.key);
return deletedMembership;
};
@@ -1345,6 +1362,7 @@ export const orgServiceFactory = ({
// Removing org members cascades their project + group memberships, changing the identity meters.
usageMeteringService.emit(orgId, SecretIdentities.key);
usageMeteringService.emit(orgId, PamIdentities.key);
+ usageMeteringService.emit(orgId, AgentVaultIdentities.key);
return deletedMemberships;
};
diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.ts
index 7eec770007..464833db67 100644
--- a/backend/src/services/project-membership/project-membership-service.ts
+++ b/backend/src/services/project-membership/project-membership-service.ts
@@ -12,7 +12,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { groupBy, unique } from "@app/lib/fn";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAccessApprovalPolicyApproverDALFactory } from "../../ee/services/access-approval-policy/access-approval-policy-approver-dal";
@@ -25,7 +25,7 @@ import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipie
import { ActorType } from "../auth/auth-type";
import { TGroupProjectDALFactory } from "../group-project/group-project-dal";
import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";
-import { resolveMembershipRoleSlugs } from "../membership/membership-fns";
+import { assertProductWillRetainAdmin, resolveMembershipRoleSlugs } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
import { TNotificationServiceFactory } from "../notification/notification-service";
@@ -377,6 +377,7 @@ export const projectMembershipServiceFactory = ({
}
usageMeteringService.emitForProject(projectId, SecretIdentities.key);
usageMeteringService.emitForProject(projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
return orgMembers;
};
@@ -457,6 +458,12 @@ export const projectMembershipServiceFactory = ({
);
const performDelete = async (tx: Knex) => {
+ await assertProductWillRetainAdmin({
+ project: await projectDAL.findById(projectId, tx),
+ excludeMembershipIds: projectMembers.map(({ id }) => id),
+ tx
+ });
+
await additionalPrivilegeDAL.delete(
{
projectId,
@@ -524,6 +531,7 @@ export const projectMembershipServiceFactory = ({
usageMeteringService.emitForProject(projectId, SecretIdentities.key);
usageMeteringService.emitForProject(projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
return memberships;
};
@@ -570,6 +578,8 @@ export const projectMembershipServiceFactory = ({
);
const deletedMembership = await membershipUserDAL.transaction(async (tx) => {
+ await assertProductWillRetainAdmin({ project, excludeMembershipIds: [actorMembership.id], tx });
+
await additionalPrivilegeDAL.delete(
{
projectId: project.id,
@@ -617,6 +627,7 @@ export const projectMembershipServiceFactory = ({
usageMeteringService.emitForProject(projectId, SecretIdentities.key);
usageMeteringService.emitForProject(projectId, PamIdentities.key);
+ usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);
return deletedMembership;
};
diff --git a/backend/src/services/project-role/project-role-fns.ts b/backend/src/services/project-role/project-role-fns.ts
index 1d9e1aa169..a657794c0a 100644
--- a/backend/src/services/project-role/project-role-fns.ts
+++ b/backend/src/services/project-role/project-role-fns.ts
@@ -10,7 +10,18 @@ import {
} from "@app/ee/services/permission/default-roles";
import { TGetPredefinedRolesDTO } from "@app/services/project-role/project-role-types";
+// Agent Vault resolves every slug except admin to its member set, so Viewer and No Access would promise
+// less access than they grant.
+const NARROWED_ROLE_PROJECT_TYPES = new Set<string>([ProjectType.AgentVault]);
+const NARROWED_ROLE_SLUGS = new Set<string>([ProjectMembershipRole.Admin, ProjectMembershipRole.Member]);
+
+const AGENT_VAULT_ROLE_DESCRIPTIONS: Record<string, string> = {
+ [ProjectMembershipRole.Admin]: "Full administrative access over Agent Vault",
+ [ProjectMembershipRole.Member]: "Create sessions over the access bundles they're granted"
+};
+
export const getPredefinedRoles = ({ projectId, projectType, roleFilter }: TGetPredefinedRolesDTO) => {
+ const isNarrowed = NARROWED_ROLE_PROJECT_TYPES.has(projectType);
return [
{
id: uuidv4(),
@@ -63,5 +74,16 @@ export const getPredefinedRoles = ({ projectId, projectType, roleFilter }: TGetP
createdAt: new Date(),
updatedAt: new Date()
}
- ].filter(({ slug, type }) => (type ? type === projectType : true) && (!roleFilter || roleFilter === slug));
+ ]
+ .filter(
+ ({ slug, type }) =>
+ (type ? type === projectType : true) &&
+ (!roleFilter || roleFilter === slug) &&
+ (!isNarrowed || NARROWED_ROLE_SLUGS.has(slug))
+ )
+ .map((role) =>
+ projectType === ProjectType.AgentVault && AGENT_VAULT_ROLE_DESCRIPTIONS[role.slug]
+ ? { ...role, description: AGENT_VAULT_ROLE_DESCRIPTIONS[role.slug] }
+ : role
+ );
};
diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.ts
index ce614ae995..385ca6199b 100644
--- a/backend/src/services/project/project-dal.ts
+++ b/backend/src/services/project/project-dal.ts
@@ -1018,7 +1018,7 @@ export const projectDALFactory = (db: TDbClient) => {
const doc = await (tx || db.replicaNode())(TableName.Project)
.whereNotIn("type", [ProjectType.CertificateManager])
.whereNull("deleteAfter")
- .whereNotIn("type", [ProjectType.CertificateManager, ProjectType.PAM])
+ .whereNotIn("type", [ProjectType.CertificateManager, ProjectType.PAM, ProjectType.AgentVault])
// Project rows of the removed SSH / Agent Sentinel products are left in
// place (see migration 20260729150000) but must not consume workspace quota.
.whereNotIn("type", ["ssh", "ai"])
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index 3350df746c..64291fb8b9 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -57,7 +57,7 @@ import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";
import { OrgServiceActor, TProjectPermission } from "@app/lib/types";
-import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";
@@ -209,7 +209,8 @@ const PROJECT_ACCESS_REQUEST_URL_SLUGS: Partial<Record<ProjectType, string>> = {
const PROJECT_ACCESS_REQUEST_PRODUCT_LABELS: Partial<Record<ProjectType, string>> = {
[ProjectType.CertificateManager]: "Certificate Manager",
- [ProjectType.PAM]: "Privileged Access Manager"
+ [ProjectType.PAM]: "Privileged Access Manager",
+ [ProjectType.AgentVault]: "Agent Vault"
};
export const projectServiceFactory = ({
@@ -265,6 +266,12 @@ export const projectServiceFactory = ({
type = ProjectType.SecretManager,
hasDeleteProtection
}: TCreateProjectDTO) => {
+ if (type === ProjectType.AgentVault) {
+ throw new BadRequestError({
+ message: "Agent Vault projects cannot be created directly. One is created for your organization automatically."
+ });
+ }
+
const organization = await orgDAL.findOne({ id: actorOrgId });
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
@@ -748,6 +755,7 @@ export const projectServiceFactory = ({
// the just-committed row; the counter filters by project type.
usageMeteringService.emit(results.orgId, SecretIdentities.key);
usageMeteringService.emit(results.orgId, PamIdentities.key);
+ usageMeteringService.emit(results.orgId, AgentVaultIdentities.key);
return results;
};
@@ -777,6 +785,12 @@ export const projectServiceFactory = ({
});
}
+ if (project.type === ProjectType.AgentVault) {
+ throw new BadRequestError({
+ message: "Agent Vault projects cannot be deleted."
+ });
+ }
+
if (project.type === ProjectType.CertificateManager) {
const certManagerProjects = await projectDAL.find({
orgId: project.orgId,
@@ -832,6 +846,7 @@ export const projectServiceFactory = ({
// The soft-deleted project drops out of the meters' counts, so its members no longer count.
usageMeteringService.emit(project.orgId, SecretIdentities.key);
usageMeteringService.emit(project.orgId, PamIdentities.key);
+ usageMeteringService.emit(project.orgId, AgentVaultIdentities.key);
return { ...softDeletedProject, slug: project.slug };
} finally {
await lock.release();
@@ -956,6 +971,14 @@ export const projectServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
+ // The org-scoped products own one implicit project each, so its name, slug and delete protection are
+ // not the caller's to change. Create and delete are already guarded; this route was not.
+ if (project.type === ProjectType.AgentVault || project.type === ProjectType.PAM) {
+ throw new BadRequestError({
+ message: `${PROJECT_ACCESS_REQUEST_PRODUCT_LABELS[project.type]} is managed for your organization and cannot be renamed or reconfigured here.`
+ });
+ }
+
if (update.secretDetectionIgnoreValues && !hasRole(ProjectMembershipRole.Admin)) {
throw new ForbiddenRequestError({
message: "Only admins can update secret detection ignore values"
@@ -2275,11 +2298,15 @@ export const projectServiceFactory = ({
const projectTypeUrl = PROJECT_ACCESS_REQUEST_URL_SLUGS[project.type as ProjectType] ?? project.type;
const encodedRequesterEmail = encodeURIComponent(userDetails.email ?? "");
- // PAM is a per-org singleton with no project-scoped route, unlike other product types
- const callbackPath =
- project.type === ProjectType.PAM
- ? `/organizations/${project.orgId}/pam/access-management?selectedTab=members&requesterEmail=${encodedRequesterEmail}`
- : `/organizations/${project.orgId}/projects/${projectTypeUrl}/${project.id}/access-management?selectedTab=members&requesterEmail=${encodedRequesterEmail}`;
+ const orgScopedProductPath: Partial<Record<ProjectType, string>> = {
+ [ProjectType.PAM]: "pam",
+ [ProjectType.AgentVault]: "agent-vault"
+ };
+ const orgScopedPath = orgScopedProductPath[project.type as ProjectType];
+
+ const callbackPath = orgScopedPath
+ ? `/organizations/${project.orgId}/${orgScopedPath}/access-management?selectedTab=members&requesterEmail=${encodedRequesterEmail}`
+ : `/organizations/${project.orgId}/projects/${projectTypeUrl}/${project.id}/access-management?selectedTab=members&requesterEmail=${encodedRequesterEmail}`;
const productLabel = PROJECT_ACCESS_REQUEST_PRODUCT_LABELS[project.type as ProjectType] ?? null;
const notificationTitle = productLabel ? `${productLabel} Access Request` : "Project Access Request";
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
index c6a04318a2..0edd21bccd 100644
--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
@@ -1,3 +1,4 @@
+import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";
import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";
import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TScepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";
@@ -40,6 +41,7 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {
approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "markExpiredGrants">;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "markExpiredApprovalRequests">;
scepTransactionDAL: Pick<TScepTransactionDALFactory, "pruneExpiredTransactions">;
+ agentVaultSessionService: Pick<TAgentVaultSessionServiceFactory, "sweepRetiredSessions">;
};
export type TDailyResourceCleanUpQueueServiceFactory = ReturnType<typeof dailyResourceCleanUpQueueServiceFactory>;
@@ -63,7 +65,8 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
approvalRequestDAL,
approvalRequestGrantsDAL,
certificateRequestDAL,
- scepTransactionDAL
+ scepTransactionDAL,
+ agentVaultSessionService
}: TDailyResourceCleanUpQueueServiceFactoryDep) => {
const appCfg = getConfig();
@@ -96,6 +99,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
await keyValueStoreDAL.pruneExpiredKeys();
await scepTransactionDAL.pruneExpiredTransactions();
await identityAccessTokenRevocationDAL.removeExpiredRevocations();
+ await agentVaultSessionService.sweepRetiredSessions();
}
});
diff --git a/backend/src/services/role/project/project-role-factory.ts b/backend/src/services/role/project/project-role-factory.ts
index 6cd0908755..258e43e553 100644
--- a/backend/src/services/role/project/project-role-factory.ts
+++ b/backend/src/services/role/project/project-role-factory.ts
@@ -1,14 +1,6 @@
import { ForbiddenError } from "@casl/ability";
-import { v4 as uuidv4 } from "uuid";
-import { AccessScope, ActionProjectType, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
-import {
- cryptographicOperatorPermissions,
- projectAdminPermissions,
- projectMemberPermissions,
- projectNoAccessPermissions,
- projectViewerPermission
-} from "@app/ee/services/permission/default-roles";
+import { AccessScope, ActionProjectType, ProjectType } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
isCustomProjectRole,
@@ -19,6 +11,7 @@ import { BadRequestError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getPredefinedRoles as buildPredefinedRoles } from "@app/services/project-role/project-role-fns";
import { TRoleScopeFactory } from "../role-types";
@@ -124,61 +117,7 @@ export const newProjectRoleFactory = ({
projectDAL.findById(scope.value)
);
if (!project) throw new BadRequestError({ message: "Project not found" });
- const projectId = project.id;
-
- return [
- {
- id: uuidv4(),
- name: "Admin",
- slug: ProjectMembershipRole.Admin,
- permissions: projectAdminPermissions,
- description: "Full administrative access over a project",
- createdAt: new Date(),
- updatedAt: new Date(),
- projectId
- },
- {
- id: uuidv4(),
- name: "Member",
- slug: ProjectMembershipRole.Member,
- permissions: projectMemberPermissions,
- description: "Limited read/write role in a project",
- createdAt: new Date(),
- updatedAt: new Date(),
- projectId
- },
- {
- id: uuidv4(),
- name: "Cryptographic Operator",
- slug: ProjectMembershipRole.KmsCryptographicOperator,
- permissions: cryptographicOperatorPermissions,
- description: "Perform cryptographic operations, such as encryption and signing, in a project",
- createdAt: new Date(),
- updatedAt: new Date(),
- projectId,
- type: ProjectType.KMS
- },
- {
- id: uuidv4(),
- name: "Viewer",
- slug: ProjectMembershipRole.Viewer,
- permissions: projectViewerPermission,
- description: "Only read role in a project",
- createdAt: new Date(),
- projectId,
- updatedAt: new Date()
- },
- {
- id: uuidv4(),
- name: "No Access",
- slug: ProjectMembershipRole.NoAccess,
- permissions: projectNoAccessPermissions,
- description: "No access to any resources in the project",
- createdAt: new Date(),
- projectId,
- updatedAt: new Date()
- }
- ].filter(({ type }) => (type ? type === project.type : true));
+ return buildPredefinedRoles({ projectId: project.id, projectType: project.type as ProjectType });
};
return {
diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts
index 92dd35c822..5cdd4e0d39 100644
--- a/backend/src/services/super-admin/super-admin-service.ts
+++ b/backend/src/services/super-admin/super-admin-service.ts
@@ -33,7 +33,13 @@ import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/valida
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
-import { IdentitiesMeter, PamIdentities, SecretIdentities, UserIdentities } from "@app/services/license-client";
+import {
+ AgentVaultIdentities,
+ IdentitiesMeter,
+ PamIdentities,
+ SecretIdentities,
+ UserIdentities
+} from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
@@ -734,6 +740,7 @@ export const superAdminServiceFactory = ({
usageMeteringService.emit(orgId, UserIdentities.key);
usageMeteringService.emit(orgId, SecretIdentities.key);
usageMeteringService.emit(orgId, PamIdentities.key);
+ usageMeteringService.emit(orgId, AgentVaultIdentities.key);
});
};
diff --git a/backend/src/services/telemetry/telemetry-dal.ts b/backend/src/services/telemetry/telemetry-dal.ts
index 30bd968f48..16138905db 100644
--- a/backend/src/services/telemetry/telemetry-dal.ts
+++ b/backend/src/services/telemetry/telemetry-dal.ts
@@ -76,7 +76,11 @@ export const telemetryDALFactory = (db: TDbClient) => {
accessApprovalPolicies,
honeyTokens,
proxiedServices,
- proxiedServicesUsedLast7Days
+ proxiedServicesUsedLast7Days,
+ agentVaultProxies,
+ activeAgentVaultProxies,
+ agentVaultAccessBundles,
+ agentVaultServices
] = await Promise.all([
(async () => {
const result = (await db(TableName.Users).where({ isGhost: false }).count().first())?.count as string;
@@ -140,7 +144,20 @@ export const telemetryDALFactory = (db: TDbClient) => {
.first()
)?.count as string;
return parseInt(result || "0", 10);
- })()
+ })(),
+ countTable(db, TableName.AgentVaultProxy),
+ (async () => {
+ const result = (
+ await db(TableName.AgentVaultProxy)
+ .whereNotNull("heartbeat")
+ .whereRaw(`"heartbeat" > NOW() - make_interval(secs => "pollInterval" * 3)`)
+ .count()
+ .first()
+ )?.count as string;
+ return parseInt(result || "0", 10);
+ })(),
+ countTable(db, TableName.AgentVaultAccessBundle),
+ countTable(db, TableName.AgentVaultService)
]);
// Per-type identity auth method breakdown
@@ -304,6 +321,10 @@ export const telemetryDALFactory = (db: TDbClient) => {
honeyTokens,
proxiedServices,
proxiedServicesUsedLast7Days,
+ agentVaultProxies,
+ activeAgentVaultProxies,
+ agentVaultAccessBundles,
+ agentVaultServices,
integrationBreakdown,
projectTypeBreakdown,
secretSyncBreakdown,
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 657f522276..56b1372977 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -1,7 +1,9 @@
import { IdentityAuthMethod, ProjectType } from "@app/db/schemas";
+import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";
import {
AcmeAccountActor,
AcmeProfileActor,
+ AgentVaultProxyActor,
EstAccountActor,
GatewayActor,
IdentityActor,
@@ -297,7 +299,28 @@ export enum PostHogEventTypes {
SecretRotationV2Failed = "Secret Rotation V2 Failed",
// Agent Proxy
- ProxiedServiceCreated = "Proxied Service Created"
+ ProxiedServiceCreated = "Proxied Service Created",
+
+ // Agent Vault
+ AgentVaultAccessBundleCreated = "Agent Vault Access Bundle Created",
+ AgentVaultAccessBundleUpdated = "Agent Vault Access Bundle Updated",
+ AgentVaultAccessBundleDeleted = "Agent Vault Access Bundle Deleted",
+ AgentVaultServiceCreated = "Agent Vault Service Created",
+ AgentVaultServiceUpdated = "Agent Vault Service Updated",
+ AgentVaultServiceDeleted = "Agent Vault Service Deleted",
+ AgentVaultAccessBundleMemberAdded = "Agent Vault Access Bundle Member Added",
+ AgentVaultAccessBundleMemberRemoved = "Agent Vault Access Bundle Member Removed",
+ AgentVaultSessionCreated = "Agent Vault Session Created",
+ AgentVaultSessionRevoked = "Agent Vault Session Revoked",
+ AgentVaultProxyRegistered = "Agent Vault Proxy Registered",
+ AgentVaultProxyUpdated = "Agent Vault Proxy Updated",
+ AgentVaultProxyDeleted = "Agent Vault Proxy Deleted",
+ AgentVaultProxyAccessRevoked = "Agent Vault Proxy Access Revoked",
+ AgentVaultProxyEnrollmentTokenReissued = "Agent Vault Proxy Enrollment Token Reissued",
+ AgentVaultProxyEnrolled = "Agent Vault Proxy Enrolled",
+ AgentVaultProductMemberAdded = "Agent Vault Product Member Added",
+ AgentVaultProductMemberUpdated = "Agent Vault Product Member Updated",
+ AgentVaultProductMemberRemoved = "Agent Vault Product Member Removed"
}
export type TSecretModifiedEvent = {
@@ -330,7 +353,8 @@ export type TSecretModifiedEvent = {
| ScepAccountActor
| GatewayActor
| RelayActor
- | KmipServerActor;
+ | KmipServerActor
+ | AgentVaultProxyActor;
};
};
@@ -638,6 +662,10 @@ export type TTelemetryInstanceStatsEvent = {
honeyTokens: number;
proxiedServices: number;
proxiedServicesUsedLast7Days: number;
+ agentVaultProxies: number;
+ activeAgentVaultProxies: number;
+ agentVaultAccessBundles: number;
+ agentVaultServices: number;
integrationBreakdown: Record<string, number>;
projectTypeBreakdown: Record<string, number>;
secretSyncBreakdown: Record<string, number>;
@@ -2337,6 +2365,159 @@ export type TProxiedServiceCreatedEvent = {
};
};
+type TAgentVaultEventBase = {
+ orgId: string;
+ channel: string;
+ actorType: string;
+};
+
+type TAgentVaultMemberType = "user" | "group" | "identity";
+
+export type TAgentVaultAccessBundleCreatedEvent = {
+ event: PostHogEventTypes.AgentVaultAccessBundleCreated;
+ properties: TAgentVaultEventBase & { accessBundleId: string };
+};
+
+export type TAgentVaultAccessBundleUpdatedEvent = {
+ event: PostHogEventTypes.AgentVaultAccessBundleUpdated;
+ properties: TAgentVaultEventBase & { accessBundleId: string };
+};
+
+export type TAgentVaultAccessBundleDeletedEvent = {
+ event: PostHogEventTypes.AgentVaultAccessBundleDeleted;
+ properties: TAgentVaultEventBase & { accessBundleId: string };
+};
+
+export type TAgentVaultServiceCreatedEvent = {
+ event: PostHogEventTypes.AgentVaultServiceCreated;
+ properties: TAgentVaultEventBase & {
+ accessBundleId: string;
+ serviceId: string;
+ credentialType: AgentVaultCredentialType;
+ hostPatternCount: number;
+ };
+};
+
+export type TAgentVaultServiceUpdatedEvent = {
+ event: PostHogEventTypes.AgentVaultServiceUpdated;
+ properties: TAgentVaultEventBase & {
+ accessBundleId: string;
+ serviceId: string;
+ credentialType: AgentVaultCredentialType;
+ hostPatternCount: number;
+ };
+};
+
+export type TAgentVaultServiceDeletedEvent = {
+ event: PostHogEventTypes.AgentVaultServiceDeleted;
+ properties: TAgentVaultEventBase & { accessBundleId: string; serviceId: string };
+};
+
+export type TAgentVaultAccessBundleMemberAddedEvent = {
+ event: PostHogEventTypes.AgentVaultAccessBundleMemberAdded;
+ properties: TAgentVaultEventBase & { accessBundleId: string; memberType: TAgentVaultMemberType };
+};
+
+export type TAgentVaultAccessBundleMemberRemovedEvent = {
+ event: PostHogEventTypes.AgentVaultAccessBundleMemberRemoved;
+ properties: TAgentVaultEventBase & { accessBundleId: string; memberType: TAgentVaultMemberType };
+};
+
+export type TAgentVaultSessionCreatedEvent = {
+ event: PostHogEventTypes.AgentVaultSessionCreated;
+ properties: TAgentVaultEventBase & {
+ sessionId: string;
+ accessBundleId: string;
+ ttlSeconds: number | null;
+ };
+};
+
+export type TAgentVaultSessionRevokedEvent = {
+ event: PostHogEventTypes.AgentVaultSessionRevoked;
+ properties: TAgentVaultEventBase & { sessionId: string };
+};
+
+export type TAgentVaultProxyRegisteredEvent = {
+ event: PostHogEventTypes.AgentVaultProxyRegistered;
+ properties: TAgentVaultEventBase & {
+ proxyId: string;
+ trafficPolicy: AgentVaultTrafficPolicy;
+ allowedHostCount: number;
+ };
+};
+
+export type TAgentVaultProxyUpdatedEvent = {
+ event: PostHogEventTypes.AgentVaultProxyUpdated;
+ properties: TAgentVaultEventBase & {
+ proxyId: string;
+ trafficPolicy: AgentVaultTrafficPolicy;
+ allowedHostCount: number;
+ };
+};
+
+export type TAgentVaultProxyDeletedEvent = {
+ event: PostHogEventTypes.AgentVaultProxyDeleted;
+ properties: TAgentVaultEventBase & { proxyId: string };
+};
+
+export type TAgentVaultProxyAccessRevokedEvent = {
+ event: PostHogEventTypes.AgentVaultProxyAccessRevoked;
+ properties: TAgentVaultEventBase & { proxyId: string };
+};
+
+export type TAgentVaultProxyEnrollmentTokenReissuedEvent = {
+ event: PostHogEventTypes.AgentVaultProxyEnrollmentTokenReissued;
+ properties: TAgentVaultEventBase & { proxyId: string };
+};
+
+export type TAgentVaultProxyEnrolledEvent = {
+ event: PostHogEventTypes.AgentVaultProxyEnrolled;
+ properties: {
+ orgId: string;
+ channel: string;
+ proxyId: string;
+ replacedExistingCa: boolean;
+ };
+};
+
+export type TAgentVaultProductMemberAddedEvent = {
+ event: PostHogEventTypes.AgentVaultProductMemberAdded;
+ properties: TAgentVaultEventBase & { memberType: TAgentVaultMemberType; role: string };
+};
+
+export type TAgentVaultProductMemberUpdatedEvent = {
+ event: PostHogEventTypes.AgentVaultProductMemberUpdated;
+ properties: TAgentVaultEventBase & { memberType: TAgentVaultMemberType; role: string };
+};
+
+export type TAgentVaultProductMemberRemovedEvent = {
+ event: PostHogEventTypes.AgentVaultProductMemberRemoved;
+ properties: TAgentVaultEventBase & { memberType: TAgentVaultMemberType };
+};
+
+export type TAgentVaultPostHogEvent =
+ | TAgentVaultAccessBundleCreatedEvent
+ | TAgentVaultAccessBundleUpdatedEvent
+ | TAgentVaultAccessBundleDeletedEvent
+ | TAgentVaultServiceCreatedEvent
+ | TAgentVaultServiceUpdatedEvent
+ | TAgentVaultServiceDeletedEvent
+ | TAgentVaultAccessBundleMemberAddedEvent
+ | TAgentVaultAccessBundleMemberRemovedEvent
+ | TAgentVaultSessionCreatedEvent
+ | TAgentVaultSessionRevokedEvent
+ | TAgentVaultProxyRegisteredEvent
+ | TAgentVaultProxyUpdatedEvent
+ | TAgentVaultProxyDeletedEvent
+ | TAgentVaultProxyAccessRevokedEvent
+ | TAgentVaultProxyEnrollmentTokenReissuedEvent
+ | TAgentVaultProxyEnrolledEvent
+ | TAgentVaultProductMemberAddedEvent
+ | TAgentVaultProductMemberUpdatedEvent
+ | TAgentVaultProductMemberRemovedEvent;
+
+export type TAgentVaultActorPostHogEvent = Exclude<TAgentVaultPostHogEvent, TAgentVaultProxyEnrolledEvent>;
+
export type TPostHogEvent = {
distinctId: string;
organizationId?: string;
@@ -2566,4 +2747,5 @@ export type TPostHogEvent = {
| TAccessApprovalPolicyUpdatedEvent
| TSecretRotationV2FailedEvent
| TProxiedServiceCreatedEvent
+ | TAgentVaultPostHogEvent
);
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index f721b0e1a5..0d72de18a2 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -15,7 +15,13 @@ import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-chan
import { AlertPrincipalType } from "@app/services/alert/alert-types";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
-import { IdentitiesMeter, PamIdentities, SecretIdentities, UserIdentities } from "@app/services/license-client";
+import {
+ AgentVaultIdentities,
+ IdentitiesMeter,
+ PamIdentities,
+ SecretIdentities,
+ UserIdentities
+} from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
@@ -629,6 +635,7 @@ export const userServiceFactory = ({
usageMeteringService.emit(orgId, UserIdentities.key);
usageMeteringService.emit(orgId, SecretIdentities.key);
usageMeteringService.emit(orgId, PamIdentities.key);
+ usageMeteringService.emit(orgId, AgentVaultIdentities.key);
});
try {
diff --git a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
index f1370a610c..202b451fd9 100644
--- a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
+++ b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
@@ -45,7 +45,7 @@
(?i)scan
(?i)flags
(?i)sub commands
-(?i)infisical (?:agent|agent-proxy|bootstrap|dynamic-secrets|export|gateway|init|kmip|login|pam|relay|reset|run|scan|secrets|service-token|token|user|vault)
+(?i)infisical (?:agent|agent-proxy|agent-vault|av|bootstrap|dynamic-secrets|export|gateway|init|kmip|login|pam|relay|reset|run|scan|secrets|service-token|token|user|vault)
# Acronyms that collide with ordinary English words, shell commands, or
# Kubernetes units.
@@ -281,6 +281,8 @@ I
(?i)Infisical Relay
(?i)Agent Injector
(?i)Agent Proxy
+(?i)Agent Vault
+(?i)Realtime
(?i)Secrets Management
(?i)Certificate Management
(?i)Privileged Access Management
diff --git a/docs/cli/commands/agent-vault.mdx b/docs/cli/commands/agent-vault.mdx
new file mode 100644
index 0000000000..2f7c628b8b
--- /dev/null
+++ b/docs/cli/commands/agent-vault.mdx
@@ -0,0 +1,280 @@
+---
+title: "infisical agent-vault"
+description: "Run an Agent Vault proxy, and launch agents through it"
+---
+
+```bash
+# Where agent traffic leaves your network
+infisical agent-vault proxy --enrollment-token <enrollment-token>
+
+# Where the agent runs
+infisical agent-vault run --session-token <session-token> --proxy <proxy-host>:17323 -- claude
+infisical agent-vault run --access-bundle <bundle-name> --proxy <proxy-host>:17323 -- claude
+```
+
+## Description
+
+These subcommands are the CLI half of [Agent Vault](/documentation/platform/agent-vault/overview). `proxy` runs the process that attaches credentials to agent traffic. `run` launches an agent with its HTTP traffic routed through a proxy and a session token to identify it.
+
+The two usually run on different machines. A proxy's settings are set on the Proxies page, not with flags, and reach a running proxy on its next poll.
+
+`av` is an alias for `agent-vault`, so `infisical av run` works wherever `infisical agent-vault run` does.
+
+## infisical agent-vault proxy
+
+Run an Agent Vault proxy. Enroll once with the token shown when the proxy was created. Later runs need no token. The proxy keeps its certificate authority, its token, and its last settings in a data directory, and passing the same enrollment token again on a restart is harmless. See [Proxies](/documentation/platform/agent-vault/proxies).
+
+```bash
+infisical agent-vault proxy --enrollment-token <enrollment-token>
+
+# Once enrolled
+infisical agent-vault proxy
+
+# Example
+infisical agent-vault proxy --port 18000 --log-format json --log-file /var/log/infisical/agent-vault.log
+```
+
+### Flags
+
+#### `--enrollment-token`
+
+The one-time token shown when the proxy was created, valid for an hour. Needed on the first run and on a re-enrollment; a proxy that has already enrolled serves without it.
+
+```bash
+# Example
+infisical agent-vault proxy --enrollment-token <enrollment-token>
+```
+
+#### `--data-dir`
+
+Where to keep the certificate authority and proxy token. Must persist across restarts.
+
+```bash
+# Example
+infisical agent-vault proxy --data-dir /var/lib/infisical/agent-vault
+```
+
+Default value: `~/.infisical/agent-vault`, or `/etc/infisical/agent-vault` when run as root
+
+#### `--port`
+
+Port to listen on.
+
+```bash
+# Example
+infisical agent-vault proxy --port 18000
+```
+
+Default value: `17323`
+
+#### `--log-format`
+
+`console` for a human-readable stream, `json` for machines. Logs go to stderr.
+
+```bash
+# Example
+infisical agent-vault proxy --log-format json
+```
+
+Default value: `console`
+
+#### `--log-file`
+
+Also write logs to this file.
+
+```bash
+# Example
+infisical agent-vault proxy --log-file /var/log/infisical/agent-vault.log
+```
+
+### Environment variables
+
+#### `INFISICAL_AGENT_VAULT_ENROLLMENT_TOKEN`
+
+The one-time enrollment token from the Proxies page. Alternative to `--enrollment-token`, and the way to keep the token off the command line.
+
+```bash
+# Example
+export INFISICAL_AGENT_VAULT_ENROLLMENT_TOKEN=<enrollment-token>
+```
+
+#### `INFISICAL_AGENT_VAULT_DATA_DIR`
+
+Where the proxy keeps its certificate authority and token. Alternative to `--data-dir`.
+
+```bash
+# Example
+export INFISICAL_AGENT_VAULT_DATA_DIR=/var/lib/infisical/agent-vault
+```
+
+#### `INFISICAL_DOMAIN`
+
+Point the CLI to your Infisical instance. Alternative to the [`--domain`](#flags-accepted-by-every-subcommand) flag, which every subcommand accepts.
+
+```bash
+# Example
+export INFISICAL_DOMAIN=https://eu.infisical.com
+```
+
+## infisical agent-vault run
+
+Launch an agent through an Agent Vault proxy. Everything after `--` is the agent's own command. On each run, the CLI:
+
+- Fetches the proxy's certificate authority from the proxy, checks it against `--ca-fingerprint` if you passed one, and writes it to `--ca-file`.
+- Gets a session: the one you pass with `--session-token`, or one created now with the access bundle named by `--access-bundle`. Exactly one of the two is required.
+- Starts the agent with `HTTPS_PROXY` and `HTTP_PROXY` pointing at the proxy, `NO_PROXY` set to `localhost,127.0.0.1` merged with your own `NO_PROXY` and `--no-proxy`, and the certificate trusted through `SSL_CERT_FILE`, `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, `GIT_SSL_CAINFO`, and `DENO_CERT`.
+
+The CLI prints the proxy's name and fingerprint and, for a session it created, when it expires, then hands the terminal to the agent. When the agent exits, a session created with `--access-bundle` is revoked unless `--keep-session` was set. A session passed with `--session-token` is left alone.
+
+```bash
+infisical agent-vault run --session-token <session-token> --proxy <proxy-host>:17323 -- [agent start command]
+
+# Pin the certificate authority the proxy serves
+infisical agent-vault run --session-token <session-token> --proxy 10.0.1.5:17323 --ca-fingerprint SHA256:9F:2C:... -- claude
+
+# Create the session here instead, as your login or a machine identity
+infisical agent-vault run --access-bundle on-call-infrastructure --proxy 10.0.1.5:17323 -- claude
+```
+
+### Flags
+
+#### `--session-token`
+
+Run with a session token created in the dashboard. No login is needed, and the CLI never revokes the session. Can't be combined with `--access-bundle`.
+
+```bash
+# Example
+infisical agent-vault run --session-token <session-token> --proxy 10.0.1.5:17323 -- claude
+```
+
+#### `--access-bundle`
+
+Create a session with this access bundle, by name. Pass it once. Creates it as the machine identity from `--client-id` and `--client-secret`, or as your login. The identity has to be an Agent Vault member with a grant on the access bundle. Can't be combined with `--session-token`.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --proxy 10.0.1.5:17323 -- claude
+```
+
+#### `--proxy`
+
+Address of the Agent Vault proxy as `host:port`. Required, unless set through `INFISICAL_AGENT_VAULT_PROXY_ADDRESS`.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --proxy 10.0.1.5:17323 -- claude
+```
+
+#### `--ttl`
+
+How long the new session lives: one number and one unit, such as `30m`, `8h`, or `7d` (not `2h30m`), or `never`. One minute is the shortest. Only applies with `--access-bundle`.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --ttl 8h --proxy 10.0.1.5:17323 -- claude
+```
+
+Default value: `7d`
+
+#### `--keep-session`
+
+Leave the session active when the agent exits instead of revoking it. Only applies with `--access-bundle`.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --keep-session --proxy 10.0.1.5:17323 -- claude
+```
+
+Default value: `false`
+
+#### `--ca-fingerprint`
+
+Abort unless the certificate authority the proxy serves matches this SHA256 fingerprint, copied from the Proxies page. Accepted with or without the `SHA256:` prefix and colons.
+
+```bash
+# Example
+infisical agent-vault run --session-token <session-token> --proxy 10.0.1.5:17323 --ca-fingerprint SHA256:9F:2C:... -- claude
+```
+
+#### `--ca-file`
+
+Where to write the certificate authority fetched from the proxy.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --proxy 10.0.1.5:17323 --ca-file /tmp/agent-vault-ca.pem -- claude
+```
+
+Default value: `~/.infisical/agent-vault/ca-<proxy-id>.pem`, one file per proxy
+
+#### `--no-ca-trust`
+
+Skip writing the certificate authority and setting the trust variables, for a machine that already trusts this proxy's certificate. A `--ca-fingerprint` mismatch is still caught.
+
+```bash
+# Example
+infisical agent-vault run --session-token <session-token> --proxy 10.0.1.5:17323 --no-ca-trust -- claude
+```
+
+Default value: `false`
+
+#### `--no-proxy`
+
+Additional comma-separated hosts the agent reaches directly, without the proxy. Always merged with `localhost,127.0.0.1` and any `NO_PROXY` already in your environment.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --proxy 10.0.1.5:17323 --no-proxy internal.corp.com -- claude
+```
+
+#### `--client-id / --client-secret`
+
+Universal Auth credentials of the machine identity that creates the session. Alternative to the `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` and `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET` environment variables.
+
+```bash
+# Example
+infisical agent-vault run --access-bundle code-review --client-id <client-id> --client-secret <client-secret> --proxy 10.0.1.5:17323 -- claude
+```
+
+### Environment variables
+
+#### `INFISICAL_AGENT_VAULT_PROXY_ADDRESS`
+
+Address of the proxy as `host:port`. Alternative to `--proxy`.
+
+```bash
+# Example
+export INFISICAL_AGENT_VAULT_PROXY_ADDRESS=10.0.1.5:17323
+```
+
+#### `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID / INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET`
+
+Universal Auth credentials of the machine identity that creates the session when you use `--access-bundle`. Alternative to `--client-id` and `--client-secret`. Without them the CLI creates it as your logged-in user.
+
+```bash
+# Example
+export INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id>
+export INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret>
+```
+
+#### `INFISICAL_DOMAIN`
+
+Point the CLI to your Infisical instance. Alternative to the [`--domain`](#flags-accepted-by-every-subcommand) flag, which every subcommand accepts.
+
+```bash
+# Example
+export INFISICAL_DOMAIN=https://eu.infisical.com
+```
+
+## Flags accepted by every subcommand
+
+#### `--domain`
+
+Point the CLI to your Infisical instance, such as `https://eu.infisical.com` for EU Cloud or your self-hosted URL. Can also be set through the `INFISICAL_DOMAIN` environment variable.
+
+```bash
+# Example
+infisical agent-vault proxy --domain https://your-instance.com --enrollment-token <enrollment-token>
+```
+
+Default value: `https://app.infisical.com`
diff --git a/docs/docs.json b/docs/docs.json
index 3d8c49bc23..0fd16d588a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -410,8 +410,7 @@
"documentation/platform/agent-proxy/standalone-agent-proxy",
"documentation/platform/agent-proxy/activity-logs"
]
- },
- "documentation/platform/agent-proxy/agent-vault"
+ }
]
}
]
@@ -746,6 +745,28 @@
]
}
]
+ },
+ {
+ "item": "Agent Vault",
+ "icon": "sparkles",
+ "pages": [
+ "documentation/platform/agent-vault/overview",
+ {
+ "group": "Get started",
+ "pages": [
+ "documentation/platform/agent-vault/quickstart"
+ ]
+ },
+ {
+ "group": "Product reference",
+ "pages": [
+ "documentation/platform/agent-vault/access-bundles",
+ "documentation/platform/agent-vault/sessions",
+ "documentation/platform/agent-vault/proxies",
+ "documentation/platform/agent-vault/access-control"
+ ]
+ }
+ ]
}
]
},
@@ -1248,6 +1269,7 @@
"cli/commands/run",
"cli/commands/secrets",
"cli/commands/agent-proxy",
+ "cli/commands/agent-vault",
"cli/commands/dynamic-secrets",
{
"group": "infisical pam",
diff --git a/docs/documentation/getting-started/overview.mdx b/docs/documentation/getting-started/overview.mdx
index a56a121861..3ebd43ad06 100644
--- a/docs/documentation/getting-started/overview.mdx
+++ b/docs/documentation/getting-started/overview.mdx
@@ -31,6 +31,9 @@ Select a product to get started:
<Card title="Privileged Access Management" icon="user-shield" href="/documentation/platform/pam/overview">
Manage access to resources like databases, servers, and accounts with policy-based controls and approvals.
</Card>
+ <Card title="Agent Vault" icon="sparkles" href="/documentation/platform/agent-vault/overview">
+ Run AI agents with the access, context, and capabilities they need to do work, without ever holding a credential.
+ </Card>
</CardGroup>
## Platform
diff --git a/docs/documentation/platform/agent-proxy/agent-vault.mdx b/docs/documentation/platform/agent-proxy/agent-vault.mdx
deleted file mode 100644
index b2e30f4b7c..0000000000
--- a/docs/documentation/platform/agent-proxy/agent-vault.mdx
+++ /dev/null
@@ -1,6 +0,0 @@
----
-title: "Agent Vault"
-sidebarTitle: "Agent Vault"
-url: "https://docs.agent-vault.dev/"
-icon: "arrow-up-right-from-square"
----
diff --git a/docs/documentation/platform/agent-vault/access-bundles.mdx b/docs/documentation/platform/agent-vault/access-bundles.mdx
new file mode 100644
index 0000000000..8cdc0c0be9
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx
@@ -0,0 +1,64 @@
+---
+title: "Access bundles and services"
+description: "How access bundles group services and who can run agents with them, and what a service sends and where."
+---
+
+An access bundle is what you hand an agent: everything it needs for a job, granted and revoked as one unit. A bundle holds services, and names who may run agents with it. A service is one external API the agent may reach, with the hosts that API answers on and the credential the proxy attaches to requests bound for it. You grant access bundles and create sessions with them; the proxy brokers the services inside.
+
+## Access bundles
+
+An access bundle has a name, an optional description, its services, and its members. Granting an access bundle to a user, machine identity, or group lets them create sessions with it. The grantee has to be an Agent Vault member first: see [Access control](/documentation/platform/agent-vault/access-control).
+
+<Frame>
+ <img src="/images/platform/agent-vault/access-bundles-list.png" alt="The Access Bundles page listing four access bundles with their services and member counts" />
+</Frame>
+
+Access bundles are how you scope access. An agent for on-call work gets the incident tooling, an agent for code review gets GitHub, and neither reaches the other's hosts.
+
+Removing a member from an access bundle, or from Agent Vault, takes effect on their running agents within one poll interval of the proxy. Deleting one removes its services from every session that carries it. See [Sessions](/documentation/platform/agent-vault/sessions#what-a-running-agent-can-reach).
+
+## Services
+
+Each service has a name, the hosts it covers, and a credential. Open an access bundle from **Access Bundles** and select **Add Service** to add one.
+
+<Frame>
+ <img src="/images/platform/agent-vault/access-bundle-services.png" alt="The code-review access bundle's Services table listing its GitHub, Slack, and Anthropic services with their credentials and hosts" />
+</Frame>
+
+### Credential types
+
+| Type | What the proxy sends | When to use it |
+| ---------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
+| **Bearer** | One header, `<header name>: <prefix> <value>`. Defaults to `Authorization: Bearer <value>`. | Most APIs. Set the header name to `X-API-Key` and clear the prefix for APIs that take a bare key. |
+| **Basic** | `Authorization: Basic <base64 of username:password>`. Either half can be blank. | APIs behind HTTP basic auth, including ones that put the whole key in the username. |
+| **Pass-through** | Nothing. The request is forwarded unchanged. | To make a host reachable on a proxy that allows only access bundle hosts. See [Traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy). |
+
+The first step offers a **Template** for common services, which fills in the hosts and the header. Choose **Custom** to set them yourself.
+
+<Frame>
+ <img src="/images/platform/agent-vault/service-template-picker.png" alt="The Choose a template panel with Custom, OpenAI, Anthropic, Slack, GitHub, and Google Workspace" />
+</Frame>
+
+If the agent's request already carries a header with the same name, the proxy replaces it with the service's credential.
+
+### Host patterns
+
+A host pattern is a comma-separated list of hosts, each with an optional port:
+
+```text
+api.github.com, uploads.github.com
+*.atlassian.net
+internal-api.example.com:8443
+```
+
+- A host without a port means port `443`. Credentials are attached to HTTPS traffic only.
+- `*.` at the start matches exactly one label. `*.example.com` covers `api.example.com`, not `a.b.example.com` or `example.com`.
+- Paths aren't allowed. A service covers a host, not a route on it.
+
+Keep patterns as narrow as the API allows. A wildcard covers every host under it, and the credential goes to all of them. Some templates carry a placeholder such as `<your-tenant>.atlassian.net` for this reason; replace it with your own tenant before saving.
+
+### When two services cover one host
+
+Within one access bundle, two services can't cover the same host with the same pattern. Infisical rejects the save and names the service that already covers it. An exact host and a wildcard that includes it can both exist, and the exact one wins: if one service covers `api.example.com` and another `*.example.com`, requests to `api.example.com` get the first service's credential.
+
+Different access bundles can cover the same host with different credentials. An agent gets the credential from the access bundle its session carries.
diff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdx
new file mode 100644
index 0000000000..cce43679b0
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/access-control.mdx
@@ -0,0 +1,51 @@
+---
+title: "Access control"
+description: "Understand how permissions work in Agent Vault."
+---
+
+Access control in Agent Vault happens at two levels:
+
+1. **Product membership** — being added to Agent Vault itself
+2. **Access bundle grants** — being granted an access bundle, which is what lets you create sessions with it
+
+Users, groups, and [machine identities](/documentation/platform/identities/machine-identities) all go through both levels and hold the same roles, so everything below applies to all three unless it says otherwise. An agent holds no access of its own: it runs on a session created by a person or a machine identity, and reaches only what that session's access bundle covers.
+
+## Product membership
+
+Agent Vault is organization-wide, so there is one membership list for the whole organization rather than one per project. There are two roles:
+
+| Role | What they can do |
+|------|------------------|
+| **Admin** | Create and manage access bundles, services, and proxies. Grant access bundles. Manage membership. Read audit logs |
+| **Member** | Create sessions with the access bundles granted to them, and revoke their own |
+
+An admin reaches every access bundle without being granted one. A member reaches nothing until an admin grants them one, and sees only the ones they hold. Members see their own sessions; admins can switch the Sessions page between **All Sessions** and **My Sessions**.
+
+<Note>
+ Organization admins can enter Agent Vault as an admin themselves, without being added by someone else. Opening the product from the organization overview is enough.
+</Note>
+
+### Adding members
+
+1. Go to **Agent Vault → Access Control**
+2. Select the **Users**, **Machine Identities**, or **Groups** tab
+3. Select **Add Users**, **Add Machine Identity**, or **Add Group**
+4. Choose who to add, and give them **Admin** or **Member**
+
+Whoever you add has to be an active member of the organization first. Invite them to the organization before adding them here.
+
+You can't change your own role or remove your own access. Ask another admin to do either.
+
+## Access bundle grants
+
+Product membership is the entry ticket. Reaching a host still takes a grant on the [access bundle](/documentation/platform/agent-vault/access-bundles) that holds the service covering it.
+
+Open an access bundle and select **Manage Access** to grant it to a user, machine identity, or group. The grantee has to be an Agent Vault member already.
+
+Granting a group grants everyone in it, and each member creates sessions as themselves. Someone who joins the group later picks the grant up, and someone who leaves loses it.
+
+## When access changes
+
+A change to membership or a grant reaches a running agent within one proxy poll, 60 seconds by default. Nothing on the agent's machine needs restarting.
+
+Removing someone from Agent Vault also takes away their access bundle grants, so adding them back leaves their sessions without credentials until you grant those again. See [what a running agent can reach](/documentation/platform/agent-vault/sessions#what-a-running-agent-can-reach) for what happens to each kind of change mid-run.
diff --git a/docs/documentation/platform/agent-vault/overview.mdx b/docs/documentation/platform/agent-vault/overview.mdx
new file mode 100644
index 0000000000..94bfa26b4c
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/overview.mdx
@@ -0,0 +1,60 @@
+---
+title: "Agent Vault"
+description: "Run AI agents with the access, context, and capabilities they need to do work."
+sidebarTitle: "Agent Vault"
+icon: "sparkles"
+---
+
+**Infisical Agent Vault** equips AI agents with what they need to do work, starting with secure access to the services they call: LLM providers, GitHub, Slack, and more.
+
+Agents like Claude Code or OpenClaw work as they always do. Their requests leave your network with the real credential attached, and the agent never holds it.
+
+```mermaid
+flowchart LR
+ subgraph private["Your private network"]
+ agent["AI agent"]
+ proxy["Agent Vault proxy"]
+ end
+ subgraph internet["Public internet"]
+ apis["api.slack.com<br/>api.github.com<br/>..."]
+ end
+ infisical["Infisical"]
+ agent -->|"request with a session token"| proxy
+ proxy -->|"request with the credential"| apis
+ proxy -->|"fetches the credentials this session may use"| infisical
+```
+
+## Why Agent Vault
+
+Traditional secrets management involves returning credentials back to applications and services.
+
+This isn't suitable for AI agents because they're vulnerable to credential exfiltration via [prompt injection](https://en.wikipedia.org/wiki/Prompt_injection); an attacker could craft a malicious prompt or payload and exfiltrate credentials from an agent back to the attacker.
+
+Enter Infisical Agent Vault, which prevents credential exfiltration by brokering access at the network boundary. The agent gets an access session that works only for the services you allowed, and only until it expires or you revoke it.
+
+## How it works
+
+You describe what an agent may use in an access bundle: one service per API the agent may reach, each with the credential the proxy attaches. You grant the access bundle to whoever runs agents, and they create a session with it to launch the agent. Requests to those services get the right credential on the way out, and everything else is untouched. The agent needs no code changes.
+
+## Get started
+
+<Card title="Quickstart" icon="rocket" href="/documentation/platform/agent-vault/quickstart">
+ Create an access bundle with a service for GitHub, enroll a proxy, and launch an agent that makes authenticated calls with a token it never sees.
+</Card>
+
+## Learn more
+
+<CardGroup cols={2}>
+ <Card title="Access bundles" icon="box" href="/documentation/platform/agent-vault/access-bundles">
+ Services, credential types, host patterns, and who can run agents with an access bundle.
+ </Card>
+ <Card title="Sessions" icon="ticket" href="/documentation/platform/agent-vault/sessions">
+ Creating one, how long it lives, revoking it, and what a running agent can reach.
+ </Card>
+ <Card title="Proxies" icon="route" href="/documentation/platform/agent-vault/proxies">
+ Where the proxy runs, enrolling it, traffic policy, and certificate trust.
+ </Card>
+ <Card title="CLI reference" icon="terminal" href="/cli/commands/agent-vault">
+ Every flag of `infisical agent-vault proxy` and `infisical agent-vault run`.
+ </Card>
+</CardGroup>
diff --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdx
new file mode 100644
index 0000000000..5689f23698
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/proxies.mdx
@@ -0,0 +1,152 @@
+---
+title: "Proxies"
+description: "Run the proxy that attaches credentials, set its traffic policy, and understand how agents trust it."
+---
+
+A proxy is the forward proxy that brokers credentials: it applies the real credential to matching requests on the way out and leaves everything else untouched. It runs where agent traffic leaves your network: on a host of its own that agents across your network share, or next to a single agent. You create it in the dashboard, enroll it once from the CLI, and change its settings from the dashboard afterwards.
+
+## Enrolling
+
+Go to **Proxies**, select **Create Proxy**, name it, and select **Create**. The dialog shows a one-time enrollment token, valid for an hour, and the same three snippets below with your token and instance filled in. Run one of them where the proxy will live:
+
+<Frame>
+ <img src="/images/platform/agent-vault/proxy-enrollment-token.png" alt="The Enrollment Token dialog with CLI, Docker, and systemd tabs and the one-hour countdown" />
+</Frame>
+
+<Tabs>
+ <Tab title="CLI">
+ ```bash
+ infisical agent-vault proxy \
+ --enrollment-token <enrollment-token> \
+ --domain <your-instance-url>
+ ```
+ </Tab>
+ <Tab title="Docker">
+ ```bash
+ docker run -d --name agent-vault-proxy \
+ -p 17323:17323 \
+ -v agent-vault-proxy:/etc/infisical/agent-vault \
+ infisical/cli agent-vault proxy \
+ --enrollment-token <enrollment-token> \
+ --domain <your-instance-url>
+ ```
+
+ The volume holds the state directory, so a re-created container resumes instead of needing a new token.
+ </Tab>
+ <Tab title="systemd">
+ ```ini
+ [Unit]
+ Description=Infisical Agent Vault proxy
+ After=network-online.target
+
+ [Service]
+ ExecStart=/usr/local/bin/infisical agent-vault proxy --enrollment-token <enrollment-token> --domain <your-instance-url>
+ Restart=always
+
+ [Install]
+ WantedBy=multi-user.target
+ ```
+
+ Save it as `/etc/systemd/system/agent-vault-proxy.service`, then run `sudo systemctl enable --now agent-vault-proxy`.
+ </Tab>
+</Tabs>
+
+`--domain` points the proxy at your Infisical instance. It defaults to `https://app.infisical.com`, so EU Cloud and self-hosted instances have to pass it.
+
+The proxy enrolls, generates its own certificate authority, and serves on port `17323`. It keeps its state in `~/.infisical/agent-vault`, or `/etc/infisical/agent-vault` when run as root, so run it somewhere that directory persists. Running the same command again on a restart is fine. A proxy that starts with an empty state directory needs a new token: select **New Enrollment Token** on the proxy's menu.
+
+<Note>
+ Anything on a command line is readable by other users on the machine. To keep the token out of it, put `INFISICAL_AGENT_VAULT_ENROLLMENT_TOKEN=<enrollment-token>` in a file with mode `0600` and pass it with `--env-file` (Docker) or `EnvironmentFile=` (systemd), dropping `--enrollment-token` from the command. You can delete the file once the proxy has enrolled.
+</Note>
+
+Run `infisical agent-vault proxy --port 18000` to listen on a different port.
+
+## Settings
+
+Every setting lives in Infisical and reaches a running proxy on its next poll. Select **Edit Settings** on the proxy's menu.
+
+### Traffic policy
+
+Which hosts an agent may reach through this proxy.
+
+- **Allow requests to reach any host**, the default: every request goes out. Hosts an access bundle covers get its credential, and the rest go out with none.
+- **Only allow requests to reach hosts specified in access bundles**: a request to any host outside them is refused, unless the host is an exception.
+
+Use the second when the proxy sits somewhere it could reach more than you intend, such as a network with internal systems on it. Under it, a pass-through service is how one access bundle makes a host reachable without giving it a credential.
+
+A refusal isn't a refused connection. The proxy answers `CONNECT` with `200 Connection Established` and completes the TLS handshake first, then refuses the request itself:
+
+```text
+HTTP/1.1 403 Forbidden
+
+no service covers host "internal.example.com": host blocked by policy
+```
+
+Ports are part of the match. A [service's host pattern](/documentation/platform/agent-vault/access-bundles#host-patterns) that names no port covers port 443 only, so a service on `example.com` doesn't cover `example.com:8443`, and under this policy a request to the second is refused. Name the port in the pattern to cover it.
+
+<Frame>
+ <img src="/images/platform/agent-vault/proxy-create.png" alt="The Create Proxy dialog with the two traffic policy options and the poll interval" />
+</Frame>
+
+### Exceptions
+
+A comma-separated list of hosts that stay reachable under **Only allow requests to reach hosts specified in access bundles**, with no credential attached. Use it for hosts every agent needs, such as a package registry or a documentation site. Under **Allow requests to reach any host** the list changes nothing.
+
+An exception written without a port matches that host on every port, unlike a service pattern, which means port 443 when it names none.
+
+An exception isn't exempt from interception. Every HTTPS host is TLS-terminated by the proxy before any policy applies, so an exception is a host the proxy doesn't block, not a host it leaves alone. To open a host for one access bundle rather than for every agent on the proxy, add a pass-through service to that bundle instead.
+
+### Poll interval
+
+How often, in seconds, the proxy re-checks each active session with Infisical and picks up settings changes. The default is 60 and the range is 10 to 300. Every "within one poll interval" on these pages means this number.
+
+If the proxy can't reach Infisical, it keeps serving what it last knew for five poll intervals, then refuses the affected requests with a 502 until it can check again. It never forwards a request without the credential it was supposed to attach. The Proxies page marks a proxy **Unreachable** after three missed check-ins.
+
+## Certificate trust
+
+The proxy terminates TLS to attach the credential, so each agent has to trust the proxy's certificate authority. Every proxy has its own.
+
+`infisical agent-vault run` handles this. It fetches the certificate from the proxy on every run and sets `SSL_CERT_FILE`, `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, `GIT_SSL_CAINFO`, and `DENO_CERT` for the agent. On macOS it also offers to add the certificate to your login keychain, for tools such as `gh` and `docker` that read the system trust store. Pass `--no-ca-trust` to skip the step on a machine that already trusts the proxy.
+
+An agent you start without the CLI, such as a container that sets `HTTPS_PROXY` itself, needs the certificate mounted and those variables set. `http://<proxy-address>/_agent-vault/ca` returns the certificate inside a JSON object, so write the `certificate` field out on its own:
+
+```bash
+curl -s http://<proxy-address>/_agent-vault/ca | jq -r .certificate > ca.pem
+```
+
+That agent also needs `HTTPS_PROXY` and `HTTP_PROXY` set, with the session token as the password:
+
+```bash
+export HTTPS_PROXY="http://x-agent-vault:<session-token>@<proxy-address>"
+export HTTP_PROXY="$HTTPS_PROXY"
+```
+
+The session token travels to the proxy with every request, so run the proxy where only your agents can reach it: the same host, a private network, or a container network.
+
+### Pinning
+
+To make sure the agent is talking to your proxy and nothing else, pass the fingerprint from the Proxies page:
+
+```bash
+infisical agent-vault run --session-token <session-token> --proxy <proxy-address> --ca-fingerprint SHA256:9F:2C:... -- claude
+```
+
+The CLI aborts before starting the agent if the served certificate doesn't match. Pin when the agent runs on a network you don't fully control.
+
+<Frame>
+ <img src="/images/platform/agent-vault/proxies-list.png" alt="The Proxies page showing two healthy proxies with their traffic policy and certificate authority fingerprints" />
+</Frame>
+
+### APIs with a private certificate authority
+
+The proxy verifies the certificate of each API it connects to, the way any HTTPS client would. If an API you're connecting to uses a private certificate authority, the machine running the proxy has to trust that authority. The agent's machine doesn't.
+
+### Re-enrolling
+
+Selecting **New Enrollment Token** and enrolling again replaces the proxy's certificate authority. The proxy keeps its name, settings, and history. Restart any agent that was running through it, since it trusts the old certificate. Update any `--ca-fingerprint` pin, mounted copy of the certificate, or macOS keychain entry as well.
+
+## Revoking and deleting
+
+**Revoke Access** on a proxy's menu invalidates the proxy's token on its next poll. Every agent routed through it loses credentials, and the proxy process exits with a message saying its access was revoked. Use it when you believe the proxy host is compromised. To bring the proxy back, select **New Enrollment Token** and enroll again.
+
+**Delete** removes the proxy record. A running process for it exits the same way.
diff --git a/docs/documentation/platform/agent-vault/quickstart.mdx b/docs/documentation/platform/agent-vault/quickstart.mdx
new file mode 100644
index 0000000000..2abce4298f
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/quickstart.mdx
@@ -0,0 +1,162 @@
+---
+title: "Agent Vault quickstart"
+sidebarTitle: "Quickstart"
+description: "Create an access bundle, enroll a proxy, and launch an agent that makes authenticated GitHub calls with a token it never sees."
+---
+
+Every Agent Vault setup starts with the same things in Infisical: an access bundle holding a service for each API, a proxy enrolled where your agent's traffic leaves the network, and a session for the agent to run with. This quickstart walks you through creating all three and launching an agent.
+
+GitHub is this guide's running example. Any other API works the same way, and the steps are identical.
+
+## Before you begin
+
+- An Infisical organization where you're an Agent Vault admin. Organization admins can join Agent Vault as an admin themselves, without being added by someone else.
+- The [Infisical CLI](/cli/overview) installed on the host that will run the proxy and on the host that will run the agent. For this guide they can be the same machine.
+- A GitHub account, to create the token you'll broker.
+- Optional: [GitHub's `gh` CLI](https://cli.github.com/), used for the check at the end. A `curl` fallback is provided, so this isn't required.
+
+## 1. Create an access bundle
+
+First, get a GitHub personal access token to broker:
+
+1. Go to [GitHub → Settings → Developer settings → Personal access tokens → Fine-grained tokens](https://github.com/settings/personal-access-tokens).
+2. Select **Generate new token**, give it a name, set an expiration, and choose the resource owner.
+3. Leave the permissions at their defaults. The check at the end of this guide calls `GET /user`, which any valid token can reach; later, grant only what your agent actually does.
+4. Select **Generate token** and copy the `github_pat_…` value. GitHub only shows it once.
+
+Then, in Infisical, open **Agent Vault** from the product switcher and go to **Access Bundles**. Select **Create Access Bundle**, name it `code-review`, and open it.
+
+<Frame>
+ <img src="/images/platform/agent-vault/access-bundle-create.png" alt="The Create Access Bundle dialog with code-review entered as the name" />
+</Frame>
+
+Select **Add Service** and work through the steps:
+
+<Frame>
+ <img src="/images/platform/agent-vault/service-template-picker.png" alt="The Choose a template panel with GitHub among the available services" />
+</Frame>
+
+<Steps>
+ <Step title="Pick the GitHub template">
+ The template fills everything in for you: the host `api.github.com` and the header GitHub expects, `Authorization: Bearer <token>`.
+ </Step>
+ <Step title="Details">
+ Keep the service name `github` and the host pattern `api.github.com`.
+ </Step>
+ <Step title="Credential">
+ Paste your `github_pat_…` token into **Token**. It's stored encrypted and never shown again.
+ </Step>
+ <Step title="Review and create">
+ Check the host and the header, then select **Add Service**.
+ </Step>
+</Steps>
+
+<Note>
+ Not on the template list? Pick **Custom** and set the host, header name, and prefix yourself. See [Access bundles and services](/documentation/platform/agent-vault/access-bundles).
+</Note>
+
+You're an admin, so you can already create sessions with this access bundle. To let a teammate or a machine identity run agents with it, select **Manage Access** on the access bundle and grant it to them. They have to be a member of Agent Vault first, under **Access Control**.
+
+## 2. Enroll a proxy
+
+Go to **Proxies**, select **Create Proxy**, name it, and select **Create**. The dialog shows a one-time enrollment token and the command to run.
+
+<Frame>
+ <img src="/images/platform/agent-vault/proxy-enrollment-token.png" alt="The Enrollment Token dialog with the CLI command, and Docker and systemd tabs alongside it" />
+</Frame>
+
+On the host that will be the proxy:
+
+```bash
+infisical agent-vault proxy --enrollment-token <enrollment-token>
+```
+
+The proxy enrolls and listens on port `17323`. Leave it running and note this host's address; step 4 points the agent at it. Within a minute its status on the Proxies page turns to **Healthy**.
+
+<Note>
+ Fine for trying it out, but this dies with your terminal. The same dialog has Docker and systemd snippets, and [Proxies](/documentation/platform/agent-vault/proxies) covers running it for real.
+</Note>
+
+## 3. Create a session
+
+Go to **Sessions**, select **Create Session**, pick `code-review`, and select **Create Session**.
+
+<Frame>
+ <img src="/images/platform/agent-vault/session-create.png" alt="The Create Session dialog with code-review picked and a seven day expiry" />
+</Frame>
+
+The token appears once, with the command to run. Copy it now.
+
+<Frame>
+ <img src="/images/platform/agent-vault/session-created.png" alt="The Session Created dialog showing the infisical agent-vault run command with the session token" />
+</Frame>
+
+## 4. Launch your agent
+
+On the host where the agent runs, pass the token and the proxy's address. Everything after `--` is your agent's own command:
+
+```bash
+infisical agent-vault run --session-token <session-token> --proxy <proxy-host>:17323 -- claude
+```
+
+The CLI trusts the proxy's certificate for the agent and starts `claude` with its HTTP traffic routed through the proxy. Calls to `api.github.com` leave the proxy with the real token attached; everything else goes out untouched. That host needs no Infisical login: the session token is the only thing on it.
+
+<Note>
+ **On macOS the first run asks for your password once.** It adds the proxy's certificate to your login keychain, which is what lets tools like `gh` accept its certificates.
+</Note>
+
+## 5. Verify it works
+
+Each check below makes the same `GET /user` call to `api.github.com`, and the client never sends a real token. As the request passes through the proxy, the real value of your GitHub token is attached, so GitHub returns your account profile even though the token never reached the client. That is the whole point: real authenticated work without the caller ever holding the credential.
+
+<Tabs>
+ <Tab title="Ask your agent">
+ The agent you just launched is already brokering. In its session, send:
+
+ > Run `curl -sS https://api.github.com/user` and show me the output.
+
+ GitHub answers with your profile. Run the same `curl` outside the agent and GitHub answers `401`.
+ </Tab>
+ <Tab title="gh CLI">
+ Not driving an interactive agent? Run the check in place of the agent command. `gh` insists on having a token, so give it a placeholder; the proxy replaces the header on the way out:
+
+ ```bash
+ infisical agent-vault run --session-token <session-token> --proxy <proxy-host>:17323 -- \
+ sh -c 'GITHUB_TOKEN=placeholder gh api user'
+ ```
+ </Tab>
+ <Tab title="curl">
+ No `gh`? Any HTTP client works the same way:
+
+ ```bash
+ infisical agent-vault run --session-token <session-token> --proxy <proxy-host>:17323 -- curl -sS https://api.github.com/user
+ ```
+
+ The proxy logs the request as `brokered`.
+ </Tab>
+</Tabs>
+
+<Note>
+ Getting a `401`? The credential wasn't applied. Open the `code-review` access bundle and confirm a service covers `api.github.com`; if one does, the stored token is wrong. A `407` or `403` from the proxy itself means the session token was missing, revoked, or expired.
+</Note>
+
+<Note>
+ Working on your own machine and signed in with `infisical login`? Skip the Sessions page: `infisical agent-vault run --access-bundle code-review --proxy <proxy-host>:17323 -- claude` creates a session for you and revokes it when the agent exits. For an agent that runs unattended, run it as a machine identity instead — see [Sessions](/documentation/platform/agent-vault/sessions#creating-a-session).
+</Note>
+
+## Next steps
+
+<CardGroup cols={2}>
+ <Card title="Access bundles" icon="box" href="/documentation/platform/agent-vault/access-bundles">
+ Add more services, choose credential types, and grant access bundles to your team.
+ </Card>
+ <Card title="Sessions" icon="ticket" href="/documentation/platform/agent-vault/sessions">
+ Choose how long a session lives and revoke one while an agent is running.
+ </Card>
+ <Card title="Proxies" icon="route" href="/documentation/platform/agent-vault/proxies">
+ Run the proxy for real, decide what happens to other hosts, and pin its certificate.
+ </Card>
+ <Card title="CLI reference" icon="terminal" href="/cli/commands/agent-vault">
+ Every flag of `infisical agent-vault proxy` and `infisical agent-vault run`.
+ </Card>
+</CardGroup>
diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdx
new file mode 100644
index 0000000000..a1211562c6
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/sessions.mdx
@@ -0,0 +1,76 @@
+---
+title: "Sessions"
+description: "Create the session an agent runs with, choose how long it lives, and revoke it while the agent is running."
+---
+
+A session is the token an agent runs with. It carries one access bundle and an expiry. On every request the proxy uses it to decide which services the agent may use right now, and applies their credentials on the way out.
+
+## Creating a session
+
+Anyone granted at least one access bundle can create a session. Admins can create one with any access bundle.
+
+<Tabs>
+ <Tab title="Dashboard">
+ Go to **Sessions** and select **Create Session**. Pick the access bundle the agent needs, set how long the session lives, and select **Create Session**. The token is shown once, with the command to run:
+
+ <Frame>
+ <img src="/images/platform/agent-vault/session-create.png" alt="The Create Session dialog with an access bundle picked and a seven day expiry" />
+ </Frame>
+
+ ```bash
+ infisical agent-vault run --session-token <session-token> --proxy <proxy-address> -- claude
+ ```
+
+ Copy it now. The dialog can't be reopened.
+
+ <Frame>
+ <img src="/images/platform/agent-vault/session-created.png" alt="The Session Created dialog showing the run command with the session token shown once" />
+ </Frame>
+
+ This is the way to start an agent on a machine that has no Infisical login. The token is the only thing you hand over.
+ </Tab>
+ <Tab title="CLI">
+ `infisical agent-vault run` creates a session for you when you name the access bundle:
+
+ ```bash
+ infisical agent-vault run --access-bundle code-review --proxy <proxy-address> -- claude
+ ```
+
+ The CLI creates the session as a machine identity when you pass `--client-id` and `--client-secret` (or their environment variables), and as your login otherwise. It revokes the session when the agent exits unless you pass `--keep-session`.
+
+ For an agent that runs unattended, set the machine identity up first: create it with Universal Auth, add it under **Access Control**, and grant it the access bundle.
+ </Tab>
+</Tabs>
+
+### How long a session lives
+
+Pick how long the session should last. **Never** keeps it working until someone revokes it, so revoke it once the agent that used it has finished.
+
+On the CLI this is [`--ttl`](/cli/commands/agent-vault#ttl), which takes a duration such as `30m`, `8h` or `7d`, or `never`.
+
+## What a running agent can reach
+
+The access bundle on a session is fixed when the session is created. Whether the agent still gets its credentials is re-checked against the current grants on every proxy poll, 60 seconds by default:
+
+- Remove someone from the access bundle, and every session they created with it gets no credentials.
+- Demote an admin to member, and their sessions over access bundles they weren't explicitly granted get no credentials.
+- Delete an access bundle, and every session that carried it gets no credentials. The session still lists the access bundle's name so you can see what it was.
+- Remove them from Agent Vault, and the proxy refuses every request on their sessions. Removal also takes away a member's access bundle grants, so adding them back leaves their sessions without credentials until you grant the access bundle again. An admin reaches every access bundle, so their sessions work as soon as they're back.
+
+In the first three cases the agent's requests still go out, and what it can reach without a credential is decided by the proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy). Nothing on the agent's machine needs to be restarted for any of this.
+
+## Revoking and expiry
+
+Select the session's menu on the Sessions page and choose **Revoke Session**. The proxy stops applying credentials for it on its next poll. Revoking is permanent.
+
+An expired session stops the same way. The Sessions page shows sessions as **Active**, **Revoked**, or **Expired**, and keeps expired and revoked sessions for 30 days so you can see what an agent could reach.
+
+<Frame>
+ <img src="/images/platform/agent-vault/sessions-list.png" alt="The Sessions page listing active, revoked, and expired sessions with their access bundle and expiry" />
+</Frame>
+
+Admins can switch the list between **All Sessions** and **My Sessions**. Members see only their own.
+
+## Audit trail
+
+Creating and revoking a session each write an audit event, as does every change to an access bundle, service, or proxy. Open **Audit Logs** in Agent Vault, or scope an [audit log stream](/documentation/platform/audit-log-streams/audit-log-streams) to the Agent Vault product.
diff --git a/docs/images/platform/agent-vault/access-bundle-create.png b/docs/images/platform/agent-vault/access-bundle-create.png
new file mode 100644
index 0000000000..686cecfede
Binary files /dev/null and b/docs/images/platform/agent-vault/access-bundle-create.png differ
diff --git a/docs/images/platform/agent-vault/access-bundle-services.png b/docs/images/platform/agent-vault/access-bundle-services.png
new file mode 100644
index 0000000000..ea638eec5b
Binary files /dev/null and b/docs/images/platform/agent-vault/access-bundle-services.png differ
diff --git a/docs/images/platform/agent-vault/access-bundles-list.png b/docs/images/platform/agent-vault/access-bundles-list.png
new file mode 100644
index 0000000000..fdfbde64f8
Binary files /dev/null and b/docs/images/platform/agent-vault/access-bundles-list.png differ
diff --git a/docs/images/platform/agent-vault/proxies-list.png b/docs/images/platform/agent-vault/proxies-list.png
new file mode 100644
index 0000000000..6b8d4a021e
Binary files /dev/null and b/docs/images/platform/agent-vault/proxies-list.png differ
diff --git a/docs/images/platform/agent-vault/proxy-create.png b/docs/images/platform/agent-vault/proxy-create.png
new file mode 100644
index 0000000000..cea85575d4
Binary files /dev/null and b/docs/images/platform/agent-vault/proxy-create.png differ
diff --git a/docs/images/platform/agent-vault/proxy-enrollment-token.png b/docs/images/platform/agent-vault/proxy-enrollment-token.png
new file mode 100644
index 0000000000..d341f51ce0
Binary files /dev/null and b/docs/images/platform/agent-vault/proxy-enrollment-token.png differ
diff --git a/docs/images/platform/agent-vault/service-template-picker.png b/docs/images/platform/agent-vault/service-template-picker.png
new file mode 100644
index 0000000000..d90ea22cde
Binary files /dev/null and b/docs/images/platform/agent-vault/service-template-picker.png differ
diff --git a/docs/images/platform/agent-vault/session-create.png b/docs/images/platform/agent-vault/session-create.png
new file mode 100644
index 0000000000..4c79ae5983
Binary files /dev/null and b/docs/images/platform/agent-vault/session-create.png differ
diff --git a/docs/images/platform/agent-vault/session-created.png b/docs/images/platform/agent-vault/session-created.png
new file mode 100644
index 0000000000..29b16f7a51
Binary files /dev/null and b/docs/images/platform/agent-vault/session-created.png differ
diff --git a/docs/images/platform/agent-vault/sessions-list.png b/docs/images/platform/agent-vault/sessions-list.png
new file mode 100644
index 0000000000..68b12d2b4c
Binary files /dev/null and b/docs/images/platform/agent-vault/sessions-list.png differ
diff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.md
index caab04aa8e..525d1d1608 100644
--- a/frontend/CLAUDE.md
+++ b/frontend/CLAUDE.md
@@ -80,6 +80,12 @@ Tailwind CSS v4 with PostCSS. Dark theme configured via CSS custom properties in
9 layout components in `src/layouts/` — `AdminLayout`, `OrganizationLayout`, `SecretManagerLayout`, `PkiManagerLayout`, `KmsLayout`, `PamLayout`, etc. Layouts handle sidebar navigation and page chrome for their product area.
+### Org-scoped products
+
+PAM and Agent Vault live at `/organizations/$orgId/<slug>` over a single implicit project, so their URLs carry no `$projectId`. Their layout's `beforeLoad` publishes `implicitProjectId` and `implicitProductType` into route context, and `useImplicitProjectId()` / `useImplicitProduct()` read them back off the matched routes. **Anything that decides whether a `useProject()` caller renders must use `useImplicitProduct()`, never the pathname.** The router changes location before it swaps matches, so a pathname gate mounts a frame early on the way in and unmounts a frame late on the way out, leaving the component asking for a project the router no longer resolves — which throws into `ErrorPage`. Reading the matches keeps these products in step with `useParams`, which is match-derived and is what every other product's gate already uses. The gates that matter today are `OrgSidebar`'s `isInsideProject`, the `ProjectSelect` wrapper, and `OrganizationCommandMenu` in `RootCommandMenu.tsx`, which had exactly this bug when it arrived from main with a pathname check; `getOrgScopedProductFromPath` remains correct for the cosmetic uses behind no `useProject` (navbar scope, `useScopeVariant`, `TypeSelect`).
+
+A new org-scoped product therefore needs: a `<product>ProjectId` on the `Organization` type, an entry in `ORG_SCOPED_PRODUCT_TYPES` and `getOrgScopedProductFromPath` (`helpers/project.ts`), and a layout `beforeLoad` that bootstraps the id, patches it into the cached org, and returns both `implicitProjectId` and `implicitProductType` (see `pages/agent-vault/layout.tsx`). Use `isOrgScopedProduct(type)` rather than adding another pathname check; the sidebar, navbar, project switcher and nav links all key off it.
+
## Conventions
- ESLint flat config (ESLint 9+) with airbnb-typescript + prettier. Double quotes enforced.
diff --git a/frontend/public/images/integrations/OpenAIWhite.png b/frontend/public/images/integrations/OpenAIWhite.png
new file mode 100644
index 0000000000..55b7a8ea9c
Binary files /dev/null and b/frontend/public/images/integrations/OpenAIWhite.png differ
diff --git a/frontend/src/components/agent-vault/AccessBundleFormDialog.tsx b/frontend/src/components/agent-vault/AccessBundleFormDialog.tsx
new file mode 100644
index 0000000000..243c7d9a5a
--- /dev/null
+++ b/frontend/src/components/agent-vault/AccessBundleFormDialog.tsx
@@ -0,0 +1,143 @@
+import { useEffect } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ TextArea
+} from "@app/components/v3";
+import {
+ useCreateAgentVaultAccessBundle,
+ useUpdateAgentVaultAccessBundle
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultAccessBundle } from "@app/hooks/api/agentVault/types";
+import { slugSchema } from "@app/lib/schemas";
+
+const schema = z.object({
+ name: slugSchema({ max: 64, field: "Name" }),
+ description: z.string().trim().max(256).optional()
+});
+
+type FormData = z.infer<typeof schema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ accessBundle?: TAgentVaultAccessBundle;
+};
+
+export const AccessBundleFormDialog = ({ isOpen, onOpenChange, accessBundle }: Props) => {
+ const createAccessBundle = useCreateAgentVaultAccessBundle();
+ const updateAccessBundle = useUpdateAgentVaultAccessBundle();
+ const isUpdate = Boolean(accessBundle);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = useForm<FormData>({ resolver: zodResolver(schema) });
+
+ useEffect(() => {
+ if (isOpen) {
+ reset({ name: accessBundle?.name ?? "", description: accessBundle?.description ?? "" });
+ }
+ }, [isOpen, accessBundle, reset]);
+
+ const onSubmit = async ({ name, description }: FormData) => {
+ try {
+ if (accessBundle) {
+ await updateAccessBundle.mutateAsync({
+ accessBundleId: accessBundle.id,
+ name,
+ description: description || null
+ });
+ } else {
+ await createAccessBundle.mutateAsync({ name, description: description || undefined });
+ }
+
+ createNotification({
+ text: `Access bundle "${name}" ${isUpdate ? "updated" : "created"}`,
+ type: "success"
+ });
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{isUpdate ? "Edit Access Bundle" : "Create Access Bundle"}</DialogTitle>
+ <DialogDescription>
+ An access bundle groups the services an agent may use.
+ </DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ placeholder="on-call-infrastructure"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldDescription>Lowercase letters, numbers and hyphens.</FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="description"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ rows={2}
+ placeholder="Paging, metrics, issue tracking"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="av" isPending={isSubmitting}>
+ {isUpdate ? "Save" : "Create Access Bundle"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/components/agent-vault/AddMemberDialog.tsx b/frontend/src/components/agent-vault/AddMemberDialog.tsx
new file mode 100644
index 0000000000..7bdd7ad025
--- /dev/null
+++ b/frontend/src/components/agent-vault/AddMemberDialog.tsx
@@ -0,0 +1,222 @@
+import { useEffect, useMemo, useState } from "react";
+import { BotIcon, UserIcon, UsersIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Combobox,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel
+} from "@app/components/v3";
+import {
+ useAddAgentVaultAccessBundleMembers,
+ useListAgentVaultProductGroupMembers,
+ useListAgentVaultProductIdentityMembers,
+ useListAgentVaultProductUserMembers
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultMember } from "@app/hooks/api/agentVault/types";
+
+import { PendingInvitationBadge } from "./PendingInvitationBadge";
+
+enum MemberKind {
+ User = "user",
+ Identity = "identity",
+ Group = "group"
+}
+
+const KIND_ICON: Record<MemberKind, typeof UserIcon> = {
+ [MemberKind.User]: UserIcon,
+ [MemberKind.Identity]: BotIcon,
+ [MemberKind.Group]: UsersIcon
+};
+
+type Option = {
+ kind: MemberKind;
+ id: string;
+ label: string;
+ subtitle: string;
+ isPendingInvitation?: boolean;
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ accessBundleId: string;
+ members: TAgentVaultMember[];
+};
+
+export const AddMemberDialog = ({ isOpen, onOpenChange, accessBundleId, members }: Props) => {
+ const addMembers = useAddAgentVaultAccessBundleMembers();
+
+ const [selected, setSelected] = useState<Option[]>([]);
+
+ useEffect(() => {
+ if (isOpen) setSelected([]);
+ }, [isOpen]);
+
+ const { data: users } = useListAgentVaultProductUserMembers(isOpen);
+ const { data: groupMemberships } = useListAgentVaultProductGroupMembers(isOpen);
+ const { data: identities } = useListAgentVaultProductIdentityMembers(isOpen);
+
+ const grantedIds = useMemo(
+ () =>
+ new Set(members.map((member) => member.userId ?? member.identityId ?? member.groupId ?? "")),
+ [members]
+ );
+
+ const options = useMemo<Option[]>(() => {
+ const userOptions = (users ?? [])
+ .filter((member) => member.userId)
+ .map((member) => {
+ const fullName = [member.firstName, member.lastName].filter(Boolean).join(" ");
+ return {
+ kind: MemberKind.User,
+ id: member.userId as string,
+ label: fullName || member.username || member.email || "",
+ subtitle: member.email || member.username,
+ isPendingInvitation: member.isOrgMembershipPending
+ };
+ })
+ .filter((option) => !grantedIds.has(option.id));
+
+ const groupOptions = (groupMemberships ?? [])
+ .filter((member) => member.groupId)
+ .map((member) => ({
+ kind: MemberKind.Group,
+ id: member.groupId as string,
+ label: member.name,
+ subtitle: "Group"
+ }))
+ .filter((option) => !grantedIds.has(option.id));
+
+ const identityOptions = (identities ?? [])
+ .filter((member) => member.identityId)
+ .map((member) => ({
+ kind: MemberKind.Identity,
+ id: member.identityId as string,
+ label: member.name,
+ subtitle: "Machine Identity"
+ }))
+ .filter((option) => !grantedIds.has(option.id))
+ .sort((a, b) => a.label.localeCompare(b.label));
+
+ return [...userOptions, ...groupOptions, ...identityOptions];
+ }, [users, groupMemberships, identities, grantedIds]);
+
+ const handleAdd = async () => {
+ try {
+ if (!selected.length) return;
+
+ const idsOfKind = (kind: MemberKind) =>
+ selected.filter((option) => option.kind === kind).map((option) => option.id);
+
+ const { members: granted, skipped } = await addMembers.mutateAsync({
+ accessBundleId,
+ userIds: idsOfKind(MemberKind.User),
+ identityIds: idsOfKind(MemberKind.Identity),
+ groupIds: idsOfKind(MemberKind.Group)
+ });
+
+ if (!granted.length) {
+ createNotification({ text: "They already had this access bundle", type: "info" });
+ } else {
+ const grantedText =
+ granted.length === 1 && selected.length === 1
+ ? `Access bundle granted to "${selected[0].label}"`
+ : `Access bundle granted to ${granted.length} members`;
+ createNotification({
+ text: skipped.length ? `${grantedText}. ${skipped.length} already had it.` : grantedText,
+ type: "success"
+ });
+ }
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Grant Access</DialogTitle>
+ <DialogDescription>
+ Whoever holds this bundle can mint a session over it. They must already be a member of
+ Agent Vault.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Field>
+ <FieldLabel htmlFor="agent-vault-grant-to">Grant To</FieldLabel>
+ <FieldContent>
+ <Combobox
+ id="agent-vault-grant-to"
+ multiple
+ options={options}
+ value={selected}
+ getOptionValue={(option) => `${option.kind}:${option.id}`}
+ getOptionLabel={(option) => option.label}
+ getOptionKeywords={(option) => [option.subtitle]}
+ placeholder="Pick users, groups, or machine identities..."
+ searchPlaceholder="Pick users, groups, or machine identities..."
+ searchAriaLabel="Search users, groups, and machine identities"
+ emptyMessage={
+ options.length
+ ? "No matches."
+ : "Nobody left to grant. Add them under Access Control first."
+ }
+ clearAriaLabel="Clear all grantees"
+ modal
+ onValueChange={(next) => setSelected([...next])}
+ renderValue={(option) => {
+ const Icon = KIND_ICON[option.kind];
+ return (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <Icon className="size-3.5 shrink-0 text-muted" />
+ <span className="truncate">{option.label}</span>
+ </span>
+ );
+ }}
+ renderOption={(option) => {
+ const Icon = KIND_ICON[option.kind];
+ return (
+ <span className="flex min-w-0 items-center gap-2.5">
+ <Icon className="size-4 shrink-0 text-muted" />
+ <span className="min-w-0">
+ <span className="block truncate">{option.label}</span>
+ <span className="block truncate text-xs leading-4 text-muted">
+ {option.subtitle}
+ </span>
+ </span>
+ <PendingInvitationBadge isPending={Boolean(option.isPendingInvitation)} />
+ </span>
+ );
+ }}
+ />
+ </FieldContent>
+ </Field>
+
+ <DialogFooter>
+ <Button
+ variant="av"
+ isDisabled={!selected.length}
+ isPending={addMembers.isPending}
+ onClick={async () => handleAdd()}
+ >
+ Grant Access
+ </Button>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/components/agent-vault/ManageAccessSheet.tsx b/frontend/src/components/agent-vault/ManageAccessSheet.tsx
new file mode 100644
index 0000000000..0e796b31a8
--- /dev/null
+++ b/frontend/src/components/agent-vault/ManageAccessSheet.tsx
@@ -0,0 +1,197 @@
+import { useState } from "react";
+import { format } from "date-fns";
+import { BanIcon, MoreHorizontalIcon, UserPlusIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ useGetAgentVaultAccessBundle,
+ useRemoveAgentVaultAccessBundleMember
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultMember } from "@app/hooks/api/agentVault/types";
+
+import { AddMemberDialog } from "./AddMemberDialog";
+import { memberDisplayName, MemberName } from "./MemberName";
+
+type Props = {
+ accessBundle: { id: string; name: string } | null;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {
+ const [isAddOpen, setIsAddOpen] = useState(false);
+ const [memberToRemove, setMemberToRemove] = useState<TAgentVaultMember | null>(null);
+
+ const { data: bundleDetails, isPending } = useGetAgentVaultAccessBundle(accessBundle?.id ?? "");
+ const removeMember = useRemoveAgentVaultAccessBundleMember();
+
+ const members = bundleDetails?.members ?? [];
+ const memberToRemoveName = memberToRemove ? memberDisplayName(memberToRemove) : "";
+
+ const handleRemove = async () => {
+ try {
+ if (!accessBundle || !memberToRemove) return;
+
+ await removeMember.mutateAsync({
+ accessBundleId: accessBundle.id,
+ memberId: memberToRemove.id
+ });
+ createNotification({
+ text: `Access bundle revoked from "${memberToRemoveName}"`,
+ type: "success"
+ });
+ setMemberToRemove(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Sheet open={Boolean(accessBundle)} onOpenChange={onOpenChange}>
+ <SheetContent className="sm:max-w-[640px]">
+ <SheetHeader>
+ <SheetTitle>Manage Access</SheetTitle>
+ <SheetDescription>Who can mint a session over {accessBundle?.name}.</SheetDescription>
+ </SheetHeader>
+
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <div className="flex items-center justify-end">
+ <Button size="sm" variant="av" onClick={() => setIsAddOpen(true)}>
+ <UserPlusIcon />
+ Grant Access
+ </Button>
+ </div>
+
+ {isPending && <Skeleton className="h-16 w-full" />}
+
+ {!isPending && members.length === 0 && (
+ <Empty className="flex-none border">
+ <EmptyHeader>
+ <EmptyTitle>No members yet</EmptyTitle>
+ <EmptyDescription>
+ Grant this bundle to a user, machine identity or group.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+
+ {!isPending && members.length > 0 && (
+ <Table className="overflow-hidden rounded-md border border-border">
+ <TableHeader>
+ <TableRow>
+ <TableHead>Member</TableHead>
+ <TableHead>Granted</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {members.map((member) => (
+ <TableRow key={member.id}>
+ <TableCell>
+ <MemberName member={member} />
+ </TableCell>
+ <TableCell>{format(new Date(member.createdAt), "MMM d, yyyy")}</TableCell>
+ <TableCell variant="action">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label={`Actions for ${memberDisplayName(member)}`}
+ >
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setMemberToRemove(member)}
+ >
+ <BanIcon />
+ Revoke Access
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </div>
+
+ {accessBundle && (
+ <AddMemberDialog
+ isOpen={isAddOpen}
+ onOpenChange={setIsAddOpen}
+ accessBundleId={accessBundle.id}
+ members={members}
+ />
+ )}
+
+ <AlertDialog
+ open={Boolean(memberToRemove)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen && !removeMember.isPending) setMemberToRemove(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ Revoke Access for &quot;{memberToRemoveName}&quot;
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ They lose this bundle, and any live session they hold stops reaching its hosts at
+ the next proxy poll.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel isDisabled={removeMember.isPending}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ isPending={removeMember.isPending}
+ onClick={async (event) => {
+ event.preventDefault();
+ await handleRemove();
+ }}
+ >
+ Revoke Access
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/components/agent-vault/MemberName.tsx b/frontend/src/components/agent-vault/MemberName.tsx
new file mode 100644
index 0000000000..dbffba19c2
--- /dev/null
+++ b/frontend/src/components/agent-vault/MemberName.tsx
@@ -0,0 +1,38 @@
+import { BotIcon, UserIcon, UsersIcon } from "lucide-react";
+
+import { TAgentVaultMember } from "@app/hooks/api/agentVault/types";
+
+export const memberDisplayName = (member: TAgentVaultMember) => {
+ if (member.group) return member.group.name;
+ if (member.identity) return member.identity.name;
+ if (!member.user) return "Unknown";
+
+ const fullName = [member.user.firstName, member.user.lastName].filter(Boolean).join(" ");
+ return fullName || member.user.username || member.user.email || "Unknown";
+};
+
+const memberKind = (member: TAgentVaultMember) => {
+ if (member.groupId) return { label: "Group", icon: UsersIcon };
+ if (member.identityId) return { label: "Machine Identity", icon: BotIcon };
+ return { label: "User", icon: UserIcon };
+};
+
+const memberSubtitle = (member: TAgentVaultMember, kindLabel: string) => {
+ if (member.user) return member.user.email || member.user.username;
+ return kindLabel;
+};
+
+export const MemberName = ({ member }: { member: TAgentVaultMember }) => {
+ const { label, icon: Icon } = memberKind(member);
+
+ return (
+ <div className="flex min-w-0 items-center gap-2.5">
+ <Icon className="size-4 shrink-0 text-muted" />
+ <span className="sr-only">{label}</span>
+ <div className="min-w-0">
+ <div className="truncate">{memberDisplayName(member)}</div>
+ <div className="truncate text-xs leading-4 text-muted">{memberSubtitle(member, label)}</div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/agent-vault/PendingInvitationBadge.tsx b/frontend/src/components/agent-vault/PendingInvitationBadge.tsx
new file mode 100644
index 0000000000..4dacd410dc
--- /dev/null
+++ b/frontend/src/components/agent-vault/PendingInvitationBadge.tsx
@@ -0,0 +1,19 @@
+import { MailIcon } from "lucide-react";
+
+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+
+export const PendingInvitationBadge = ({ isPending }: { isPending: boolean }) => {
+ if (!isPending) return null;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="info">
+ <MailIcon />
+ Pending Invitation
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>Access begins once they accept their organization invitation.</TooltipContent>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/components/agent-vault/ProductRoleBadge.tsx b/frontend/src/components/agent-vault/ProductRoleBadge.tsx
new file mode 100644
index 0000000000..3b6e465d3f
--- /dev/null
+++ b/frontend/src/components/agent-vault/ProductRoleBadge.tsx
@@ -0,0 +1,16 @@
+import { ShieldIcon, UserIcon } from "lucide-react";
+
+import { Badge } from "@app/components/v3";
+import { formatProjectRoleName } from "@app/helpers/roles";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+export const ProductRoleBadge = ({ role }: { role: string }) => {
+ const isAdmin = role === ProjectMembershipRole.Admin;
+
+ return (
+ <Badge variant={isAdmin ? "av" : "neutral"}>
+ {isAdmin ? <ShieldIcon /> : <UserIcon />}
+ {formatProjectRoleName(role)}
+ </Badge>
+ );
+};
diff --git a/frontend/src/components/agent-vault/ServiceIconStack.tsx b/frontend/src/components/agent-vault/ServiceIconStack.tsx
new file mode 100644
index 0000000000..6b92df635c
--- /dev/null
+++ b/frontend/src/components/agent-vault/ServiceIconStack.tsx
@@ -0,0 +1,137 @@
+import { ComponentPropsWithoutRef, forwardRef, ReactNode, useMemo, useState } from "react";
+import { GlobeIcon } from "lucide-react";
+
+import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import { findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";
+
+type TServiceIcon = {
+ label: string;
+ image?: string;
+};
+
+const labelOf = (pattern: string) => {
+ const trimmed = pattern.trim();
+ // A bracketed IPv6 host is full of colons, so only the one after the bracket separates the port.
+ const host = trimmed.startsWith("[")
+ ? trimmed.slice(0, trimmed.indexOf("]") + 1)
+ : trimmed.split(":")[0];
+ return host || trimmed;
+};
+
+const iconFromHostPattern = (hostPattern: string): TServiceIcon => {
+ const template = findTemplateForHostPattern(hostPattern);
+ return { label: template?.name ?? labelOf(hostPattern), image: template?.image };
+};
+
+const iconsFromHostPatterns = (hostPatterns: string[]): TServiceIcon[] => {
+ const byLabel = new Map<string, TServiceIcon>();
+
+ hostPatterns.forEach((pattern) => {
+ const icon = iconFromHostPattern(pattern);
+ if (icon.label && !byLabel.has(icon.label)) byLabel.set(icon.label, icon);
+ });
+
+ return [...byLabel.values()];
+};
+
+const chipClassName =
+ "flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-border text-foreground/60";
+
+// The ring paints in the table surface color, following the row hover, so each overlapping chip
+// reads as its own layer instead of a dark outline.
+const stackedChipClassName =
+ "ring-2 ring-container transition-shadow duration-75 [tr:hover_&]:ring-container-hover";
+
+type TServiceChipProps = ComponentPropsWithoutRef<"div"> & { icon: TServiceIcon };
+
+const ServiceChip = forwardRef<HTMLDivElement, TServiceChipProps>(
+ ({ icon, className, ...props }, ref) => {
+ const [hasImageError, setHasImageError] = useState(false);
+
+ return (
+ <div ref={ref} className={cn(chipClassName, className)} {...props}>
+ {icon.image && !hasImageError ? (
+ <img
+ src={`/images/integrations/${icon.image}`}
+ alt=""
+ className="size-full object-contain p-1"
+ onError={() => setHasImageError(true)}
+ />
+ ) : (
+ <GlobeIcon className="size-3.5" />
+ )}
+ </div>
+ );
+ }
+);
+
+ServiceChip.displayName = "ServiceChip";
+
+export const ServiceIcon = ({
+ hostPattern,
+ className
+}: {
+ hostPattern: string;
+ className?: string;
+}) => {
+ const icon = useMemo(() => iconFromHostPattern(hostPattern), [hostPattern]);
+ return <ServiceChip icon={icon} className={className} />;
+};
+
+type Props = {
+ hostPatterns: string[];
+ maxVisible?: number;
+ emptyPlaceholder?: ReactNode;
+ className?: string;
+};
+
+export const ServiceIconStack = ({
+ hostPatterns,
+ maxVisible = 4,
+ emptyPlaceholder = <span className="text-muted">&mdash;</span>,
+ className
+}: Props) => {
+ const icons = useMemo(() => iconsFromHostPatterns(hostPatterns), [hostPatterns]);
+
+ if (icons.length === 0) return emptyPlaceholder;
+
+ const visible = icons.slice(0, maxVisible);
+ const hidden = icons.slice(maxVisible);
+
+ return (
+ // The leftmost chip has to paint on top, and flex-row-reverse cannot do it: reversing the
+ // direction moves a chip visually and its paint order follows, so the right edge wins either
+ // way. `isolate` confines these depths to the stack.
+ <div className={cn("isolate flex items-center -space-x-1.5", className)}>
+ {visible.map((icon, index) => (
+ <Tooltip key={icon.label}>
+ <TooltipTrigger asChild>
+ <ServiceChip
+ icon={icon}
+ className={cn(stackedChipClassName, "relative")}
+ style={{ zIndex: visible.length - index }}
+ />
+ </TooltipTrigger>
+ <TooltipContent>{icon.label}</TooltipContent>
+ </Tooltip>
+ ))}
+ {hidden.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className={cn(chipClassName, stackedChipClassName, "text-[10px] font-medium")}>
+ +{hidden.length}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="flex flex-col">
+ {hidden.map((icon) => (
+ <span key={icon.label}>{icon.label}</span>
+ ))}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
new file mode 100644
index 0000000000..4f9ce8b954
--- /dev/null
+++ b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
@@ -0,0 +1,152 @@
+import { useMemo, useState } from "react";
+import { GlobeIcon, PlusIcon, SearchIcon } from "lucide-react";
+
+import { InputGroup, InputGroupAddon, InputGroupInput } from "@app/components/v3";
+import {
+ AGENT_VAULT_TEMPLATES,
+ AgentVaultTemplate,
+ AgentVaultTemplateCategory,
+ POPULAR_AGENT_VAULT_TEMPLATES
+} from "@app/helpers/agentVaultTemplates";
+
+const TemplateCard = ({
+ template,
+ onSelect
+}: {
+ template: AgentVaultTemplate;
+ onSelect: (template: AgentVaultTemplate) => void;
+}) => {
+ const [hasImageError, setHasImageError] = useState(false);
+
+ return (
+ <button
+ type="button"
+ onClick={() => onSelect(template)}
+ className="group flex cursor-pointer flex-col gap-3 rounded-md border border-border bg-card p-4 text-left transition-colors hover:border-mineshaft-500 hover:bg-mineshaft-700/50"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex size-9 items-center justify-center rounded-md bg-mineshaft-700">
+ {hasImageError ? (
+ <GlobeIcon className="size-5 text-bunker-300" />
+ ) : (
+ <img
+ src={`/images/integrations/${template.image}`}
+ alt={`${template.name} logo`}
+ className="size-6 object-contain"
+ onError={() => setHasImageError(true)}
+ />
+ )}
+ </div>
+ <span className="text-[10px] font-medium tracking-wider text-muted uppercase">
+ {template.category}
+ </span>
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="text-sm font-semibold text-foreground">{template.name}</p>
+ <p className="text-xs leading-relaxed text-muted">{template.description}</p>
+ </div>
+ </button>
+ );
+};
+
+const CustomCard = ({ onSelect }: { onSelect: () => void }) => (
+ <button
+ type="button"
+ onClick={onSelect}
+ className="group flex cursor-pointer flex-col gap-3 rounded-md border border-dashed border-mineshaft-500 bg-card p-4 text-left transition-colors hover:border-mineshaft-400 hover:bg-mineshaft-700/50"
+ >
+ <div className="flex items-start gap-2">
+ <div className="flex size-9 items-center justify-center rounded-md bg-mineshaft-700">
+ <PlusIcon className="size-5 text-bunker-300" />
+ </div>
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="text-sm font-semibold text-foreground">Custom</p>
+ <p className="text-xs leading-relaxed text-muted">Name the hosts yourself.</p>
+ </div>
+ </button>
+);
+
+const Grid = ({ children }: { children: React.ReactNode }) => (
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">{children}</div>
+);
+
+const SectionLabel = ({ children }: { children: React.ReactNode }) => (
+ <p className="mb-3 text-[11px] font-medium tracking-wider text-muted uppercase">{children}</p>
+);
+
+type Props = {
+ onSelect: (template: AgentVaultTemplate | null) => void;
+};
+
+export const ServiceTemplateSelect = ({ onSelect }: Props) => {
+ const [search, setSearch] = useState("");
+
+ const filtered = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ if (!term) return null;
+
+ return AGENT_VAULT_TEMPLATES.filter((template) =>
+ [template.name, template.category, template.key, ...(template.aliases ?? [])].some((value) =>
+ value.toLowerCase().includes(term)
+ )
+ );
+ }, [search]);
+
+ const popular = AGENT_VAULT_TEMPLATES.filter((template) =>
+ POPULAR_AGENT_VAULT_TEMPLATES.includes(template.key)
+ );
+
+ return (
+ <div className="flex flex-col gap-6">
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search templates — OpenAI, Anthropic, Slack, GitHub..."
+ />
+ </InputGroup>
+
+ {filtered ? (
+ <Grid>
+ <CustomCard onSelect={() => onSelect(null)} />
+ {filtered.map((template) => (
+ <TemplateCard key={template.key} template={template} onSelect={onSelect} />
+ ))}
+ </Grid>
+ ) : (
+ <>
+ <div>
+ <SectionLabel>Popular</SectionLabel>
+ <Grid>
+ <CustomCard onSelect={() => onSelect(null)} />
+ {popular.map((template) => (
+ <TemplateCard key={template.key} template={template} onSelect={onSelect} />
+ ))}
+ </Grid>
+ </div>
+ {Object.values(AgentVaultTemplateCategory).map((category) => {
+ const templates = AGENT_VAULT_TEMPLATES.filter(
+ (template) => template.category === category
+ );
+ if (templates.length === 0) return null;
+
+ return (
+ <div key={category}>
+ <SectionLabel>{category}</SectionLabel>
+ <Grid>
+ {templates.map((template) => (
+ <TemplateCard key={template.key} template={template} onSelect={onSelect} />
+ ))}
+ </Grid>
+ </div>
+ );
+ })}
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
new file mode 100644
index 0000000000..069b42dd73
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
@@ -0,0 +1,238 @@
+import { useEffect, useState } from "react";
+import { Controller, ControllerRenderProps, useFormContext } from "react-hook-form";
+import { EyeIcon, EyeOffIcon } from "lucide-react";
+
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ CodeBlock,
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ Input,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+
+import { CREDENTIAL_LABELS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";
+
+export const credentialPreview = (
+ form: {
+ credentialType: AgentVaultCredentialType;
+ headerName?: string;
+ headerPrefix?: string;
+ },
+ secret = "••••••••"
+): string | null => {
+ if (form.credentialType === AgentVaultCredentialType.Passthrough) return null;
+ if (form.credentialType === AgentVaultCredentialType.Basic)
+ return `Authorization: Basic ${secret}`;
+ const prefix = form.headerPrefix ? `${form.headerPrefix} ` : "";
+ return `${form.headerName || "Authorization"}: ${prefix}${secret}`;
+};
+
+type SecretName = "secret" | "username";
+
+const SecretInput = <TName extends SecretName>({
+ field,
+ label,
+ placeholder,
+ isError,
+ isUntouched
+}: {
+ field: ControllerRenderProps<TServiceForm, TName>;
+ label: string;
+ placeholder: string;
+ isError: boolean;
+ isUntouched: boolean;
+}) => {
+ const [isVisible, setIsVisible] = useState(false);
+
+ return (
+ <InputGroup>
+ <InputGroupInput
+ {...field}
+ type={isVisible ? "text" : "password"}
+ // Selected rather than cleared, so focusing the field and moving on cannot remove a credential.
+ onFocus={(event) => {
+ if (isUntouched) event.target.select();
+ }}
+ placeholder={placeholder}
+ isError={isError}
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ // A stored credential is never returned, so until it is replaced there is nothing to reveal.
+ isDisabled={isUntouched}
+ aria-label={`${isVisible ? "Hide" : "Show"} ${label.toLowerCase()}`}
+ onClick={() => setIsVisible((prev) => !prev)}
+ >
+ {isVisible ? <EyeOffIcon /> : <EyeIcon />}
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ );
+};
+
+type Props = {
+ storedType?: AgentVaultCredentialType;
+};
+
+export const CredentialFields = ({ storedType }: Props) => {
+ const { control, watch, setValue } = useFormContext<TServiceForm>();
+ const credentialType = watch("credentialType");
+ const secret = watch("secret");
+ const username = watch("username");
+ const headerName = watch("headerName");
+ const headerPrefix = watch("headerPrefix");
+
+ const isBasic = credentialType === AgentVaultCredentialType.Basic;
+ const isUntouched = secret === UNCHANGED_SECRET;
+ const isUsernameUntouched = username === UNCHANGED_SECRET;
+
+ useEffect(() => {
+ if (!storedType || credentialType === storedType) return;
+ if (isUntouched) setValue("secret", "");
+ if (isUsernameUntouched) setValue("username", "");
+ }, [isUntouched, isUsernameUntouched, credentialType, storedType, setValue]);
+
+ return (
+ <div className="flex flex-col gap-5">
+ <Controller
+ control={control}
+ name="credentialType"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Credential Type</FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(AgentVaultCredentialType).map((value) => (
+ <SelectItem key={value} value={value}>
+ {CREDENTIAL_LABELS[value]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ {credentialType === AgentVaultCredentialType.Bearer && (
+ <>
+ <Controller
+ control={control}
+ name="headerName"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Header Name</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ placeholder="Authorization"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="headerPrefix"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Prefix</FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="Bearer" isError={Boolean(fieldState.error)} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </>
+ )}
+
+ {credentialType === AgentVaultCredentialType.Basic && (
+ <Controller
+ control={control}
+ name="username"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Username</FieldLabel>
+ <FieldContent>
+ <SecretInput
+ field={field}
+ label="Username"
+ placeholder="Enter the username"
+ isError={Boolean(fieldState.error)}
+ isUntouched={isUsernameUntouched}
+ />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ {credentialType !== AgentVaultCredentialType.Passthrough && (
+ <Controller
+ control={control}
+ name="secret"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>{isBasic ? "Password" : "Token"}</FieldLabel>
+ <FieldContent>
+ <SecretInput
+ field={field}
+ label={isBasic ? "Password" : "Token"}
+ placeholder={isBasic ? "Enter the password" : "Enter the token"}
+ isError={Boolean(fieldState.error)}
+ isUntouched={isUntouched}
+ />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ {credentialType !== AgentVaultCredentialType.Passthrough && (
+ <CodeBlock
+ label="Sends"
+ isCopyable={false}
+ value={
+ credentialPreview(
+ { credentialType, headerName, headerPrefix },
+ isBasic ? "base64(<username>:<password>)" : "<token>"
+ ) ?? ""
+ }
+ />
+ )}
+
+ {credentialType === AgentVaultCredentialType.Passthrough && (
+ <Alert variant="info">
+ <AlertTitle>No credentials are sent</AlertTitle>
+ <AlertDescription>
+ Requests go out as they are. On a proxy that denies everything else, this is what makes
+ these hosts reachable.
+ </AlertDescription>
+ </Alert>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsx b/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsx
new file mode 100644
index 0000000000..8193df5a75
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsx
@@ -0,0 +1,58 @@
+import { Controller, useFormContext } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ TextArea
+} from "@app/components/v3";
+
+import { TServiceForm } from "./serviceSchema";
+
+export const DetailsFields = () => {
+ const { control } = useFormContext<TServiceForm>();
+
+ return (
+ <div className="flex flex-col gap-5">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="datadog-us5" isError={Boolean(fieldState.error)} />
+ <FieldDescription>Lowercase letters, numbers and hyphens.</FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="hostPattern"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Hosts</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ rows={3}
+ placeholder="api.datadoghq.com"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldDescription>
+ Comma separated. Wildcards like *.example.com are allowed.
+ </FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
new file mode 100644
index 0000000000..ac738e1bc9
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
@@ -0,0 +1,79 @@
+import { useFormContext } from "react-hook-form";
+
+import {
+ Detail,
+ DetailGroup,
+ DetailGroupHeader,
+ DetailLabel,
+ DetailValue
+} from "@app/components/v3";
+import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+
+import { credentialPreview } from "./CredentialFields";
+import { CREDENTIAL_LABELS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";
+
+type Props = {
+ isUpdate: boolean;
+};
+
+export const ReviewFields = ({ isUpdate }: Props) => {
+ const { watch } = useFormContext<TServiceForm>();
+ const form = watch();
+
+ const isBasic = form.credentialType === AgentVaultCredentialType.Basic;
+ const secretLabel = isBasic ? "Password" : "Token";
+ const sends = credentialPreview(form);
+
+ const outcome = (value: string | undefined, canClear: boolean) => {
+ if (!isUpdate) return value ? "Set" : "None";
+ if (value === UNCHANGED_SECRET) return "Unchanged";
+ if (value) return "Replaced";
+ return canClear ? "Cleared" : "Unchanged";
+ };
+
+ return (
+ <div className="mb-4 flex flex-col gap-y-8">
+ <DetailGroup>
+ <DetailGroupHeader className="border-b border-border pb-2">Details</DetailGroupHeader>
+ <div className="flex flex-wrap gap-x-8 gap-y-4">
+ <Detail>
+ <DetailLabel>Name</DetailLabel>
+ <DetailValue>{form.name}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Hosts</DetailLabel>
+ <DetailValue className="font-mono">{form.hostPattern}</DetailValue>
+ </Detail>
+ </div>
+ </DetailGroup>
+
+ <DetailGroup>
+ <DetailGroupHeader className="border-b border-border pb-2">Credential</DetailGroupHeader>
+ <div className="flex flex-wrap gap-x-8 gap-y-4">
+ <Detail>
+ <DetailLabel>Type</DetailLabel>
+ <DetailValue>{CREDENTIAL_LABELS[form.credentialType]}</DetailValue>
+ </Detail>
+ {sends && (
+ <Detail>
+ <DetailLabel>Sends</DetailLabel>
+ <DetailValue className="font-mono">{sends}</DetailValue>
+ </Detail>
+ )}
+ {isBasic && (
+ <Detail>
+ <DetailLabel>Username</DetailLabel>
+ <DetailValue>{outcome(form.username, true)}</DetailValue>
+ </Detail>
+ )}
+ {form.credentialType !== AgentVaultCredentialType.Passthrough && (
+ <Detail>
+ <DetailLabel>{secretLabel}</DetailLabel>
+ <DetailValue>{outcome(form.secret, isBasic)}</DetailValue>
+ </Detail>
+ )}
+ </div>
+ </DetailGroup>
+ </div>
+ );
+};
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
new file mode 100644
index 0000000000..7ebc1b3da7
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@ -0,0 +1,407 @@
+import { useEffect, useMemo, useState } from "react";
+import { FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import axios from "axios";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ DiscardChangesAlertDialog,
+ DocumentationLinkBadge,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Stepper,
+ StepperList,
+ StepperStep
+} from "@app/components/v3";
+import { AgentVaultTemplate } from "@app/helpers/agentVaultTemplates";
+import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";
+import {
+ AgentVaultCredentialType,
+ useCreateAgentVaultService,
+ useUpdateAgentVaultService
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
+import { onRequestError } from "@app/hooks/api/reactQuery";
+import { ApiErrorTypes, TApiErrors } from "@app/hooks/api/types";
+
+import { ServiceTemplateSelect } from "../ServiceTemplateSelect";
+import { CredentialFields } from "./CredentialFields";
+import { DetailsFields } from "./DetailsFields";
+import { ReviewFields } from "./ReviewFields";
+import {
+ buildServiceSchema,
+ displayHostPattern,
+ SERVICE_STEP_FIELDS,
+ ServiceStep,
+ TServiceForm,
+ UNCHANGED_SECRET
+} from "./serviceSchema";
+import { SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";
+
+const BLANK_SERVICE_FORM: TServiceForm = {
+ name: "",
+ hostPattern: "",
+ credentialType: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ username: "",
+ secret: ""
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ accessBundleId: string;
+ service?: TAgentVaultService | null;
+};
+
+export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }: Props) => {
+ const isUpdate = Boolean(service);
+ const createService = useCreateAgentVaultService();
+ const updateService = useUpdateAgentVaultService();
+
+ const [template, setTemplate] = useState<AgentVaultTemplate | null>(null);
+
+ const schema = useMemo(() => buildServiceSchema(service), [service]);
+
+ const formMethods = useForm<TServiceForm>({ resolver: zodResolver(schema) });
+ const {
+ handleSubmit,
+ reset,
+ setError,
+ trigger,
+ formState: { isDirty, isSubmitting }
+ } = formMethods;
+
+ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =
+ useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });
+
+ const steps = useMemo(
+ () =>
+ isUpdate ? SERVICE_STEPS.filter((meta) => meta.step !== ServiceStep.Template) : SERVICE_STEPS,
+ [isUpdate]
+ );
+ const stepKeys = useMemo(() => steps.map((meta) => meta.step), [steps]);
+
+ const { step, isLastStep, goBack, goNext, onFormInvalid, setStep } = useWizardSteps<ServiceStep>({
+ stepKeys,
+ stepFields: SERVICE_STEP_FIELDS,
+ invalidMessage: "Fix the errors before saving.",
+ validateStep: (fields) => trigger(fields as (keyof TServiceForm)[])
+ });
+
+ useEffect(() => {
+ if (!isOpen) return;
+
+ setStep(0);
+ setTemplate(null);
+
+ if (service) {
+ const { credential } = service;
+ reset({
+ name: service.name,
+ hostPattern: displayHostPattern(service.hostPattern),
+ credentialType: credential.type,
+ // Seeded even for a credential that has no header, so switching the type to Bearer starts from
+ // the same defaults a new service gets. Left undefined, the submit would send an empty
+ // prefix and the proxy would attach a bare token.
+ headerName:
+ credential.type === AgentVaultCredentialType.Bearer
+ ? credential.headerName
+ : "Authorization",
+ headerPrefix:
+ credential.type === AgentVaultCredentialType.Bearer ? credential.headerPrefix : "Bearer",
+ username: credential.type === AgentVaultCredentialType.Basic ? UNCHANGED_SECRET : undefined,
+ secret: credential.type === AgentVaultCredentialType.Passthrough ? "" : UNCHANGED_SECRET
+ });
+ } else {
+ reset(BLANK_SERVICE_FORM);
+ }
+ }, [isOpen, service, isUpdate, reset, setStep]);
+
+ const handleTemplatePicked = (picked: AgentVaultTemplate | null) => {
+ setTemplate(picked);
+
+ if (picked) {
+ const cred = picked.credential;
+ reset({
+ ...BLANK_SERVICE_FORM,
+ name: picked.key,
+ hostPattern: picked.hostPattern,
+ credentialType: cred.type,
+ ...(cred.type === AgentVaultCredentialType.Bearer && {
+ headerName: cred.headerName ?? "Authorization",
+ headerPrefix: cred.headerPrefix ?? "Bearer"
+ })
+ });
+ } else {
+ reset(BLANK_SERVICE_FORM);
+ }
+ setStep(1);
+ };
+
+ const buildCredential = (data: TServiceForm) => {
+ if (data.credentialType === AgentVaultCredentialType.Passthrough) {
+ return { type: AgentVaultCredentialType.Passthrough as const };
+ }
+ if (data.credentialType === AgentVaultCredentialType.Basic) {
+ return {
+ type: AgentVaultCredentialType.Basic as const,
+ username: data.username ?? "",
+ password: data.secret ?? ""
+ };
+ }
+ return {
+ type: AgentVaultCredentialType.Bearer as const,
+ headerName: data.headerName || undefined,
+ headerPrefix: data.headerPrefix ?? "",
+ value: data.secret ?? ""
+ };
+ };
+
+ const buildCredentialPatch = (data: TServiceForm) => {
+ if (data.credentialType === AgentVaultCredentialType.Passthrough) {
+ return { type: AgentVaultCredentialType.Passthrough as const };
+ }
+ const untouched = data.secret === UNCHANGED_SECRET;
+
+ if (data.credentialType === AgentVaultCredentialType.Basic) {
+ return {
+ type: AgentVaultCredentialType.Basic as const,
+ username: data.username === UNCHANGED_SECRET ? undefined : (data.username ?? ""),
+ password: untouched ? undefined : (data.secret ?? "")
+ };
+ }
+ return {
+ type: AgentVaultCredentialType.Bearer as const,
+ headerName: data.headerName || "Authorization",
+ headerPrefix: data.headerPrefix ?? "",
+ value: untouched || !data.secret ? undefined : data.secret
+ };
+ };
+
+ const onSubmit = async (data: TServiceForm) => {
+ try {
+ if (service) {
+ await updateService.mutateAsync({
+ accessBundleId,
+ serviceId: service.id,
+ name: data.name,
+ hostPattern: data.hostPattern,
+ credential: buildCredentialPatch(data)
+ });
+ } else {
+ await createService.mutateAsync({
+ accessBundleId,
+ name: data.name,
+ hostPattern: data.hostPattern,
+ credential: buildCredential(data)
+ });
+ }
+
+ createNotification({
+ text: `Service "${data.name}" ${isUpdate ? "updated" : "created"}`,
+ type: "success"
+ });
+
+ onOpenChange(false);
+ } catch (error) {
+ const serverResponse = axios.isAxiosError(error)
+ ? (error.response?.data as TApiErrors | undefined)
+ : undefined;
+
+ if (
+ serverResponse?.error === ApiErrorTypes.BadRequestError &&
+ serverResponse.message.includes("already covers")
+ ) {
+ setError("hostPattern", { type: "server", message: serverResponse.message });
+ setStep(stepKeys.indexOf(ServiceStep.Details));
+ return;
+ }
+
+ if (serverResponse?.error === ApiErrorTypes.ValidationError) {
+ const hostIssues = serverResponse.message.filter(
+ (issue) => issue.path[0] === "hostPattern"
+ );
+ if (hostIssues.length > 0) {
+ setError("hostPattern", {
+ type: "server",
+ message: hostIssues.map((issue) => issue.message).join(" ")
+ });
+ setStep(stepKeys.indexOf(ServiceStep.Details));
+ }
+ if (hostIssues.length < serverResponse.message.length) onRequestError(error);
+ return;
+ }
+
+ // The mutation suppresses the global toast for bad requests so the conflict above shows once.
+ // Every other bad request has nothing rendering it, so hand those back.
+ onRequestError(error);
+ }
+ };
+
+ const handleStepChange = async (target: number) => {
+ if (target === step) return;
+ if (target < step) {
+ setStep(target);
+ return;
+ }
+ for (let i = step; i < target; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ if (!(await trigger(SERVICE_STEP_FIELDS[stepKeys[i]] as (keyof TServiceForm)[]))) {
+ return;
+ }
+ }
+ setStep(target);
+ };
+
+ const handleNext = async () => {
+ if (isLastStep) {
+ handleSubmit(onSubmit, onFormInvalid)();
+ return;
+ }
+ await goNext();
+ };
+
+ const stepDescription = (meta: (typeof SERVICE_STEPS)[number]) => {
+ if (meta.step === ServiceStep.Template) return template?.name ?? "Custom";
+ if (meta.step === ServiceStep.Review && isUpdate) return "Confirm and save";
+ return meta.shortDescription;
+ };
+
+ const current = steps[step];
+ const isTemplateStep = current.step === ServiceStep.Template;
+ const saveLabel = isUpdate ? "Save" : "Add Service";
+
+ return (
+ <Sheet
+ open={isOpen}
+ onOpenChange={(nextOpen) => {
+ if (nextOpen) {
+ onOpenChange(true);
+ return;
+ }
+ requestDiscard();
+ }}
+ >
+ <SheetContent className="sm:max-w-6xl">
+ <SheetHeader>
+ {isTemplateStep ? (
+ <>
+ <SheetTitle>Choose a template</SheetTitle>
+ <SheetDescription>
+ Start from a template, or configure the service yourself.
+ </SheetDescription>
+ </>
+ ) : (
+ <>
+ <SheetTitle className="flex items-center gap-2.5">
+ {template && (
+ <img
+ src={`/images/integrations/${template.image}`}
+ alt=""
+ className="size-6 object-contain"
+ />
+ )}
+ {template?.name ?? (isUpdate ? service?.name : "Custom")}
+ <DocumentationLinkBadge href={SERVICE_DOCS_URL} />
+ </SheetTitle>
+ <SheetDescription>Set up the service and its credentials.</SheetDescription>
+ </>
+ )}
+ </SheetHeader>
+
+ <FormProvider {...formMethods}>
+ {isTemplateStep ? (
+ <div className="min-h-0 flex-1 overflow-y-auto p-6">
+ <ServiceTemplateSelect onSelect={handleTemplatePicked} />
+ </div>
+ ) : (
+ // Nothing submits natively: a type="submit" on the last step is the same reconciled node as Continue,
+ // so the click that advances to Review would also save.
+ <form onSubmit={(e) => e.preventDefault()} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
+ Setup steps
+ </p>
+ <Stepper activeStep={step} orientation="vertical" onStepChange={handleStepChange}>
+ <StepperList>
+ {steps.map((meta, index) => (
+ <StepperStep
+ key={meta.step}
+ index={index}
+ title={meta.name}
+ description={stepDescription(meta)}
+ />
+ ))}
+ </StepperList>
+ </Stepper>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col overflow-y-auto px-8 py-6">
+ <div className="mb-6">
+ <h2 className="text-lg font-semibold text-foreground">{current.title}</h2>
+ <p className="mt-1 text-sm text-muted">{current.subtitle}</p>
+ </div>
+
+ {current.step === ServiceStep.Details && <DetailsFields />}
+ {current.step === ServiceStep.Credential && (
+ <CredentialFields storedType={service?.credential.type} />
+ )}
+ {current.step === ServiceStep.Review && <ReviewFields isUpdate={isUpdate} />}
+ </div>
+
+ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Step {step + 1} · {current.rightLabel}
+ </p>
+ <DocumentationLinkBadge href={SERVICE_DOCS_URL} />
+ </div>
+ <p className="text-sm font-semibold text-foreground">What this step does</p>
+ <p className="text-sm leading-relaxed text-muted">{current.rightDescription}</p>
+ </aside>
+ </div>
+
+ <SheetFooter className="items-center justify-between border-t">
+ <span className="text-xs text-muted">{isDirty ? "Unsaved changes" : ""}</span>
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-muted">
+ Step {step + 1} of {steps.length}
+ </span>
+ {step > 0 && (
+ <Button type="button" variant="outline" onClick={goBack}>
+ Back
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="av"
+ onClick={handleNext}
+ isPending={isLastStep && isSubmitting}
+ >
+ {isLastStep ? saveLabel : "Continue"}
+ </Button>
+ </div>
+ </SheetFooter>
+ </form>
+ )}
+ </FormProvider>
+
+ <DiscardChangesAlertDialog
+ open={isDiscardDialogOpen}
+ onOpenChange={setIsDiscardDialogOpen}
+ onDiscard={confirmDiscard}
+ title="Discard Changes?"
+ description="Your changes will be lost."
+ />
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/components/agent-vault/service-sheet/index.ts b/frontend/src/components/agent-vault/service-sheet/index.ts
new file mode 100644
index 0000000000..560e6f47b6
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/index.ts
@@ -0,0 +1 @@
+export * from "./ServiceSheet";
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
new file mode 100644
index 0000000000..9b1d81a906
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
@@ -0,0 +1,91 @@
+import { z } from "zod";
+
+import { addHostListIssues } from "@app/helpers/agentVaultHostPattern";
+import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
+import { slugSchema } from "@app/lib/schemas";
+
+/**
+ * Seeded into a secret field on edit so the box can show that something is stored without the server
+ * returning it. Never sent: the sheet maps it back to an omitted key.
+ */
+export const UNCHANGED_SECRET = "__INFISICAL_UNCHANGED__";
+
+/** The API stores :443 explicitly, so it is stripped wherever a host pattern is shown and put back on save. */
+export const displayHostPattern = (hostPattern: string) =>
+ hostPattern
+ .split(",")
+ .map((host) => host.trim().replace(/:443$/, ""))
+ .join(", ");
+
+export const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {
+ [AgentVaultCredentialType.Bearer]: "Bearer",
+ [AgentVaultCredentialType.Basic]: "Basic Auth",
+ [AgentVaultCredentialType.Passthrough]: "Pass-through"
+};
+
+export enum ServiceStep {
+ Template = "template",
+ Details = "details",
+ Credential = "credential",
+ Review = "review"
+}
+
+export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {
+ [ServiceStep.Template]: [],
+ [ServiceStep.Details]: ["name", "hostPattern"],
+ [ServiceStep.Credential]: ["credentialType", "headerName", "headerPrefix", "username", "secret"],
+ [ServiceStep.Review]: []
+};
+
+export const buildServiceSchema = (service?: TAgentVaultService | null) =>
+ z
+ .object({
+ name: slugSchema({ max: 64, field: "Name" }),
+ hostPattern: z.string().trim().min(1, "Required").max(1024).superRefine(addHostListIssues),
+ credentialType: z.nativeEnum(AgentVaultCredentialType),
+ headerName: z
+ .string()
+ .trim()
+ .max(128)
+ .regex(
+ /^[A-Za-z0-9!#$%&'*+.^_`|~-]*$/,
+ "A header name can't contain spaces or colons. Use letters, digits and dashes, as in X-API-Key."
+ )
+ .optional(),
+ headerPrefix: z.string().trim().max(64).optional(),
+ username: z.string().trim().max(256).optional(),
+ secret: z.string().max(8192).optional()
+ })
+ .superRefine((data, ctx) => {
+ if (data.credentialType === AgentVaultCredentialType.Passthrough) return;
+
+ const isUnchanged = data.secret === UNCHANGED_SECRET;
+
+ const typeChanged = Boolean(service) && service?.credential.type !== data.credentialType;
+
+ if (data.credentialType === AgentVaultCredentialType.Bearer) {
+ if ((!service || typeChanged) && !data.secret) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["secret"], message: "Required" });
+ }
+ return;
+ }
+
+ const willHaveUsername = data.username === UNCHANGED_SECRET ? true : Boolean(data.username);
+ const willHavePassword = isUnchanged ? true : Boolean(data.secret);
+ if (
+ typeChanged
+ ? Boolean(data.username) || Boolean(data.secret)
+ : willHaveUsername || willHavePassword
+ ) {
+ return;
+ }
+
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["username"],
+ message: "Enter a username, a password, or both."
+ });
+ });
+
+export type TServiceForm = z.infer<ReturnType<typeof buildServiceSchema>>;
diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
new file mode 100644
index 0000000000..39cc0b7bf0
--- /dev/null
+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
@@ -0,0 +1,49 @@
+import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urls";
+
+import { ServiceStep } from "./serviceSchema";
+
+export const SERVICE_DOCS_URL = AgentVaultDocsUrls.accessBundles;
+
+type StepMeta = {
+ step: ServiceStep;
+ name: string;
+ shortDescription?: string;
+ title?: string;
+ subtitle?: string;
+ rightLabel?: string;
+ rightDescription?: string;
+};
+
+export const SERVICE_STEPS: StepMeta[] = [
+ {
+ step: ServiceStep.Template,
+ name: "Template"
+ },
+ {
+ step: ServiceStep.Details,
+ name: "Details",
+ shortDescription: "Name and hosts",
+ title: "Details",
+ subtitle: "What this service is called, and the hosts it covers.",
+ rightLabel: "DETAILS",
+ rightDescription: "The credentials are only used for the hosts you list here."
+ },
+ {
+ step: ServiceStep.Credential,
+ name: "Credential",
+ shortDescription: "How to authenticate",
+ title: "Credential",
+ subtitle: "How requests to this service are authenticated.",
+ rightLabel: "CREDENTIAL",
+ rightDescription: "Agents reach this service without ever holding the credentials themselves."
+ },
+ {
+ step: ServiceStep.Review,
+ name: "Review",
+ shortDescription: "Confirm and add",
+ title: "Review",
+ subtitle: "Check everything before you save. You can change it later.",
+ rightLabel: "REVIEW",
+ rightDescription: "Review your settings before saving."
+ }
+];
diff --git a/frontend/src/components/auth/ProductSelectionStep.tsx b/frontend/src/components/auth/ProductSelectionStep.tsx
index b6e37ac496..fab9555bc7 100644
--- a/frontend/src/components/auth/ProductSelectionStep.tsx
+++ b/frontend/src/components/auth/ProductSelectionStep.tsx
@@ -36,8 +36,7 @@ interface ProductSelectionStepProps {
}
const setUpProduct = async (product: SignupProductType): Promise<Project | undefined> => {
- // PAM pages are org-scoped; there is no project to create.
- if (product === ProjectType.PAM) return undefined;
+ if (product === ProjectType.PAM || product === ProjectType.AgentVault) return undefined;
// Locate before creating: a retry after a lost response or a mid-flow refresh can arrive
// with the project already created (cert-manager is even bootstrapped server-side), and the
diff --git a/frontend/src/components/auth/SignupCompleteStep.tsx b/frontend/src/components/auth/SignupCompleteStep.tsx
index 3266a5eb89..c55477bdfe 100644
--- a/frontend/src/components/auth/SignupCompleteStep.tsx
+++ b/frontend/src/components/auth/SignupCompleteStep.tsx
@@ -77,6 +77,9 @@ export default function SignupCompleteStep({
if (target === ProjectType.PAM) {
return { to: "/organizations/$orgId/pam/access" as const, params: { orgId } };
}
+ if (target === ProjectType.AgentVault) {
+ return { to: "/organizations/$orgId/agent-vault/sessions" as const, params: { orgId } };
+ }
if (target !== ORG_OVERVIEW) {
const project = projects[target];
if (project) {
diff --git a/frontend/src/components/auth/TeamInviteStep.tsx b/frontend/src/components/auth/TeamInviteStep.tsx
index c6c6c41169..40a245a3a6 100644
--- a/frontend/src/components/auth/TeamInviteStep.tsx
+++ b/frontend/src/components/auth/TeamInviteStep.tsx
@@ -30,6 +30,7 @@ interface TeamInviteStepProps {
projectIds?: string[];
/** Also grant access to the org's PAM product (org-scoped, no project id). */
grantPamAccess?: boolean;
+ grantAgentVaultAccess?: boolean;
onComplete: () => void;
}
@@ -40,6 +41,7 @@ export default function TeamInviteStep({
productName,
projectIds,
grantPamAccess,
+ grantAgentVaultAccess,
onComplete
}: TeamInviteStepProps): JSX.Element {
const { t } = useTranslation();
@@ -51,7 +53,8 @@ export default function TeamInviteStep({
const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["setUpEmail"] as const);
const orgId = String(localStorage.getItem("orgData.id"));
- const grantCount = (projectIds?.length ?? 0) + (grantPamAccess ? 1 : 0);
+ const grantCount =
+ (projectIds?.length ?? 0) + (grantPamAccess ? 1 : 0) + (grantAgentVaultAccess ? 1 : 0);
const inviteUsersAndContinue = async () => {
if (isSending) return;
@@ -72,7 +75,8 @@ export default function TeamInviteStep({
organizationId: orgId,
organizationRoleSlug: "member",
...(projectIds?.length ? { projectIds } : {}),
- ...(grantPamAccess ? { grantPamAccess } : {})
+ ...(grantPamAccess ? { grantPamAccess } : {}),
+ ...(grantAgentVaultAccess ? { grantAgentVaultAccess } : {})
});
await waitForMinimumDuration(startedAt, 500);
diff --git a/frontend/src/components/auth/signupProducts.ts b/frontend/src/components/auth/signupProducts.ts
index 91ec9f57c4..0b25bf62d9 100644
--- a/frontend/src/components/auth/signupProducts.ts
+++ b/frontend/src/components/auth/signupProducts.ts
@@ -8,6 +8,7 @@ export type SignupProductType =
| ProjectType.CertificateManager
| ProjectType.KMS
| ProjectType.PAM
+ | ProjectType.AgentVault
| ProjectType.SecretScanning;
export const EXPLORING_SELECTION = "exploring" as const;
@@ -78,6 +79,18 @@ export const SIGNUP_PRODUCTS: SignupProductMeta[] = [
radioClassName: "border-product-pam",
dotClassName: "bg-product-pam"
},
+ {
+ type: ProjectType.AgentVault,
+ name: "Agent Vault",
+ description: "Run AI agents with the access, context, and capabilities they need to do work.",
+ completedDescription: "Everything is ready. Jump in and create your first access bundle.",
+ icon: getProjectLucideIcon(ProjectType.AgentVault),
+ iconClassName: "text-product-av",
+ tileClassName: "border-product-av/30 bg-gradient-to-br from-product-av/20 to-product-av/5",
+ selectedCardClassName: "border-product-av/50 bg-product-av/[0.04]",
+ radioClassName: "border-product-av",
+ dotClassName: "bg-product-av"
+ },
{
type: ProjectType.SecretScanning,
name: "Secret Scanning",
diff --git a/frontend/src/components/v2/PageHeader/PageHeader.tsx b/frontend/src/components/v2/PageHeader/PageHeader.tsx
index 6e4d7ad085..b3ab9b5d25 100644
--- a/frontend/src/components/v2/PageHeader/PageHeader.tsx
+++ b/frontend/src/components/v2/PageHeader/PageHeader.tsx
@@ -21,6 +21,7 @@ const SCOPE_BADGE: Record<NonNullable<Props["scope"]>, { icon: LucideIcon; class
[ProjectType.CertificateManager]: { className: "text-project", icon: ProjectIcon },
[ProjectType.KMS]: { className: "text-project", icon: ProjectIcon },
[ProjectType.PAM]: { className: "text-product-pam", icon: ProjectIcon },
+ [ProjectType.AgentVault]: { className: "text-product-av", icon: ProjectIcon },
[ProjectType.SecretScanning]: { className: "text-project", icon: ProjectIcon },
namespace: { className: "text-sub-org", icon: SubOrgIcon },
instance: { className: "text-neutral", icon: InstanceIcon }
@@ -40,7 +41,9 @@ export const PageHeader = ({ title, description, children, className, scope, ico
scope === "instance" && "decoration-neutral/90",
scope === "namespace" && "decoration-sub-org/90",
scope === ProjectType.PAM && "decoration-product-pam/90",
+ scope === ProjectType.AgentVault && "decoration-product-av/90",
scope !== ProjectType.PAM &&
+ scope !== ProjectType.AgentVault &&
Object.values(ProjectType).includes((scope as ProjectType) ?? "") &&
"decoration-project/90",
!scope && "no-underline"
diff --git a/frontend/src/components/v3/generic/Badge/Badge.tsx b/frontend/src/components/v3/generic/Badge/Badge.tsx
index 7bd2f1f913..7ea6f26727 100644
--- a/frontend/src/components/v3/generic/Badge/Badge.tsx
+++ b/frontend/src/components/v3/generic/Badge/Badge.tsx
@@ -42,7 +42,8 @@ const badgeVariants = cva(
"bg-project/15 text-project border-project/10 border [a&,button&]:hover:bg-project/35",
org: "bg-org/15 border border-org/10 text-org [a&,button&]:hover:bg-org/35",
"sub-org": "bg-sub-org/15 border-sub-org/10 text-sub-org [a&,button&]:hover:bg-sub-org/35",
- pam: "bg-product-pam/15 border-product-pam/10 text-product-pam [a&,button&]:hover:bg-product-pam/35"
+ pam: "bg-product-pam/15 border-product-pam/10 text-product-pam [a&,button&]:hover:bg-product-pam/35",
+ av: "bg-product-av/15 border-product-av/10 text-product-av [a&,button&]:hover:bg-product-av/35"
}
},
defaultVariants: {
diff --git a/frontend/src/components/v3/generic/Button/Button.tsx b/frontend/src/components/v3/generic/Button/Button.tsx
index 27568d2aa1..3cffd0dc9b 100644
--- a/frontend/src/components/v3/generic/Button/Button.tsx
+++ b/frontend/src/components/v3/generic/Button/Button.tsx
@@ -37,6 +37,7 @@ const buttonVariants = cva(
danger:
"border-danger/25 bg-danger/10 text-foreground hover:bg-danger/15 hover:border-danger/30 data-[state=open]:bg-danger/15 data-[state=open]:border-danger/30 [--control-variant-color:var(--color-danger)] [--control-variant-border-color:color-mix(in_oklab,var(--color-danger)_25%,transparent)] hover:[--control-variant-border-color:color-mix(in_oklab,var(--color-danger)_30%,transparent)] data-[state=open]:[--control-variant-border-color:color-mix(in_oklab,var(--color-danger)_30%,transparent)]",
pam: "border-product-pam/30 bg-product-pam/25 text-foreground hover:bg-product-pam/30 hover:border-product-pam/35 data-[state=open]:bg-product-pam/30 data-[state=open]:border-product-pam/35 [--control-variant-color:var(--color-product-pam)] [--control-variant-border-color:color-mix(in_oklab,var(--color-product-pam)_30%,transparent)] hover:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-pam)_35%,transparent)] data-[state=open]:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-pam)_35%,transparent)]",
+ av: "border-product-av/30 bg-product-av/25 text-foreground hover:bg-product-av/30 hover:border-product-av/35 data-[state=open]:bg-product-av/30 data-[state=open]:border-product-av/35 [--control-variant-color:var(--color-product-av)] [--control-variant-border-color:color-mix(in_oklab,var(--color-product-av)_30%,transparent)] hover:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-av)_35%,transparent)] data-[state=open]:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-av)_35%,transparent)]",
// Tinted from --product-color, which the caller must set inline (e.g. a billing catalog
// product's color) since the palette isn't knowable at build time.
product:
diff --git a/frontend/src/components/v3/generic/Button/ButtonBadge.tsx b/frontend/src/components/v3/generic/Button/ButtonBadge.tsx
index 73eb1a249b..062a6e6cdf 100644
--- a/frontend/src/components/v3/generic/Button/ButtonBadge.tsx
+++ b/frontend/src/components/v3/generic/Button/ButtonBadge.tsx
@@ -13,7 +13,8 @@ const buttonBadgeBackgrounds: Partial<Record<NonNullable<TBadgeProps["variant"]>
project: "bg-[color-mix(in_srgb,var(--color-project)_15%,var(--color-card))]",
org: "bg-[color-mix(in_srgb,var(--color-org)_15%,var(--color-card))]",
"sub-org": "bg-[color-mix(in_srgb,var(--color-sub-org)_15%,var(--color-card))]",
- pam: "bg-[color-mix(in_srgb,var(--color-product-pam)_15%,var(--color-card))]"
+ pam: "bg-[color-mix(in_srgb,var(--color-product-pam)_15%,var(--color-card))]",
+ av: "bg-[color-mix(in_srgb,var(--color-product-av)_15%,var(--color-card))]"
};
const buttonBadgeVariants = cva("pointer-events-none absolute z-10", {
diff --git a/frontend/src/components/v3/generic/Checkbox/Checkbox.tsx b/frontend/src/components/v3/generic/Checkbox/Checkbox.tsx
index 49cc252fb0..1ccbcef102 100644
--- a/frontend/src/components/v3/generic/Checkbox/Checkbox.tsx
+++ b/frontend/src/components/v3/generic/Checkbox/Checkbox.tsx
@@ -26,6 +26,7 @@ const checkboxVariants = cva(
org: "data-[state=checked]:border-org/25 data-[state=checked]:bg-org/10 data-[state=checked]:text-foreground data-[state=checked]:hover:bg-org/15 data-[state=checked]:hover:border-org/30",
"sub-org":
"data-[state=checked]:border-sub-org/25 data-[state=checked]:bg-sub-org/10 data-[state=checked]:text-foreground data-[state=checked]:hover:bg-sub-org/15 data-[state=checked]:hover:border-sub-org/30",
+ av: "data-[state=checked]:border-product-av/25 data-[state=checked]:bg-product-av/10 data-[state=checked]:text-foreground data-[state=checked]:hover:bg-product-av/15 data-[state=checked]:hover:border-product-av/30",
success:
"data-[state=checked]:border-success/25 data-[state=checked]:bg-success/10 data-[state=checked]:text-foreground data-[state=checked]:hover:bg-success/15 data-[state=checked]:hover:border-success/30",
info: "data-[state=checked]:border-info/25 data-[state=checked]:bg-info/10 data-[state=checked]:text-foreground data-[state=checked]:hover:bg-info/15 data-[state=checked]:hover:border-info/30",
diff --git a/frontend/src/components/v3/generic/Field/Field.tsx b/frontend/src/components/v3/generic/Field/Field.tsx
index 6980d64cfb..9ef69fdf3d 100644
--- a/frontend/src/components/v3/generic/Field/Field.tsx
+++ b/frontend/src/components/v3/generic/Field/Field.tsx
@@ -131,7 +131,8 @@ const fieldLabelVariants = cva(
org: "has-[[data-state=checked]]:border-org/30 has-[[data-state=checked]]:bg-org/5! [--control-variant-color:var(--color-org)] has-[[data-state=checked]]:[--control-variant-border-color:color-mix(in_oklab,var(--color-org)_30%,transparent)]",
"sub-org":
"has-[[data-state=checked]]:border-sub-org/30 has-[[data-state=checked]]:bg-sub-org/5! [--control-variant-color:var(--color-sub-org)] has-[[data-state=checked]]:[--control-variant-border-color:color-mix(in_oklab,var(--color-sub-org)_30%,transparent)]",
- pam: "has-[[data-state=checked]]:border-product-pam/30 has-[[data-state=checked]]:bg-product-pam/5! [--control-variant-color:var(--color-product-pam)] has-[[data-state=checked]]:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-pam)_30%,transparent)]"
+ pam: "has-[[data-state=checked]]:border-product-pam/30 has-[[data-state=checked]]:bg-product-pam/5! [--control-variant-color:var(--color-product-pam)] has-[[data-state=checked]]:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-pam)_30%,transparent)]",
+ av: "has-[[data-state=checked]]:border-product-av/30 has-[[data-state=checked]]:bg-product-av/5! [--control-variant-color:var(--color-product-av)] has-[[data-state=checked]]:[--control-variant-border-color:color-mix(in_oklab,var(--color-product-av)_30%,transparent)]"
},
size: {
default: "text-xs",
diff --git a/frontend/src/components/v3/generic/IconButton/IconButton.tsx b/frontend/src/components/v3/generic/IconButton/IconButton.tsx
index 584267cfa2..b6cc473039 100644
--- a/frontend/src/components/v3/generic/IconButton/IconButton.tsx
+++ b/frontend/src/components/v3/generic/IconButton/IconButton.tsx
@@ -38,7 +38,8 @@ const iconButtonVariants = cva(
"border-warning/25 bg-warning/10 text-foreground hover:bg-warning/15 hover:border-warning/30 data-[state=open]:bg-warning/15 data-[state=open]:border-warning/30",
danger:
"border-danger/25 bg-danger/10 text-foreground hover:bg-danger/15 hover:border-danger/30 data-[state=open]:bg-danger/15 data-[state=open]:border-danger/30",
- pam: "border-product-pam/30 bg-product-pam/25 text-foreground hover:bg-product-pam/30 hover:border-product-pam/35 data-[state=open]:bg-product-pam/30 data-[state=open]:border-product-pam/35"
+ pam: "border-product-pam/30 bg-product-pam/25 text-foreground hover:bg-product-pam/30 hover:border-product-pam/35 data-[state=open]:bg-product-pam/30 data-[state=open]:border-product-pam/35",
+ av: "border-product-av/30 bg-product-av/25 text-foreground hover:bg-product-av/30 hover:border-product-av/35 data-[state=open]:bg-product-av/30 data-[state=open]:border-product-av/35"
},
size: {
"2xs": "h-6 w-6 [&>svg]:size-3 rounded-sm [&>svg]:stroke-[1.75]",
diff --git a/frontend/src/components/v3/generic/Sidebar/Sidebar.tsx b/frontend/src/components/v3/generic/Sidebar/Sidebar.tsx
index 050747a5e6..9193a069d5 100644
--- a/frontend/src/components/v3/generic/Sidebar/Sidebar.tsx
+++ b/frontend/src/components/v3/generic/Sidebar/Sidebar.tsx
@@ -36,7 +36,14 @@ const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
-type SidebarScope = "org" | "sub-org" | "project" | "pam" | "admin";
+type SidebarScope = "org" | "sub-org" | "project" | "pam" | "agent-vault" | "admin";
+
+// Products that own a colour repoint the shared --color-project variable rather than adding a parallel
+// set of scope classes.
+const SIDEBAR_SCOPE_COLOR_OVERRIDE: Partial<Record<SidebarScope, Record<string, string>>> = {
+ pam: { "--color-project": "#ed3453" },
+ "agent-vault": { "--color-project": "var(--color-product-av)" }
+};
const SidebarScopeContext = React.createContext<SidebarScope>("org");
@@ -196,7 +203,8 @@ function Sidebar({
data-mobile="true"
className={cn(
"w-(--sidebar-width) bg-gradient-to-r to-transparent p-0 text-foreground [&>button]:hidden",
- (scope === "project" || scope === "pam") && "from-project/5",
+ (scope === "project" || scope === "pam" || scope === "agent-vault") &&
+ "from-project/5",
scope === "sub-org" && "from-sub-org/5",
scope === "org" && "from-org/5",
scope === "admin" && "from-admin/5"
@@ -204,7 +212,7 @@ function Sidebar({
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
- ...(scope === "pam" ? { "--color-project": "#ed3453" } : {})
+ ...(SIDEBAR_SCOPE_COLOR_OVERRIDE[scope] ?? {})
} as React.CSSProperties
}
side={side}
@@ -232,17 +240,14 @@ function Sidebar({
className={cn(
"flex h-full flex-col overflow-hidden border-r border-border bg-gradient-to-r to-transparent text-foreground transition-[width] duration-200 ease-linear",
state === "collapsed" ? "w-(--sidebar-width-icon)" : "w-(--sidebar-width)",
- (scope === "project" || scope === "pam") && "from-project/5",
+ (scope === "project" || scope === "pam" || scope === "agent-vault") &&
+ "from-project/5",
scope === "sub-org" && "from-sub-org/5",
scope === "org" && "from-org/5",
scope === "admin" && "from-admin/5",
className
)}
- style={
- scope === "pam"
- ? ({ "--color-project": "#ed3453" } as React.CSSProperties)
- : undefined
- }
+ style={SIDEBAR_SCOPE_COLOR_OVERRIDE[scope] as React.CSSProperties | undefined}
{...props}
>
{children}
@@ -648,6 +653,7 @@ const sidebarMenuButtonVariants = cva(
"sub-org": "data-active:border-l-sub-org data-active:[&_svg]:text-sub-org",
project: "data-active:border-l-project data-active:[&_svg]:text-project",
pam: "data-active:border-l-project data-active:[&_svg]:text-project",
+ "agent-vault": "data-active:border-l-project data-active:[&_svg]:text-project",
admin: "data-active:border-l-admin data-active:[&_svg]:text-admin"
}
},
diff --git a/frontend/src/components/v3/generic/Tabs/Tabs.tsx b/frontend/src/components/v3/generic/Tabs/Tabs.tsx
index 6c32dd44f5..53d0c00dd9 100644
--- a/frontend/src/components/v3/generic/Tabs/Tabs.tsx
+++ b/frontend/src/components/v3/generic/Tabs/Tabs.tsx
@@ -50,7 +50,7 @@ const Tabs = React.forwardRef<
);
});
-type TabsVariant = "filled" | "project" | "org" | "sub-org" | "pam";
+type TabsVariant = "filled" | "project" | "org" | "sub-org" | "pam" | "av";
const tabsListVariants: Record<"filled" | "underline", string> = {
filled: "border p-1 border-border",
@@ -63,7 +63,8 @@ const tabsListStyleByVariant: Record<TabsVariant, "filled" | "underline"> = {
project: "underline",
org: "underline",
"sub-org": "underline",
- pam: "underline"
+ pam: "underline",
+ av: "underline"
};
const tabsListAriaLabelByVariant: Record<TabsVariant, string> = {
@@ -71,7 +72,8 @@ const tabsListAriaLabelByVariant: Record<TabsVariant, string> = {
project: "Project sections",
org: "Organization sections",
"sub-org": "Sub-organization sections",
- pam: "PAM sections"
+ pam: "PAM sections",
+ av: "Agent Vault sections"
};
const TabsList = React.forwardRef<
@@ -130,6 +132,7 @@ const TabsTrigger = React.forwardRef<
"group-data-[variant=org]/tabs-list:after:bg-org",
"group-data-[variant=sub-org]/tabs-list:after:bg-sub-org",
"group-data-[variant=pam]/tabs-list:after:bg-product-pam",
+ "group-data-[variant=av]/tabs-list:after:bg-product-av",
className
)}
ref={ref}
diff --git a/frontend/src/components/v3/generic/Toggle/Toggle.tsx b/frontend/src/components/v3/generic/Toggle/Toggle.tsx
index 8b2b459483..0526551381 100644
--- a/frontend/src/components/v3/generic/Toggle/Toggle.tsx
+++ b/frontend/src/components/v3/generic/Toggle/Toggle.tsx
@@ -35,7 +35,8 @@ const toggleVariants = cva(
"data-[state=checked]:border-warning/10 data-[state=checked]:bg-warning/25 data-[state=checked]:hover:border-warning/15 data-[state=checked]:hover:bg-warning/30",
danger:
"data-[state=checked]:border-danger/10 data-[state=checked]:bg-danger/25 data-[state=checked]:hover:border-danger/15 data-[state=checked]:hover:bg-danger/30",
- pam: "data-[state=checked]:border-product-pam/10 data-[state=checked]:bg-product-pam/25 data-[state=checked]:hover:border-product-pam/15 data-[state=checked]:hover:bg-product-pam/30"
+ pam: "data-[state=checked]:border-product-pam/10 data-[state=checked]:bg-product-pam/25 data-[state=checked]:hover:border-product-pam/15 data-[state=checked]:hover:bg-product-pam/30",
+ av: "data-[state=checked]:border-product-av/10 data-[state=checked]:bg-product-av/25 data-[state=checked]:hover:border-product-av/15 data-[state=checked]:hover:bg-product-av/30"
}
},
defaultVariants: {
diff --git a/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx b/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx
index fc6615fbc3..0f722e3d0d 100644
--- a/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx
+++ b/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx
@@ -53,7 +53,7 @@ export type DateRangeFilterResult = {
isUtc: boolean;
};
-export type DateRangeFilterAccent = "primary" | "secondary";
+export type DateRangeFilterAccent = "primary" | "secondary" | "av";
type Props = {
defaultValue?: DateRangeFilterValue;
@@ -98,6 +98,19 @@ export const ACCENT_STYLES: Record<
applyButton: "border-org/25 bg-org/10 hover:bg-org/15 hover:border-org/30",
calendarMiddle: "data-[range-middle=true]:!bg-muted/[12%]",
activeVariant: "org"
+ },
+ av: {
+ selectedBorderBg: "border-product-av bg-product-av/5",
+ selectedCard: "border-product-av/40 bg-product-av/5 shadow-xs",
+ selectedBadge:
+ "rounded-sm bg-product-av/5 px-1.5 py-0.5 text-[11px] font-medium text-product-av",
+ selectedChip: "border-product-av/40 bg-product-av/5 text-foreground",
+ switchChecked:
+ "data-[state=checked]:border-product-av/25 data-[state=checked]:bg-product-av/10 data-[state=checked]:hover:border-product-av/30 data-[state=checked]:hover:bg-product-av/15",
+ applyButton:
+ "border-product-av/25 bg-product-av/10 hover:bg-product-av/15 hover:border-product-av/30",
+ calendarMiddle: "data-[range-middle=true]:!bg-muted/[12%]",
+ activeVariant: "av"
}
};
diff --git a/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx b/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx
index 1eb6cd2e6c..5a9049920a 100644
--- a/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx
+++ b/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx
@@ -1,4 +1,5 @@
import { useLayoutEffect, useRef, useState } from "react";
+import { Link, LinkComponentProps } from "@tanstack/react-router";
import { Badge, TBadgeProps } from "../../generic/Badge";
import { Popover, PopoverContent, PopoverTrigger } from "../../generic/Popover";
@@ -10,7 +11,11 @@ type TOverflowBadgeListProps<T> = {
getKey: (item: T) => React.Key;
getLabel: (item: T) => string;
getVariant?: (item: T) => TBadgeProps["variant"];
+ getTooltip?: (item: T) => React.ReactNode;
+ getClassName?: (item: T) => string | undefined;
appearance?: "badge" | "text";
+ icon?: React.ReactNode;
+ getLinkProps?: (item: T) => LinkComponentProps | undefined;
onItemClick?: (item: T) => void;
maxBadgeWidth?: number;
className?: string;
@@ -26,7 +31,11 @@ export const OverflowBadgeList = <T,>({
getKey,
getLabel,
getVariant,
+ getTooltip,
+ getClassName,
appearance = "badge",
+ icon,
+ getLinkProps,
onItemClick,
maxBadgeWidth = 160,
className
@@ -104,10 +113,11 @@ export const OverflowBadgeList = <T,>({
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
- }, [getLabel, getVariant, items, maxBadgeWidth]);
+ }, [getLabel, getVariant, getClassName, icon, items, maxBadgeWidth]);
const renderItem = (item: T, width?: number) => {
const label = getLabel(item);
+ const tooltip = getTooltip?.(item) ?? label;
if (appearance === "text") {
return (
@@ -125,25 +135,40 @@ export const OverflowBadgeList = <T,>({
{label}
</button>
</TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
+ <TooltipContent>{tooltip}</TooltipContent>
</Tooltip>
);
}
+ const linkProps = getLinkProps?.(item);
+
return (
<Tooltip key={getKey(item)}>
<TooltipTrigger asChild>
<Badge
variant={getVariant?.(item) ?? "neutral"}
+ className={getClassName?.(item)}
isTruncatable
+ iconPosition={icon ? "left" : undefined}
+ asChild={Boolean(linkProps)}
style={{
maxWidth: width ?? maxBadgeWidth
}}
>
- <span>{label}</span>
+ {linkProps ? (
+ <Link {...linkProps}>
+ {icon}
+ <span>{label}</span>
+ </Link>
+ ) : (
+ <>
+ {icon}
+ <span>{label}</span>
+ </>
+ )}
</Badge>
</TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
+ <TooltipContent>{tooltip}</TooltipContent>
</Tooltip>
);
};
@@ -206,9 +231,12 @@ export const OverflowBadgeList = <T,>({
key={getKey(item)}
data-overflow-badge-measure
variant={getVariant?.(item) ?? "neutral"}
+ className={getClassName?.(item)}
isTruncatable
+ iconPosition={icon ? "left" : undefined}
style={{ maxWidth: maxBadgeWidth }}
>
+ {icon}
<span>{getLabel(item)}</span>
</Badge>
)
@@ -216,7 +244,8 @@ export const OverflowBadgeList = <T,>({
{appearance === "text" ? (
<span data-overflow-badge-minimum className="w-6 text-sm" />
) : (
- <Badge data-overflow-badge-minimum isTruncatable>
+ <Badge data-overflow-badge-minimum isTruncatable iconPosition={icon ? "left" : undefined}>
+ {icon}
<span />
</Badge>
)}
diff --git a/frontend/src/components/v3/platform/PageHeader/PageHeader.tsx b/frontend/src/components/v3/platform/PageHeader/PageHeader.tsx
index d0986a2609..8f1be914bb 100644
--- a/frontend/src/components/v3/platform/PageHeader/PageHeader.tsx
+++ b/frontend/src/components/v3/platform/PageHeader/PageHeader.tsx
@@ -61,6 +61,11 @@ const PAGE_HEADER_SCOPE_CONFIG: Record<NonNullable<TPageHeaderScope>, TPageHeade
icon: ProjectIcon,
iconClassName: "text-product-pam",
titleClassName: "decoration-product-pam/90"
+ },
+ [ProjectType.AgentVault]: {
+ icon: ProjectIcon,
+ iconClassName: "text-product-av",
+ titleClassName: "decoration-product-av/90"
}
};
diff --git a/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts b/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts
index 76627208f3..98919b7ad2 100644
--- a/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts
+++ b/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts
@@ -25,11 +25,13 @@ import {
ListChecksIcon,
LockIcon,
type LucideIcon,
+ PackageIcon,
PenLineIcon,
PuzzleIcon,
RadarIcon,
RadioIcon,
RefreshCwIcon,
+ RouteIcon,
ScaleIcon,
ScrollTextIcon,
SearchIcon,
@@ -41,6 +43,7 @@ import {
StampIcon,
TableIcon,
TagIcon,
+ TicketIcon,
UndoIcon,
UserCheckIcon,
UsersIcon,
@@ -65,7 +68,8 @@ export const ProjectPermissionSubjectFamily = {
ProjectAdmin: "project-admin",
CertificateManager: "certificate-manager",
Kms: "kms",
- SecretScanning: "secret-scanning"
+ SecretScanning: "secret-scanning",
+ AgentVault: "agent-vault"
} as const;
export type ProjectPermissionSubjectFamily =
@@ -157,6 +161,8 @@ const kms = (Icon: LucideIcon) => present(ProjectPermissionSubjectFamily.Kms, Ic
const scanning = (Icon: LucideIcon) => present(ProjectPermissionSubjectFamily.SecretScanning, Icon);
+const agentVault = (Icon: LucideIcon) => present(ProjectPermissionSubjectFamily.AgentVault, Icon);
+
export const PROJECT_PERMISSION_SUBJECT_PRESENTATION = {
[ProjectPermissionSub.Secrets]: smResource(KeyIcon, PERMISSION_SUBJECT_SECRET_COLOR),
[ProjectPermissionSub.SecretFolders]: smResource(FolderIcon, PERMISSION_SUBJECT_FOLDER_COLOR),
@@ -221,7 +227,10 @@ export const PROJECT_PERMISSION_SUBJECT_PRESENTATION = {
[ProjectPermissionSub.HsmConnectors]: kms(CpuIcon),
[ProjectPermissionSub.SecretScanningDataSources]: scanning(DatabaseIcon),
[ProjectPermissionSub.SecretScanningFindings]: scanning(SearchIcon),
- [ProjectPermissionSub.SecretScanningConfigs]: scanning(SlidersHorizontalIcon)
+ [ProjectPermissionSub.SecretScanningConfigs]: scanning(SlidersHorizontalIcon),
+ [ProjectPermissionSub.AgentVaultAccessBundles]: agentVault(PackageIcon),
+ [ProjectPermissionSub.AgentVaultSessions]: agentVault(TicketIcon),
+ [ProjectPermissionSub.AgentVaultProxies]: agentVault(RouteIcon)
} as const satisfies Record<ProjectPermissionSub, ProjectPermissionSubjectPresentation>;
export const getProjectPermissionSubjectPresentation = (
diff --git a/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsx b/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsx
index 5b0de4f966..a0f0281c53 100644
--- a/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsx
+++ b/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsx
@@ -7,6 +7,7 @@ import {
DatabaseIcon,
FileTextIcon,
FolderOpenIcon,
+ IdCardIcon,
InboxIcon,
KeyIcon,
KeyRoundIcon,
@@ -56,6 +57,7 @@ import {
ProjectPermissionSecretSyncActions
} from "@app/context/ProjectPermissionContext/types";
import { getProjectLucideIcon, getProjectTitle } from "@app/helpers/project";
+import { useImplicitProduct } from "@app/hooks";
import { useGetOrganizationGroups, useGetOrganizationsWithSubOrgs } from "@app/hooks/api";
import { useGetAccessibleProjectsWithSubOrgs } from "@app/hooks/api/projects/queries";
import type { Project, TProjectNavigation } from "@app/hooks/api/projects/types";
@@ -85,7 +87,8 @@ const projectIconClassNames: Record<ProjectType, string> = {
[ProjectType.CertificateManager]: "text-product-pki",
[ProjectType.KMS]: "text-product-kms",
[ProjectType.SecretScanning]: "text-product-ss",
- [ProjectType.PAM]: "text-product-pam"
+ [ProjectType.PAM]: "text-product-pam",
+ [ProjectType.AgentVault]: "text-product-av"
};
const NavigationCommandMenu = ({
@@ -137,6 +140,11 @@ const navigateToProject = (
to: "/organizations/$orgId/pam/accounts",
params: { orgId: project.orgId }
});
+ case ProjectType.AgentVault:
+ return navigate({
+ to: "/organizations/$orgId/agent-vault/sessions",
+ params: { orgId: project.orgId }
+ });
case ProjectType.KMS:
default:
return navigate({
@@ -633,7 +641,8 @@ const getProjectLandingItem = ({
[ProjectType.CertificateManager]: { label: "Dashboard", icon: LayoutDashboardIcon },
[ProjectType.KMS]: { label: "Overview", icon: KeyIcon },
[ProjectType.SecretScanning]: { label: "Data Sources", icon: DatabaseIcon },
- [ProjectType.PAM]: { label: "Accounts", icon: FolderOpenIcon }
+ [ProjectType.PAM]: { label: "Accounts", icon: FolderOpenIcon },
+ [ProjectType.AgentVault]: { label: "Sessions", icon: IdCardIcon }
};
return {
@@ -982,8 +991,8 @@ const CurrentProjectCommandMenu = ({ content }: { content: CommandContent }) =>
};
const OrganizationCommandMenu = () => {
- const { pathname } = useLocation();
const { projectId } = useParams({ strict: false }) as { projectId?: string };
+ const orgScopedProduct = useImplicitProduct();
const { currentOrg, isRootOrganization } = useOrganization();
const user = useRouteContext({ from: "/_authenticate", select: (context) => context.user });
const { permission } = useOrgPermission();
@@ -1052,10 +1061,7 @@ const OrganizationCommandMenu = () => {
...entityGroups.searchGroups
]
};
- const isProjectRoute = Boolean(projectId);
- const isPamRoute = pathname.startsWith(`/organizations/${currentOrg.id}/pam`);
-
- if (isProjectRoute || isPamRoute) return <CurrentProjectCommandMenu content={content} />;
+ if (projectId || orgScopedProduct) return <CurrentProjectCommandMenu content={content} />;
return <NavigationCommandMenu {...content} />;
};
diff --git a/frontend/src/context/ProjectContext/ProjectContext.tsx b/frontend/src/context/ProjectContext/ProjectContext.tsx
index bafe70ab42..21679d7812 100644
--- a/frontend/src/context/ProjectContext/ProjectContext.tsx
+++ b/frontend/src/context/ProjectContext/ProjectContext.tsx
@@ -3,17 +3,16 @@ import { useParams } from "@tanstack/react-router";
import { projectKeys } from "@app/hooks/api";
import { fetchProjectById } from "@app/hooks/api/projects/queries";
-
-import { useOrganization } from "../OrganizationContext";
+import { useImplicitProjectId } from "@app/hooks/useImplicitProjectId";
export const useProject = () => {
const params = useParams({
strict: false
});
- const { currentOrg } = useOrganization();
+ const implicitProjectId = useImplicitProjectId();
- const projectId = params.projectId ?? currentOrg.pamProjectId;
+ const projectId = params.projectId ?? implicitProjectId;
if (!projectId) {
throw new Error("Missing project id");
diff --git a/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx b/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
index d8d5e4b7d9..92359bfe81 100644
--- a/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
+++ b/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
@@ -6,8 +6,8 @@ import { useParams } from "@tanstack/react-router";
import { evaluatePermissionsAbility } from "@app/helpers/permissions";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
+import { useImplicitProjectId } from "@app/hooks/useImplicitProjectId";
-import { useOrganization } from "../OrganizationContext";
import { ProjectPermissionSet } from "./types";
export const useProjectPermission = () => {
@@ -15,9 +15,9 @@ export const useProjectPermission = () => {
strict: false
});
- const { currentOrg } = useOrganization();
+ const implicitProjectId = useImplicitProjectId();
- const projectId = params.projectId ?? currentOrg.pamProjectId;
+ const projectId = params.projectId ?? implicitProjectId;
if (!projectId) {
throw new Error("useProjectPermission to be used within <ProjectPermissionContext>");
diff --git a/frontend/src/context/ProjectPermissionContext/index.tsx b/frontend/src/context/ProjectPermissionContext/index.tsx
index e7705a2c5d..106d5b7f61 100644
--- a/frontend/src/context/ProjectPermissionContext/index.tsx
+++ b/frontend/src/context/ProjectPermissionContext/index.tsx
@@ -2,6 +2,9 @@ export { useProjectPermission } from "./ProjectPermissionContext";
export type { ProjectPermissionSet, TProjectPermission } from "./types";
export {
ProjectPermissionActions,
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionAgentVaultProxyActions,
+ ProjectPermissionAgentVaultSessionActions,
ProjectPermissionAuditLogsActions,
ProjectPermissionCertificateActions,
ProjectPermissionCertificateAuthorityActions,
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index 0650b5b768..a22cccf60d 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -291,6 +291,29 @@ export enum ProjectPermissionProxiedServiceActions {
ReportUsage = "report-usage"
}
+export enum ProjectPermissionAgentVaultAccessBundleActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ ManageMembers = "manage-members"
+}
+
+export enum ProjectPermissionAgentVaultSessionActions {
+ Read = "read",
+ Create = "create",
+ Revoke = "revoke"
+}
+
+export enum ProjectPermissionAgentVaultProxyActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ IssueToken = "issue-token",
+ Revoke = "revoke"
+}
+
export enum ProjectPermissionApprovalRequestActions {
Read = "read",
Create = "create"
@@ -443,6 +466,9 @@ export enum ProjectPermissionSub {
HsmConnectors = "hsm-connectors",
HoneyTokens = "honey-tokens",
ProxiedServices = "proxied-services",
+ AgentVaultAccessBundles = "agent-vault-access-bundles",
+ AgentVaultSessions = "agent-vault-sessions",
+ AgentVaultProxies = "agent-vault-proxies",
ApprovalRequests = "approval-requests",
ApprovalRequestGrants = "approval-request-grants",
ProjectFolderGrant = "project-folder-grant",
@@ -723,6 +749,9 @@ export type ProjectPermissionSet =
| (ForcedSubject<ProjectPermissionSub.ProxiedServices> & ProxiedServiceSubjectFields)
)
]
+ | [ProjectPermissionAgentVaultAccessBundleActions, ProjectPermissionSub.AgentVaultAccessBundles]
+ | [ProjectPermissionAgentVaultSessionActions, ProjectPermissionSub.AgentVaultSessions]
+ | [ProjectPermissionAgentVaultProxyActions, ProjectPermissionSub.AgentVaultProxies]
| [
ProjectPermissionProjectFolderGrantActions,
(
diff --git a/frontend/src/context/index.tsx b/frontend/src/context/index.tsx
index 86b6ae4a20..c9023e1936 100644
--- a/frontend/src/context/index.tsx
+++ b/frontend/src/context/index.tsx
@@ -18,6 +18,9 @@ export { useProject } from "./ProjectContext";
export type { TProjectPermission } from "./ProjectPermissionContext";
export {
ProjectPermissionActions,
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionAgentVaultProxyActions,
+ ProjectPermissionAgentVaultSessionActions,
ProjectPermissionAuditLogsActions,
ProjectPermissionCertificateActions,
ProjectPermissionCertificateAuthorityActions,
diff --git a/frontend/src/helpers/agentVaultHostPattern.ts b/frontend/src/helpers/agentVaultHostPattern.ts
new file mode 100644
index 0000000000..1a9ad0d671
--- /dev/null
+++ b/frontend/src/helpers/agentVaultHostPattern.ts
@@ -0,0 +1,51 @@
+import { z } from "zod";
+
+const HOST_LABELS_RE =
+ /^(?:\*\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/i;
+
+/**
+ * A partial pre-check, so a malformed host is caught on the field that holds it rather than bounced
+ * back from a submit. agent-vault-host-pattern.ts stays the grammar of record.
+ */
+const hostSegmentError = (segment: string, seen: Set<string>): string | null => {
+ const raw = segment.trim();
+ if (!raw) return "Remove the empty entry";
+ if (raw.includes("://")) return "Remove the scheme, for example https://";
+ if (raw.includes("/"))
+ return "A host pattern covers a whole host, so remove everything from the first /";
+ if (raw.startsWith("[")) return null;
+
+ let host = raw;
+ let port = "443";
+ const colonIdx = raw.lastIndexOf(":");
+ if (colonIdx !== -1) {
+ host = raw.slice(0, colonIdx);
+ port = raw.slice(colonIdx + 1);
+ const parsed = Number(port);
+ if (!/^\d+$/.test(port) || parsed < 1 || parsed > 65535) return `"${raw}" has an invalid port`;
+ }
+
+ host = host.replace(/\.$/, "").toLowerCase();
+ if (host === "*" || host === "*.") return "Name specific hosts. A bare wildcard is too broad.";
+ if (!HOST_LABELS_RE.test(host)) return `"${raw}" is not a valid host`;
+
+ const key = `${host}:${port}`;
+ if (seen.has(key)) return `"${raw}" is listed more than once`;
+ seen.add(key);
+
+ return null;
+};
+
+export const addHostListIssues = (
+ value: string | undefined,
+ ctx: z.RefinementCtx,
+ path?: (string | number)[]
+) => {
+ if (!value) return;
+
+ const seen = new Set<string>();
+ value.split(",").forEach((segment) => {
+ const error = hostSegmentError(segment, seen);
+ if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, message: error, ...(path && { path }) });
+ });
+};
diff --git a/frontend/src/helpers/agentVaultTemplates.ts b/frontend/src/helpers/agentVaultTemplates.ts
new file mode 100644
index 0000000000..2346d2c212
--- /dev/null
+++ b/frontend/src/helpers/agentVaultTemplates.ts
@@ -0,0 +1,411 @@
+import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+
+// Copied from the proxied-services catalog rather than imported: that module stays independently
+// deletable, and Agent Vault's grammar rejects the paths several of its entries carry.
+export enum AgentVaultTemplateCategory {
+ Llm = "LLM Providers",
+ DeveloperTools = "Developer Tools",
+ Communication = "Communication",
+ Monitoring = "Monitoring",
+ Productivity = "Productivity",
+ Payments = "Payments",
+ Commerce = "Commerce"
+}
+
+export type AgentVaultTemplateCredential =
+ | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string }
+ | { type: AgentVaultCredentialType.Basic }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type AgentVaultTemplate = {
+ key: string;
+ name: string;
+ image: string;
+ category: AgentVaultTemplateCategory;
+ description: string;
+ hostPattern: string;
+ aliases?: string[];
+ credential: AgentVaultTemplateCredential;
+};
+
+export const AGENT_VAULT_TEMPLATES: AgentVaultTemplate[] = [
+ {
+ key: "openai",
+ name: "OpenAI",
+ image: "OpenAIWhite.png",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Chat and models from OpenAI.",
+ hostPattern: "api.openai.com",
+ aliases: ["gpt", "chatgpt"],
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "anthropic",
+ name: "Anthropic",
+ image: "Anthropic.png",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Claude models from Anthropic.",
+ hostPattern: "api.anthropic.com",
+ aliases: ["claude"],
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "x-api-key",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "gemini",
+ name: "Google Gemini",
+ image: "Gemini.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Google's Gemini models.",
+ hostPattern: "generativelanguage.googleapis.com",
+ aliases: ["google", "bard", "vertex"],
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "x-goog-api-key",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "mistral",
+ name: "Mistral AI",
+ image: "Mistral.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Chat and embedding models from Mistral.",
+ hostPattern: "api.mistral.ai",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "cohere",
+ name: "Cohere",
+ image: "Cohere.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Cohere's language models.",
+ hostPattern: "api.cohere.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "groq",
+ name: "Groq",
+ image: "Groq.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Fast model inference from Groq.",
+ hostPattern: "api.groq.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "perplexity",
+ name: "Perplexity",
+ image: "Perplexity.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Perplexity's answer engine.",
+ hostPattern: "api.perplexity.ai",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "openrouter",
+ name: "OpenRouter",
+ image: "OpenRouter.png",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "One key for many AI models.",
+ hostPattern: "openrouter.ai",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "together",
+ name: "Together AI",
+ image: "Together.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Open models on Together AI.",
+ hostPattern: "api.together.ai, api.together.xyz",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "deepseek",
+ name: "DeepSeek",
+ image: "DeepSeek.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "DeepSeek's chat and reasoning models.",
+ hostPattern: "api.deepseek.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "xai",
+ name: "xAI (Grok)",
+ image: "xAI.svg",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Grok models from xAI.",
+ hostPattern: "api.x.ai",
+ aliases: ["grok"],
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "fireworks",
+ name: "Fireworks AI",
+ image: "Fireworks.png",
+ category: AgentVaultTemplateCategory.Llm,
+ description: "Fast open-model inference.",
+ hostPattern: "api.fireworks.ai",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "stripe",
+ name: "Stripe",
+ image: "Stripe.svg",
+ category: AgentVaultTemplateCategory.Payments,
+ description: "Payments and billing.",
+ hostPattern: "api.stripe.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "twilio",
+ name: "Twilio",
+ image: "Twilio.svg",
+ category: AgentVaultTemplateCategory.Communication,
+ description: "SMS, voice, and messaging.",
+ hostPattern: "api.twilio.com",
+ credential: { type: AgentVaultCredentialType.Basic }
+ },
+ {
+ key: "sendgrid",
+ name: "SendGrid",
+ image: "SendGrid.png",
+ category: AgentVaultTemplateCategory.Communication,
+ description: "Send transactional email.",
+ hostPattern: "api.sendgrid.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "resend",
+ name: "Resend",
+ image: "Resend.svg",
+ category: AgentVaultTemplateCategory.Communication,
+ description: "Email built for developers.",
+ hostPattern: "api.resend.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "slack",
+ name: "Slack",
+ image: "Slack.svg",
+ category: AgentVaultTemplateCategory.Communication,
+ description: "Post messages and build Slack apps.",
+ hostPattern: "slack.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "discord",
+ name: "Discord",
+ image: "Discord.svg",
+ category: AgentVaultTemplateCategory.Communication,
+ description: "Build and run Discord bots.",
+ hostPattern: "discord.com",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bot"
+ }
+ },
+ {
+ key: "github",
+ name: "GitHub",
+ image: "GitHub.png",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "Repos, issues, and more on GitHub.",
+ hostPattern: "api.github.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "gitlab",
+ name: "GitLab",
+ image: "GitLab.png",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "Repos and pipelines on GitLab.",
+ hostPattern: "gitlab.com",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "PRIVATE-TOKEN",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "vercel",
+ name: "Vercel",
+ image: "Vercel.png",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "Deploys and the Vercel API.",
+ hostPattern: "api.vercel.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "cloudflare",
+ name: "Cloudflare",
+ image: "Cloudflare.png",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "DNS, CDN, and the Cloudflare API.",
+ hostPattern: "api.cloudflare.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "supabase",
+ name: "Supabase",
+ image: "Supabase.png",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "Postgres, auth, and storage.",
+ hostPattern: "<your-project>.supabase.co",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "apikey",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "npm",
+ name: "npm",
+ image: "NPM.svg",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "The npm package registry.",
+ hostPattern: "registry.npmjs.org",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "github-npm",
+ name: "GitHub Packages",
+ image: "GitHub.png",
+ category: AgentVaultTemplateCategory.DeveloperTools,
+ description: "GitHub's npm package registry.",
+ hostPattern: "npm.pkg.github.com",
+ aliases: ["npm", "packages"],
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "datadog",
+ name: "Datadog",
+ image: "Datadog.png",
+ category: AgentVaultTemplateCategory.Monitoring,
+ description: "Monitoring and analytics.",
+ hostPattern: "api.datadoghq.com",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "DD-API-KEY",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "sentry",
+ name: "Sentry",
+ image: "Sentry.svg",
+ category: AgentVaultTemplateCategory.Monitoring,
+ description: "Error and performance monitoring.",
+ hostPattern: "sentry.io",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "pagerduty",
+ name: "PagerDuty",
+ image: "PagerDuty.svg",
+ category: AgentVaultTemplateCategory.Monitoring,
+ description: "On-call and incident management.",
+ hostPattern: "api.pagerduty.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "linear",
+ name: "Linear",
+ image: "Linear.svg",
+ category: AgentVaultTemplateCategory.Productivity,
+ description: "Issue tracking and project management.",
+ hostPattern: "api.linear.app",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "notion",
+ name: "Notion",
+ image: "Notion.svg",
+ category: AgentVaultTemplateCategory.Productivity,
+ description: "Notion workspace and docs.",
+ hostPattern: "api.notion.com",
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "jira",
+ name: "Jira",
+ image: "Jira.svg",
+ category: AgentVaultTemplateCategory.Productivity,
+ description: "Atlassian Jira issue tracking.",
+ hostPattern: "<your-tenant>.atlassian.net",
+ credential: { type: AgentVaultCredentialType.Basic }
+ },
+ {
+ key: "google-workspace",
+ name: "Google Workspace",
+ image: "Google Workspace.svg",
+ category: AgentVaultTemplateCategory.Productivity,
+ description: "Gmail, Calendar, Sheets, and Drive.",
+ hostPattern: "gmail.googleapis.com, sheets.googleapis.com, www.googleapis.com",
+ aliases: ["workspace", "gsuite", "gmail", "calendar", "sheets", "drive", "gdrive"],
+ credential: { type: AgentVaultCredentialType.Bearer }
+ },
+ {
+ key: "postmark",
+ name: "Postmark",
+ image: "Postmark.png",
+ category: AgentVaultTemplateCategory.Communication,
+ description: "Transactional email.",
+ hostPattern: "api.postmarkapp.com",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "X-Postmark-Server-Token",
+ headerPrefix: ""
+ }
+ },
+ {
+ key: "shopify",
+ name: "Shopify",
+ image: "Shopify.svg",
+ category: AgentVaultTemplateCategory.Commerce,
+ description: "Shopify e-commerce API.",
+ hostPattern: "<your-store>.myshopify.com",
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "X-Shopify-Access-Token",
+ headerPrefix: ""
+ }
+ }
+];
+
+export const POPULAR_AGENT_VAULT_TEMPLATES = [
+ "openai",
+ "anthropic",
+ "github",
+ "slack",
+ "google-workspace"
+];
+
+const stripPort = (pattern: string) => pattern.split(":")[0];
+
+const hostMatchesTemplateHost = (host: string, templateHost: string) => {
+ if (!templateHost.startsWith("*.")) return host === templateHost;
+ const suffix = templateHost.slice(2);
+ if (!host.endsWith(`.${suffix}`)) return false;
+ return !host.slice(0, host.length - suffix.length - 1).includes(".");
+};
+
+export const findTemplateForHostPattern = (hostPattern: string): AgentVaultTemplate | undefined => {
+ const hosts = hostPattern
+ .split(",")
+ .map((entry) => stripPort(entry.trim()))
+ .filter(Boolean);
+
+ return AGENT_VAULT_TEMPLATES.find((template) =>
+ template.hostPattern
+ .split(",")
+ .map((entry) => stripPort(entry.trim()))
+ .some((templateHost) => hosts.some((host) => hostMatchesTemplateHost(host, templateHost)))
+ );
+};
diff --git a/frontend/src/helpers/project.ts b/frontend/src/helpers/project.ts
index 8306e01af6..7f8680d429 100644
--- a/frontend/src/helpers/project.ts
+++ b/frontend/src/helpers/project.ts
@@ -1,4 +1,12 @@
-import { FileKeyIcon, KeyIcon, LockIcon, LucideIcon, RadarIcon, UsersIcon } from "lucide-react";
+import {
+ FileKeyIcon,
+ KeyIcon,
+ LockIcon,
+ LucideIcon,
+ RadarIcon,
+ UsersIcon,
+ VaultIcon
+} from "lucide-react";
import { apiRequest } from "@app/config/request";
import { createWorkspace } from "@app/hooks/api/projects/queries";
@@ -88,7 +96,8 @@ const VALID_PROJECT_SLUGS = new Set<string>([
ProjectType.CertificateManager,
ProjectType.KMS,
ProjectType.SecretScanning,
- ProjectType.PAM
+ ProjectType.PAM,
+ ProjectType.AgentVault
]);
export const urlSlugToProjectType = (slug: string): ProjectType | null => {
@@ -115,6 +124,24 @@ const PROJECT_TYPES_WITH_INTERMEDIATE_VIEW = new Set<ProjectType>([
export const hasIntermediateProjectsView = (type: ProjectType) =>
PROJECT_TYPES_WITH_INTERMEDIATE_VIEW.has(type);
+// Products that live at /organizations/$orgId/<slug> over a single implicit project, with no $projectId
+// in the URL.
+const ORG_SCOPED_PRODUCT_TYPES = new Set<ProjectType>([ProjectType.PAM, ProjectType.AgentVault]);
+
+export const isOrgScopedProduct = (type: ProjectType) => ORG_SCOPED_PRODUCT_TYPES.has(type);
+
+const PRODUCTS_WITHOUT_ASSUME_PRIVILEGES = new Set<ProjectType>([ProjectType.AgentVault]);
+
+export const supportsAssumePrivileges = (type: ProjectType) =>
+ !PRODUCTS_WITHOUT_ASSUME_PRIVILEGES.has(type);
+
+const ORG_SCOPED_PRODUCT_PATH_RE = /^\/organizations\/[^/]+\/(pam|agent-vault)(?:\/|$)/;
+
+export const getOrgScopedProductFromPath = (pathname: string): ProjectType | null => {
+ const slug = pathname.match(ORG_SCOPED_PRODUCT_PATH_RE)?.[1];
+ return slug ? urlSlugToProjectType(slug) : null;
+};
+
export const getProjectBaseURL = (type: ProjectType) => {
switch (type) {
case ProjectType.SecretManager:
@@ -123,6 +150,8 @@ export const getProjectBaseURL = (type: ProjectType) => {
return "/organizations/$orgId/projects/cert-manager/$projectId";
case ProjectType.PAM:
return "/organizations/$orgId/pam" as const;
+ case ProjectType.AgentVault:
+ return "/organizations/$orgId/agent-vault" as const;
default:
return `/organizations/$orgId/projects/${type}/$projectId` as const;
}
@@ -140,6 +169,8 @@ export const getProjectHomePage = (type: ProjectType, environments: ProjectEnv[]
return `/organizations/$orgId/projects/${type}/$projectId/data-sources` as const;
case ProjectType.PAM:
return "/organizations/$orgId/pam/access" as const;
+ case ProjectType.AgentVault:
+ return "/organizations/$orgId/agent-vault/sessions" as const;
default:
return `/organizations/$orgId/projects/${type}/$projectId/overview` as const;
}
@@ -151,7 +182,8 @@ export const getProjectTitle = (type: ProjectType) => {
[ProjectType.KMS]: "KMS",
[ProjectType.CertificateManager]: "Certificate Manager",
[ProjectType.SecretScanning]: "Secret Scanning",
- [ProjectType.PAM]: "Privileged Access Manager"
+ [ProjectType.PAM]: "Privileged Access Manager",
+ [ProjectType.AgentVault]: "Agent Vault"
};
return titleConvert[type] || type;
};
@@ -167,7 +199,9 @@ export const getProjectDescription = (type: ProjectType) => {
[ProjectType.SecretScanning]:
"Continuously scan repositories, builds, and runtime artifacts for leaked secrets and misconfigurations.",
[ProjectType.PAM]:
- "Connect to databases and servers securely with session brokering, recording, and credential vaulting."
+ "Connect to databases and servers securely with session brokering, recording, and credential vaulting.",
+ [ProjectType.AgentVault]:
+ "Run AI agents with the access, context, and capabilities they need to do work, wherever they operate."
};
return descriptions[type] ?? "";
};
@@ -203,7 +237,8 @@ export const getProjectLucideIcon = (type: ProjectType): LucideIcon => {
[ProjectType.KMS]: LockIcon,
[ProjectType.CertificateManager]: FileKeyIcon,
[ProjectType.SecretScanning]: RadarIcon,
- [ProjectType.PAM]: UsersIcon
+ [ProjectType.PAM]: UsersIcon,
+ [ProjectType.AgentVault]: VaultIcon
};
return iconConvert[type] || KeyIcon;
};
diff --git a/frontend/src/helpers/roles.ts b/frontend/src/helpers/roles.ts
index 0a3c201afe..f452ac7e7b 100644
--- a/frontend/src/helpers/roles.ts
+++ b/frontend/src/helpers/roles.ts
@@ -33,6 +33,19 @@ export const PAM_PRODUCT_ROLE_OPTIONS = [
}
];
+export const AGENT_VAULT_PRODUCT_ROLE_OPTIONS = [
+ {
+ value: ProjectMembershipRole.Admin,
+ label: "Admin",
+ description: "Full administrative access over Agent Vault"
+ },
+ {
+ value: ProjectMembershipRole.Member,
+ label: "Member",
+ description: "Create sessions over the access bundles they're granted"
+ }
+];
+
export const formatProjectRoleName = (role: string, customRoleName?: string) => {
switch (role) {
case ProjectMembershipRole.Admin:
diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.ts
new file mode 100644
index 0000000000..e8d04d4114
--- /dev/null
+++ b/frontend/src/hooks/api/agentVault/enums.ts
@@ -0,0 +1,21 @@
+export enum AgentVaultCredentialType {
+ Bearer = "bearer",
+ Basic = "basic",
+ Passthrough = "passthrough"
+}
+
+export enum AgentVaultTrafficPolicy {
+ AnyHost = "any-host",
+ BundleHosts = "bundle-hosts"
+}
+
+export enum AgentVaultSessionStatus {
+ Active = "active",
+ Revoked = "revoked",
+ Expired = "expired"
+}
+
+export enum AgentVaultSessionScope {
+ Mine = "mine",
+ All = "all"
+}
diff --git a/frontend/src/hooks/api/agentVault/index.ts b/frontend/src/hooks/api/agentVault/index.ts
new file mode 100644
index 0000000000..f49a872a5a
--- /dev/null
+++ b/frontend/src/hooks/api/agentVault/index.ts
@@ -0,0 +1,4 @@
+export * from "./enums";
+export * from "./mutations";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
new file mode 100644
index 0000000000..6011553a52
--- /dev/null
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -0,0 +1,386 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+import { useOrganization } from "@app/context";
+
+import { ApiErrorTypes } from "../types";
+import { agentVaultKeys } from "./queries";
+import {
+ TAddAgentVaultMembersDTO,
+ TAgentVaultAccessBundle,
+ TAgentVaultEnrollment,
+ TAgentVaultMintedSession,
+ TAgentVaultProductMemberActor,
+ TAgentVaultProxy,
+ TAgentVaultProxySettingsDTO,
+ TAgentVaultService,
+ TCreateAgentVaultAccessBundleDTO,
+ TCreateAgentVaultServiceDTO,
+ TCreateAgentVaultSessionDTO,
+ TUpdateAgentVaultAccessBundleDTO,
+ TUpdateAgentVaultServiceDTO
+} from "./types";
+
+export const useCreateAgentVaultAccessBundle = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (params: TCreateAgentVaultAccessBundleDTO) => {
+ const { data } = await apiRequest.post<{ accessBundle: TAgentVaultAccessBundle }>(
+ "/api/v1/agent-vault/access-bundles",
+ params
+ );
+ return data.accessBundle;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ }
+ });
+};
+
+export const useUpdateAgentVaultAccessBundle = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ accessBundleId, ...params }: TUpdateAgentVaultAccessBundleDTO) => {
+ const { data } = await apiRequest.patch<{ accessBundle: TAgentVaultAccessBundle }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}`,
+ params
+ );
+ return data.accessBundle;
+ },
+ onSuccess: (_, { accessBundleId }) => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ queryClient.invalidateQueries({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
+ });
+ }
+ });
+};
+
+export const useDeleteAgentVaultAccessBundle = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (accessBundleId: string) => {
+ const { data } = await apiRequest.delete<{ accessBundle: TAgentVaultAccessBundle }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}`
+ );
+ return data.accessBundle;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });
+ }
+ });
+};
+
+export const useCreateAgentVaultService = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ // The sheet renders a host-pattern conflict inline and hands anything else back to onRequestError,
+ // so the global toast must not also fire for it.
+ meta: { skipValidationToast: true, handledErrorCodes: [ApiErrorTypes.BadRequestError] },
+ mutationFn: async ({ accessBundleId, ...params }: TCreateAgentVaultServiceDTO) => {
+ const { data } = await apiRequest.post<{ service: TAgentVaultService }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`,
+ params
+ );
+ return data;
+ },
+ onSuccess: (_, { accessBundleId }) => {
+ queryClient.invalidateQueries({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
+ });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ }
+ });
+};
+
+export const useUpdateAgentVaultService = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ // The sheet renders a host-pattern conflict inline and hands anything else back to onRequestError,
+ // so the global toast must not also fire for it.
+ meta: { skipValidationToast: true, handledErrorCodes: [ApiErrorTypes.BadRequestError] },
+ mutationFn: async ({ accessBundleId, serviceId, ...params }: TUpdateAgentVaultServiceDTO) => {
+ const { data } = await apiRequest.patch<{ service: TAgentVaultService }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}`,
+ params
+ );
+ return data;
+ },
+ onSuccess: (_, { accessBundleId }) => {
+ queryClient.invalidateQueries({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
+ });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ }
+ });
+};
+
+export const useDeleteAgentVaultService = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ accessBundleId,
+ serviceId
+ }: {
+ accessBundleId: string;
+ serviceId: string;
+ }) => {
+ const { data } = await apiRequest.delete<{ service: { id: string; name: string } }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}`
+ );
+ return data.service;
+ },
+ onSuccess: (_, { accessBundleId }) => {
+ queryClient.invalidateQueries({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
+ });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ }
+ });
+};
+
+export const useAddAgentVaultAccessBundleMembers = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ accessBundleId, ...params }: TAddAgentVaultMembersDTO) => {
+ const { data } = await apiRequest.post<{
+ members: { id: string }[];
+ skipped: string[];
+ }>(`/api/v1/agent-vault/access-bundles/${accessBundleId}/members`, params);
+ return data;
+ },
+ onSuccess: (_, { accessBundleId }) => {
+ queryClient.invalidateQueries({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
+ });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ }
+ });
+};
+
+export const useRemoveAgentVaultAccessBundleMember = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ accessBundleId,
+ memberId
+ }: {
+ accessBundleId: string;
+ memberId: string;
+ }) => {
+ const { data } = await apiRequest.delete<{ member: { id: string } }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/members/${memberId}`
+ );
+ return data.member;
+ },
+ onSuccess: (_, { accessBundleId }) => {
+ queryClient.invalidateQueries({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
+ });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });
+ }
+ });
+};
+
+export const useCreateAgentVaultSession = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (params: TCreateAgentVaultSessionDTO) => {
+ const { data } = await apiRequest.post<{ session: TAgentVaultMintedSession }>(
+ "/api/v1/agent-vault/sessions",
+ params
+ );
+ return data.session;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });
+ }
+ });
+};
+
+export const useRevokeAgentVaultSession = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (sessionId: string) => {
+ const { data } = await apiRequest.post<{
+ session: { id: string; revokedAt: string | null };
+ }>(`/api/v1/agent-vault/sessions/${sessionId}/revoke`);
+ return data.session;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });
+ }
+ });
+};
+
+export const useCreateAgentVaultProxy = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (params: TAgentVaultProxySettingsDTO) => {
+ const { data } = await apiRequest.post<{
+ proxy: TAgentVaultProxy;
+ token: string;
+ expiresAt: string;
+ }>("/api/v1/agent-vault/proxies", params);
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.proxies(currentOrg.id) });
+ }
+ });
+};
+
+export const useUpdateAgentVaultProxy = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ proxyId,
+ ...params
+ }: Partial<TAgentVaultProxySettingsDTO> & { proxyId: string }) => {
+ const { data } = await apiRequest.patch<{ proxy: TAgentVaultProxy }>(
+ `/api/v1/agent-vault/proxies/${proxyId}`,
+ params
+ );
+ return data.proxy;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.proxies(currentOrg.id) });
+ }
+ });
+};
+
+export const useDeleteAgentVaultProxy = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (proxyId: string) => {
+ const { data } = await apiRequest.delete<{ proxy: { id: string; name: string } }>(
+ `/api/v1/agent-vault/proxies/${proxyId}`
+ );
+ return data.proxy;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.proxies(currentOrg.id) });
+ }
+ });
+};
+
+export const useReissueAgentVaultProxyEnrollmentToken = () =>
+ useMutation({
+ mutationFn: async (proxyId: string) => {
+ const { data } = await apiRequest.post<TAgentVaultEnrollment>(
+ `/api/v1/agent-vault/proxies/${proxyId}/token-auth/generate-enrollment-token`
+ );
+ return data;
+ }
+ });
+
+export const useRevokeAgentVaultProxyAccess = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (proxyId: string) => {
+ const { data } = await apiRequest.post<{ proxy: TAgentVaultProxy }>(
+ `/api/v1/agent-vault/proxies/${proxyId}/revoke`
+ );
+ return data.proxy;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.proxies(currentOrg.id) });
+ }
+ });
+};
+
+// The member is named in the URL, so a call with no actor has nowhere to go. The role dialogs pass an
+// empty actor while closed, which cannot reach a mutation, so this only fires on a genuine mistake.
+const agentVaultMemberPath = ({
+ userId,
+ groupId,
+ identityId
+}: TAgentVaultProductMemberActor): string => {
+ if (userId) return `users/${userId}`;
+ if (groupId) return `groups/${groupId}`;
+ if (identityId) return `identities/${identityId}`;
+ throw new Error("Name a user, group or machine identity");
+};
+
+const invalidateProductMembers = (
+ queryClient: ReturnType<typeof useQueryClient>,
+ orgId: string
+) => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.productMembers(orgId) });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(orgId) });
+};
+
+export const useAddAgentVaultProductUserMembers = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (dto: { userIds: string[]; emails: string[]; role: string }) => {
+ const { data } = await apiRequest.post<{
+ members: { membershipId: string; userId?: string; role: string; createdAt: string }[];
+ skipped: string[];
+ }>("/api/v1/agent-vault/memberships/users", dto);
+ return data;
+ },
+ onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)
+ });
+};
+
+// Users are added through the batch route, so this covers groups and machine identities only.
+export const useAddAgentVaultProductMember = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ role, ...actor }: TAgentVaultProductMemberActor & { role: string }) => {
+ const { data } = await apiRequest.post(
+ `/api/v1/agent-vault/memberships/${agentVaultMemberPath(actor)}`,
+ { role }
+ );
+ return data;
+ },
+ onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)
+ });
+};
+
+export const useUpdateAgentVaultProductMemberRole = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ role, ...actor }: TAgentVaultProductMemberActor & { role: string }) => {
+ const { data } = await apiRequest.patch(
+ `/api/v1/agent-vault/memberships/${agentVaultMemberPath(actor)}`,
+ { role }
+ );
+ return data;
+ },
+ onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)
+ });
+};
+
+export const useRemoveAgentVaultProductMember = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (actor: TAgentVaultProductMemberActor) => {
+ const { data } = await apiRequest.delete(
+ `/api/v1/agent-vault/memberships/${agentVaultMemberPath(actor)}`
+ );
+ return data;
+ },
+ onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)
+ });
+};
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
new file mode 100644
index 0000000000..610c7c05ad
--- /dev/null
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -0,0 +1,140 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+import { useOrganization } from "@app/context";
+
+import {
+ TAgentVaultAccessBundleDetails,
+ TAgentVaultAccessBundleListItem,
+ TAgentVaultProductGroupMember,
+ TAgentVaultProductIdentityMember,
+ TAgentVaultProductUserMember,
+ TAgentVaultProxy,
+ TAgentVaultSession,
+ TListAgentVaultSessionsDTO
+} from "./types";
+
+export const fetchAgentVaultProjectId = async () => {
+ const { data } = await apiRequest.get<{ projectId: string }>("/api/v1/agent-vault/project");
+ return data.projectId;
+};
+
+// Every key carries the org, because Agent Vault is org-scoped through the JWT rather than through a
+// path parameter: without it a switch to another org would serve the previous org's data from cache.
+export const agentVaultKeys = {
+ all: (orgId: string) => ["agent-vault", orgId] as const,
+ accessBundles: (orgId: string) => [...agentVaultKeys.all(orgId), "access-bundles"] as const,
+ accessBundle: (orgId: string, accessBundleId: string) =>
+ [...agentVaultKeys.accessBundles(orgId), accessBundleId] as const,
+ // sessions() is the invalidation prefix; folding the parameters in would put an `undefined` in it,
+ // which prefix-matches nothing.
+ sessions: (orgId: string) => [...agentVaultKeys.all(orgId), "sessions"] as const,
+ sessionList: (orgId: string, params?: TListAgentVaultSessionsDTO) =>
+ [...agentVaultKeys.sessions(orgId), params] as const,
+ proxies: (orgId: string) => [...agentVaultKeys.all(orgId), "proxies"] as const,
+ productMembers: (orgId: string) => [...agentVaultKeys.all(orgId), "product-members"] as const,
+ productUserMembers: (orgId: string) =>
+ [...agentVaultKeys.productMembers(orgId), "users"] as const,
+ productGroupMembers: (orgId: string) =>
+ [...agentVaultKeys.productMembers(orgId), "groups"] as const,
+ productIdentityMembers: (orgId: string) =>
+ [...agentVaultKeys.productMembers(orgId), "identities"] as const
+};
+
+const fetchProductMembers = async <T,>(path: string) => {
+ const { data } = await apiRequest.get<{ members: T[] }>(
+ `/api/v1/agent-vault/memberships/${path}`
+ );
+ return data.members;
+};
+
+export const useListAgentVaultProductUserMembers = (enabled = true) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.productUserMembers(currentOrg.id),
+ queryFn: () => fetchProductMembers<TAgentVaultProductUserMember>("users"),
+ enabled
+ });
+};
+
+export const useListAgentVaultProductGroupMembers = (enabled = true) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.productGroupMembers(currentOrg.id),
+ queryFn: () => fetchProductMembers<TAgentVaultProductGroupMember>("groups"),
+ enabled
+ });
+};
+
+export const useListAgentVaultProductIdentityMembers = (enabled = true) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.productIdentityMembers(currentOrg.id),
+ queryFn: () => fetchProductMembers<TAgentVaultProductIdentityMember>("identities"),
+ enabled
+ });
+};
+
+export const useListAgentVaultAccessBundles = () => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.accessBundles(currentOrg.id),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ accessBundles: TAgentVaultAccessBundleListItem[];
+ }>("/api/v1/agent-vault/access-bundles");
+ return data.accessBundles;
+ }
+ });
+};
+
+export const useGetAgentVaultAccessBundle = (accessBundleId: string) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ accessBundle: TAgentVaultAccessBundleDetails }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}`
+ );
+ return data.accessBundle;
+ },
+ enabled: Boolean(accessBundleId)
+ });
+};
+
+export const useListAgentVaultSessions = (params?: TListAgentVaultSessionsDTO) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.sessionList(currentOrg.id, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ sessions: TAgentVaultSession[];
+ totalCount: number;
+ }>("/api/v1/agent-vault/sessions", { params });
+ return data;
+ },
+ refetchInterval: 30_000,
+ placeholderData: (prev) => prev
+ });
+};
+
+export const useListAgentVaultProxies = () => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.proxies(currentOrg.id),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ proxies: TAgentVaultProxy[] }>(
+ "/api/v1/agent-vault/proxies"
+ );
+ return data.proxies;
+ },
+ refetchInterval: 30_000
+ });
+};
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
new file mode 100644
index 0000000000..277839be56
--- /dev/null
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -0,0 +1,206 @@
+import {
+ AgentVaultCredentialType,
+ AgentVaultSessionScope,
+ AgentVaultSessionStatus,
+ AgentVaultTrafficPolicy
+} from "./enums";
+
+export type TAgentVaultCredentialSummary =
+ | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }
+ | { type: AgentVaultCredentialType.Basic }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type TAgentVaultCredentialInput =
+ | {
+ type: AgentVaultCredentialType.Bearer;
+ headerName?: string;
+ headerPrefix?: string;
+ value: string;
+ }
+ | { type: AgentVaultCredentialType.Basic; username: string; password: string }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type TAgentVaultCredentialUpdate =
+ | {
+ type: AgentVaultCredentialType.Bearer;
+ headerName?: string;
+ headerPrefix?: string;
+ value?: string;
+ }
+ | { type: AgentVaultCredentialType.Basic; username?: string; password?: string }
+ | { type: AgentVaultCredentialType.Passthrough };
+
+export type TAgentVaultService = {
+ id: string;
+ accessBundleId: string;
+ name: string;
+ hostPattern: string;
+ credential: TAgentVaultCredentialSummary;
+ createdAt: string;
+};
+
+export type TAgentVaultMember = {
+ id: string;
+ userId: string | null;
+ identityId: string | null;
+ groupId: string | null;
+ createdAt: string;
+ user: {
+ username: string;
+ email: string | null;
+ firstName: string | null;
+ lastName: string | null;
+ } | null;
+ identity: { name: string } | null;
+ group: { name: string } | null;
+};
+
+export type TAgentVaultAccessBundle = {
+ id: string;
+ name: string;
+ description?: string | null;
+ createdAt: string;
+};
+
+export type TAgentVaultAccessBundleListItem = TAgentVaultAccessBundle & {
+ serviceCount: number;
+ memberCount: number;
+ hostPatterns: string[];
+};
+
+export type TAgentVaultAccessBundleDetails = TAgentVaultAccessBundle & {
+ services: TAgentVaultService[];
+ members?: TAgentVaultMember[];
+};
+
+export type TAgentVaultSessionAccessBundle = {
+ id: string | null;
+ name: string;
+ position: number;
+};
+
+export type TAgentVaultSession = {
+ id: string;
+ userId: string | null;
+ identityId: string | null;
+ actorName: string;
+ actorEmail: string | null;
+ status: AgentVaultSessionStatus;
+ expiresAt: string | null;
+ revokedAt: string | null;
+ createdAt: string;
+ accessBundles: TAgentVaultSessionAccessBundle[];
+};
+
+export type TAgentVaultMintedSession = {
+ id: string;
+ token: string;
+ expiresAt: string | null;
+ createdAt: string;
+ accessBundles: TAgentVaultSessionAccessBundle[];
+};
+
+export type TAgentVaultProxy = {
+ id: string;
+ name: string;
+ heartbeat: string | null;
+ isHealthy: boolean;
+ rootCaFingerprint: string | null;
+ rootCaExpiresAt: string | null;
+ trafficPolicy?: AgentVaultTrafficPolicy;
+ allowedHosts?: string | null;
+ pollInterval?: number;
+ createdAt?: string;
+};
+
+export type TAgentVaultEnrollment = {
+ token: string;
+ expiresAt: string;
+};
+
+export type TListAgentVaultSessionsDTO = {
+ scope?: AgentVaultSessionScope;
+ status?: AgentVaultSessionStatus;
+ limit?: number;
+ offset?: number;
+ search?: string;
+};
+
+export type TCreateAgentVaultAccessBundleDTO = {
+ name: string;
+ description?: string;
+};
+
+export type TUpdateAgentVaultAccessBundleDTO = {
+ accessBundleId: string;
+ name?: string;
+ description?: string | null;
+};
+
+export type TCreateAgentVaultServiceDTO = {
+ accessBundleId: string;
+ name: string;
+ hostPattern: string;
+ credential: TAgentVaultCredentialInput;
+};
+
+export type TUpdateAgentVaultServiceDTO = {
+ accessBundleId: string;
+ serviceId: string;
+ name?: string;
+ hostPattern?: string;
+ credential?: TAgentVaultCredentialUpdate;
+};
+
+export type TAddAgentVaultMembersDTO = {
+ accessBundleId: string;
+ userIds: string[];
+ identityIds: string[];
+ groupIds: string[];
+};
+
+export type TCreateAgentVaultSessionDTO = {
+ accessBundles: string[];
+ ttl: string;
+};
+
+export type TAgentVaultProxySettingsDTO = {
+ name: string;
+ trafficPolicy?: AgentVaultTrafficPolicy;
+ allowedHosts?: string | null;
+ pollInterval?: number;
+};
+
+export type TAgentVaultProductMember = {
+ membershipId: string;
+ userId: string | null;
+ groupId: string | null;
+ identityId: string | null;
+ role: string;
+ isActive: boolean;
+ createdAt: string;
+};
+
+export type TAgentVaultProductUserMember = TAgentVaultProductMember & {
+ email: string | null;
+ username: string;
+ firstName: string | null;
+ lastName: string | null;
+ isOrgMembershipPending: boolean;
+};
+
+export type TAgentVaultProductGroupMember = TAgentVaultProductMember & {
+ name: string;
+};
+
+export type TAgentVaultProductIdentityMember = TAgentVaultProductMember & {
+ name: string;
+ identityProjectId: string | null;
+ identityOrgId: string | null;
+};
+
+export type TAgentVaultProductMemberActor = {
+ userId?: string;
+ groupId?: string;
+ identityId?: string;
+};
diff --git a/frontend/src/hooks/api/auditLogStreams/enums.ts b/frontend/src/hooks/api/auditLogStreams/enums.ts
index 139d4fef2e..426fd790d4 100644
--- a/frontend/src/hooks/api/auditLogStreams/enums.ts
+++ b/frontend/src/hooks/api/auditLogStreams/enums.ts
@@ -25,5 +25,6 @@ export enum AuditLogStreamProduct {
KMS = "kms",
SecretScanning = "secret-scanning",
PAM = "pam",
+ AgentVault = "agent-vault",
Organization = "organization"
}
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index ce4095e9bb..12eac7147a 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -455,7 +455,27 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CREATE_SECRET_FOLDER_ACCESS]: "Grant folder access",
[EventType.UPDATE_SECRET_FOLDER_ACCESS]: "Update folder access",
- [EventType.DELETE_SECRET_FOLDER_ACCESS]: "Revoke folder access"
+ [EventType.DELETE_SECRET_FOLDER_ACCESS]: "Revoke folder access",
+
+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_CREATE]: "Create access bundle",
+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_UPDATE]: "Update access bundle",
+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_DELETE]: "Delete access bundle",
+ [EventType.AGENT_VAULT_SERVICE_CREATE]: "Create service",
+ [EventType.AGENT_VAULT_SERVICE_UPDATE]: "Update service",
+ [EventType.AGENT_VAULT_SERVICE_DELETE]: "Delete service",
+ [EventType.AGENT_VAULT_MEMBER_ADD]: "Add member",
+ [EventType.AGENT_VAULT_MEMBER_UPDATE]: "Change member role",
+ [EventType.AGENT_VAULT_MEMBER_REMOVE]: "Remove member",
+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD]: "Grant access bundle",
+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE]: "Revoke access bundle",
+ [EventType.AGENT_VAULT_SESSION_MINT]: "Create session",
+ [EventType.AGENT_VAULT_SESSION_REVOKE]: "Revoke session",
+ [EventType.AGENT_VAULT_PROXY_REGISTER]: "Create proxy",
+ [EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE]: "Generate proxy enrollment token",
+ [EventType.AGENT_VAULT_PROXY_ENROLL]: "Enroll proxy",
+ [EventType.AGENT_VAULT_PROXY_UPDATE]: "Update proxy",
+ [EventType.AGENT_VAULT_PROXY_REVOKE]: "Revoke proxy access",
+ [EventType.AGENT_VAULT_PROXY_DELETE]: "Delete proxy"
};
export const userAgentTypeToNameMap: { [K in UserAgentType]: string } = {
@@ -508,5 +528,26 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.PAM_DISCOVERY_SOURCE_DELETE,
EventType.PAM_DISCOVERY_SCAN,
EventType.PAM_DISCOVERED_ACCOUNT_IMPORT
+ ],
+ [ProjectType.AgentVault]: [
+ EventType.AGENT_VAULT_ACCESS_BUNDLE_CREATE,
+ EventType.AGENT_VAULT_ACCESS_BUNDLE_UPDATE,
+ EventType.AGENT_VAULT_ACCESS_BUNDLE_DELETE,
+ EventType.AGENT_VAULT_SERVICE_CREATE,
+ EventType.AGENT_VAULT_SERVICE_UPDATE,
+ EventType.AGENT_VAULT_SERVICE_DELETE,
+ EventType.AGENT_VAULT_MEMBER_ADD,
+ EventType.AGENT_VAULT_MEMBER_UPDATE,
+ EventType.AGENT_VAULT_MEMBER_REMOVE,
+ EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD,
+ EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,
+ EventType.AGENT_VAULT_SESSION_MINT,
+ EventType.AGENT_VAULT_SESSION_REVOKE,
+ EventType.AGENT_VAULT_PROXY_REGISTER,
+ EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE,
+ EventType.AGENT_VAULT_PROXY_ENROLL,
+ EventType.AGENT_VAULT_PROXY_UPDATE,
+ EventType.AGENT_VAULT_PROXY_REVOKE,
+ EventType.AGENT_VAULT_PROXY_DELETE
]
};
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index fe2ad071ca..e61a136b08 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -7,6 +7,7 @@ export enum ActorType {
ACME_PROFILE = "acmeProfile",
ACME_ACCOUNT = "acmeAccount",
EST_ACCOUNT = "estAccount",
+ AGENT_VAULT_PROXY = "agentVaultProxy",
UNKNOWN_USER = "unknownUser"
}
@@ -452,5 +453,25 @@ export enum EventType {
// Secret folder access (folder RBAC)
CREATE_SECRET_FOLDER_ACCESS = "create-secret-folder-access",
UPDATE_SECRET_FOLDER_ACCESS = "update-secret-folder-access",
- DELETE_SECRET_FOLDER_ACCESS = "delete-secret-folder-access"
+ DELETE_SECRET_FOLDER_ACCESS = "delete-secret-folder-access",
+
+ AGENT_VAULT_ACCESS_BUNDLE_CREATE = "agent-vault-access-bundle-create",
+ AGENT_VAULT_ACCESS_BUNDLE_UPDATE = "agent-vault-access-bundle-update",
+ AGENT_VAULT_ACCESS_BUNDLE_DELETE = "agent-vault-access-bundle-delete",
+ AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",
+ AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",
+ AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",
+ AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",
+ AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",
+ AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",
+ AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD = "agent-vault-access-bundle-member-add",
+ AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",
+ AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",
+ AGENT_VAULT_SESSION_REVOKE = "agent-vault-session-revoke",
+ AGENT_VAULT_PROXY_REGISTER = "agent-vault-proxy-register",
+ AGENT_VAULT_PROXY_TOKEN_REISSUE = "agent-vault-proxy-token-reissue",
+ AGENT_VAULT_PROXY_ENROLL = "agent-vault-proxy-enroll",
+ AGENT_VAULT_PROXY_UPDATE = "agent-vault-proxy-update",
+ AGENT_VAULT_PROXY_REVOKE = "agent-vault-proxy-revoke",
+ AGENT_VAULT_PROXY_DELETE = "agent-vault-proxy-delete"
}
diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsx
index 6caf657f87..2798bc3393 100644
--- a/frontend/src/hooks/api/auditLogs/types.tsx
+++ b/frontend/src/hooks/api/auditLogs/types.tsx
@@ -100,6 +100,11 @@ export interface EstAccountActor {
metadata: EstAccountActorMetadata;
}
+export interface AgentVaultProxyActor {
+ type: ActorType.AGENT_VAULT_PROXY;
+ metadata: { agentVaultProxyId: string };
+}
+
export type Actor =
| UserActor
| ServiceActor
@@ -109,7 +114,8 @@ export type Actor =
| KmipClientActor
| AcmeProfileActor
| AcmeAccountActor
- | EstAccountActor;
+ | EstAccountActor
+ | AgentVaultProxyActor;
interface GetSecretsEvent {
type: EventType.GET_SECRETS;
diff --git a/frontend/src/hooks/api/auth/types.ts b/frontend/src/hooks/api/auth/types.ts
index f2fdc8ada3..e5d44fb106 100644
--- a/frontend/src/hooks/api/auth/types.ts
+++ b/frontend/src/hooks/api/auth/types.ts
@@ -120,15 +120,24 @@ export type SignupOnboardingDTO = {
| "kms"
| "secret-scanning"
| "pam"
+ | "agent-vault"
| "exploring";
/** An empty array means "just exploring". */
- selectedProducts?: ("secret-manager" | "cert-manager" | "kms" | "secret-scanning" | "pam")[];
+ selectedProducts?: (
+ | "secret-manager"
+ | "cert-manager"
+ | "kms"
+ | "secret-scanning"
+ | "pam"
+ | "agent-vault"
+ )[];
launchDestination?:
| "secret-manager"
| "cert-manager"
| "kms"
| "secret-scanning"
| "pam"
+ | "agent-vault"
| "organization-overview";
attributionSource?: string;
};
diff --git a/frontend/src/hooks/api/orgAdmin/index.tsx b/frontend/src/hooks/api/orgAdmin/index.tsx
index c0fead35c6..2580836524 100644
--- a/frontend/src/hooks/api/orgAdmin/index.tsx
+++ b/frontend/src/hooks/api/orgAdmin/index.tsx
@@ -1 +1 @@
-export { useOrgAdminAccessProject } from "./mutation";
+export { grantOrgAdminProjectAccess, useOrgAdminAccessProject } from "./mutation";
diff --git a/frontend/src/hooks/api/orgAdmin/mutation.tsx b/frontend/src/hooks/api/orgAdmin/mutation.tsx
index 9565eb417c..7553e860cb 100644
--- a/frontend/src/hooks/api/orgAdmin/mutation.tsx
+++ b/frontend/src/hooks/api/orgAdmin/mutation.tsx
@@ -5,16 +5,18 @@ import { projectKeys } from "@app/hooks/api/projects/query-keys";
import { TOrgAdminAccessProjectDTO } from "./types";
+export const grantOrgAdminProjectAccess = async ({ projectId }: TOrgAdminAccessProjectDTO) => {
+ const { data } = await apiRequest.post(
+ `/api/v1/organization-admin/projects/${projectId}/grant-admin-access`
+ );
+ return data;
+};
+
export const useOrgAdminAccessProject = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ projectId }: TOrgAdminAccessProjectDTO) => {
- const { data } = await apiRequest.post(
- `/api/v1/organization-admin/projects/${projectId}/grant-admin-access`
- );
- return data;
- },
+ mutationFn: grantOrgAdminProjectAccess,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: projectKeys.allProjectQueries() });
}
diff --git a/frontend/src/hooks/api/organization/types.ts b/frontend/src/hooks/api/organization/types.ts
index af9daf2110..db9d8a00d7 100644
--- a/frontend/src/hooks/api/organization/types.ts
+++ b/frontend/src/hooks/api/organization/types.ts
@@ -40,6 +40,7 @@ export type Organization = {
rootOrgId: string | null;
secretShareBrandConfig?: TSecretShareBrandConfig;
pamProjectId: string | null;
+ agentVaultProjectId: string | null;
};
export type UpdateOrgDTO = {
@@ -118,4 +119,9 @@ export type TOrgProductStats = {
accountTemplatesCount: number;
foldersCount: number;
};
+ agentVault: {
+ accessBundlesCount: number;
+ servicesCount: number;
+ proxiesCount: number;
+ };
};
diff --git a/frontend/src/hooks/api/projects/types.ts b/frontend/src/hooks/api/projects/types.ts
index 3ab59728a1..4f1dd949f3 100644
--- a/frontend/src/hooks/api/projects/types.ts
+++ b/frontend/src/hooks/api/projects/types.ts
@@ -13,7 +13,8 @@ export enum ProjectType {
CertificateManager = "cert-manager",
KMS = "kms",
SecretScanning = "secret-scanning",
- PAM = "pam"
+ PAM = "pam",
+ AgentVault = "agent-vault"
}
export enum ProjectUserMembershipTemporaryMode {
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index 6386ee33fb..ab1f0a7d80 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -192,6 +192,7 @@ export const useAddUsersToOrg = () => {
grantFailures?: {
projectIds: string[];
pamAccess: boolean;
+ agentVaultAccess: boolean;
};
};
};
diff --git a/frontend/src/hooks/api/users/types.ts b/frontend/src/hooks/api/users/types.ts
index d579e84439..d9de01b0e7 100644
--- a/frontend/src/hooks/api/users/types.ts
+++ b/frontend/src/hooks/api/users/types.ts
@@ -185,6 +185,7 @@ export type AddUserToOrgDTO = {
projectIds?: string[];
/** Also grant invitees member access to the org's PAM product. */
grantPamAccess?: boolean;
+ grantAgentVaultAccess?: boolean;
};
export type CreateAPIKeyRes = {
diff --git a/frontend/src/hooks/index.ts b/frontend/src/hooks/index.ts
index 6f7fca075f..14e8f9b1dd 100644
--- a/frontend/src/hooks/index.ts
+++ b/frontend/src/hooks/index.ts
@@ -5,6 +5,8 @@ export {
export { useDebounce } from "./useDebounce";
export { useDiscardChangesGuard } from "./useDiscardChangesGuard";
export * from "./useGetProjectTypeFromRoute";
+export { useImplicitProduct } from "./useImplicitProduct";
+export { useImplicitProjectId } from "./useImplicitProjectId";
export { useLastLogin } from "./useLastLogin";
export { useLocalStorageState } from "./useLocalStorageState";
export { useOnboarding } from "./useOnboarding";
@@ -17,4 +19,6 @@ export { useScopeVariant } from "./useScopeVariant";
export { useSecretsActivationNudge } from "./useSecretsActivationNudge";
export { useSyntaxHighlight } from "./useSyntaxHighlight";
export { useTimedReset } from "./useTimedReset";
+export { useTimeRemaining } from "./useTimeRemaining";
export { useToggle } from "./useToggle";
+export { useWizardSteps } from "./useWizardSteps";
diff --git a/frontend/src/hooks/useImplicitProduct.ts b/frontend/src/hooks/useImplicitProduct.ts
new file mode 100644
index 0000000000..da5a39fc4e
--- /dev/null
+++ b/frontend/src/hooks/useImplicitProduct.ts
@@ -0,0 +1,19 @@
+import { useRouterState } from "@tanstack/react-router";
+
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+// The org-scoped products (PAM, Agent Vault) carry no $projectId in the URL, so their layouts publish
+// what they are into route context. Reading that rather than the pathname is what keeps this in step
+// with useParams, which every other product's gate already uses: the router changes location before it
+// swaps matches, so a pathname read answers yes on the way in and no on the way out a frame early, and
+// anything gated on it mounts or unmounts out of step with the project it needs.
+export const useImplicitProduct = (): ProjectType | null =>
+ useRouterState({
+ select: (state) => {
+ for (let i = state.matches.length - 1; i >= 0; i -= 1) {
+ const { implicitProductType } = state.matches[i].context;
+ if (implicitProductType) return implicitProductType;
+ }
+ return null;
+ }
+ });
diff --git a/frontend/src/hooks/useImplicitProjectId.ts b/frontend/src/hooks/useImplicitProjectId.ts
new file mode 100644
index 0000000000..19eed7a6f6
--- /dev/null
+++ b/frontend/src/hooks/useImplicitProjectId.ts
@@ -0,0 +1,15 @@
+import { useRouterState } from "@tanstack/react-router";
+
+// PAM and Agent Vault carry no $projectId in the URL, so their layouts publish the id they resolved in
+// beforeLoad. Every gate that decides whether a useProject caller renders reads the matched routes too
+// (see useImplicitProduct), so the id and the gate move together.
+export const useImplicitProjectId = () =>
+ useRouterState({
+ select: (state) => {
+ for (let i = state.matches.length - 1; i >= 0; i -= 1) {
+ const { implicitProjectId } = state.matches[i].context;
+ if (implicitProjectId) return implicitProjectId;
+ }
+ return null;
+ }
+ });
diff --git a/frontend/src/hooks/useScopeVariant.ts b/frontend/src/hooks/useScopeVariant.ts
index bf5c972ae7..efa616e0bf 100644
--- a/frontend/src/hooks/useScopeVariant.ts
+++ b/frontend/src/hooks/useScopeVariant.ts
@@ -1,18 +1,22 @@
-import { useParams } from "@tanstack/react-router";
+import { useLocation, useParams } from "@tanstack/react-router";
import { useOrganization } from "@app/context";
+import { getOrgScopedProductFromPath } from "@app/helpers/project";
+import { ProjectType } from "@app/hooks/api/projects/types";
-export type ScopeVariant = "org" | "project" | "sub-org";
+export type ScopeVariant = "org" | "project" | "sub-org" | "av";
/**
- * Returns the scope-coloured variant ("org" | "project" | "sub-org") to pass to
- * v3 components (Button, TabsList, IconButton, etc.) so they match the
- * surrounding page chrome.
+ * Returns the scope-coloured variant to pass to v3 components (Button, TabsList, IconButton, etc.) so
+ * they match the surrounding page chrome. An org-scoped product has no projectId in its URL, so it is
+ * read from the pathname instead, or its pages would take the org colour.
*/
export const useScopeVariant = (): ScopeVariant => {
const { projectId } = useParams({ strict: false });
+ const { pathname } = useLocation();
const { isSubOrganization } = useOrganization();
+ if (getOrgScopedProductFromPath(pathname) === ProjectType.AgentVault) return "av";
if (projectId) return "project";
if (isSubOrganization) return "sub-org";
return "org";
diff --git a/frontend/src/hooks/useTimeRemaining.ts b/frontend/src/hooks/useTimeRemaining.ts
new file mode 100644
index 0000000000..f3864a4fff
--- /dev/null
+++ b/frontend/src/hooks/useTimeRemaining.ts
@@ -0,0 +1,31 @@
+import { useEffect, useState } from "react";
+
+const formatRemaining = (remainingSeconds: number) => {
+ const hours = Math.floor(remainingSeconds / 3600);
+ const minutes = Math.floor((remainingSeconds % 3600) / 60);
+ const seconds = remainingSeconds % 60;
+
+ if (hours > 0) return `${hours}h ${minutes}m remaining`;
+ return `${minutes}m ${seconds}s remaining`;
+};
+
+/** Live countdown to an expiry, ticking every second. */
+export const useTimeRemaining = (expiresAt?: string | null) => {
+ // Date.now() at render, not at mount: a value seeded once would render the first frame stale.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => setNow(Date.now()), [expiresAt]);
+
+ useEffect(() => {
+ if (!expiresAt) return undefined;
+
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [expiresAt]);
+
+ if (!expiresAt) return { label: "", isExpired: false };
+
+ const remainingSeconds = Math.max(0, Math.ceil((new Date(expiresAt).getTime() - now) / 1000));
+ if (remainingSeconds === 0) return { label: "Expired", isExpired: true };
+
+ return { label: formatRemaining(remainingSeconds), isExpired: false };
+};
diff --git a/frontend/src/hooks/useWizardSteps.ts b/frontend/src/hooks/useWizardSteps.ts
new file mode 100644
index 0000000000..c913ce5f98
--- /dev/null
+++ b/frontend/src/hooks/useWizardSteps.ts
@@ -0,0 +1,49 @@
+import { useCallback, useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+
+export const useWizardSteps = <TStepKey extends string>({
+ stepKeys,
+ stepFields,
+ invalidMessage,
+ validateStep
+}: {
+ stepKeys: readonly TStepKey[];
+ stepFields: Record<TStepKey, string[]>;
+ invalidMessage: string;
+ validateStep?: (fields: string[]) => Promise<boolean>;
+}) => {
+ const [step, setStep] = useState(0);
+ const activeStep = Math.min(step, stepKeys.length - 1);
+
+ const goBack = useCallback(() => setStep(Math.max(0, activeStep - 1)), [activeStep]);
+ const goNext = useCallback(async () => {
+ if (validateStep && !(await validateStep(stepFields[stepKeys[activeStep]]))) {
+ createNotification({ text: "Fix the errors on this step to continue.", type: "error" });
+ return;
+ }
+ setStep(Math.min(stepKeys.length - 1, activeStep + 1));
+ }, [stepKeys, stepFields, activeStep, validateStep]);
+
+ const onFormInvalid = useCallback(
+ (errors: Record<string, unknown>) => {
+ const errorKeys = Object.keys(errors);
+ const idx = stepKeys.findIndex((key) =>
+ stepFields[key].some((name) => errorKeys.includes(name))
+ );
+ if (idx >= 0) setStep(idx);
+ createNotification({ text: invalidMessage, type: "error" });
+ },
+ [stepKeys, stepFields, invalidMessage]
+ );
+
+ return {
+ step: activeStep,
+ setStep,
+ currentStepKey: stepKeys[activeStep],
+ isLastStep: activeStep === stepKeys.length - 1,
+ goBack,
+ goNext,
+ onFormInvalid
+ };
+};
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 99c03fa201..ce44f71c43 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -107,6 +107,7 @@
--color-product-kms: #34edbf;
--color-product-ss: #b056f0;
--color-product-pam: #ff3568;
+ --color-product-av: #a1d434;
--color-admin: #c0c0c8;
--color-neutral: #adaeb0;
--color-border: #2b2c30;
diff --git a/frontend/src/layouts/AgentVaultLayout/AgentVaultLayout.tsx b/frontend/src/layouts/AgentVaultLayout/AgentVaultLayout.tsx
new file mode 100644
index 0000000000..771ef42c97
--- /dev/null
+++ b/frontend/src/layouts/AgentVaultLayout/AgentVaultLayout.tsx
@@ -0,0 +1,16 @@
+import { Outlet } from "@tanstack/react-router";
+
+import { useProjectPermission } from "@app/context";
+
+import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
+
+export const AgentVaultLayout = () => {
+ const { assumedPrivilegeDetails } = useProjectPermission();
+
+ return (
+ <>
+ {assumedPrivilegeDetails && <AssumePrivilegeModeBanner />}
+ <Outlet />
+ </>
+ );
+};
diff --git a/frontend/src/layouts/AgentVaultLayout/index.tsx b/frontend/src/layouts/AgentVaultLayout/index.tsx
new file mode 100644
index 0000000000..cd6f1afc5c
--- /dev/null
+++ b/frontend/src/layouts/AgentVaultLayout/index.tsx
@@ -0,0 +1 @@
+export { AgentVaultLayout } from "./AgentVaultLayout";
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
index 75d0296156..d6946b47a2 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
@@ -67,6 +67,7 @@ import {
} from "@app/context";
import { OrgPermissionSubOrgActions } from "@app/context/OrgPermissionContext/types";
import { isInfisicalCloud } from "@app/helpers/platform";
+import { getOrgScopedProductFromPath } from "@app/helpers/project";
import { useToggle } from "@app/hooks";
import {
adminQueryKeys,
@@ -78,6 +79,8 @@ import {
import { appConnectionKeys } from "@app/hooks/api/appConnections";
import { authKeys, selectOrganization } from "@app/hooks/api/auth/queries";
import { MfaMethod } from "@app/hooks/api/auth/types";
+import { pamKeys } from "@app/hooks/api/pam";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { getAuthToken } from "@app/hooks/api/reactQuery";
import { getSubscriptionPlanLabel } from "@app/hooks/api/subscriptions";
import { Organization } from "@app/hooks/api/types";
@@ -223,6 +226,8 @@ export const Navbar = () => {
queryClient.removeQueries({ queryKey: authKeys.getAuthToken });
queryClient.removeQueries({ queryKey: subOrgQuery.queryKey });
queryClient.removeQueries({ queryKey: appConnectionKeys.all });
+ // PAM's keys carry no org, so a stale entry would render another org's data until it goes stale.
+ queryClient.removeQueries({ queryKey: pamKeys.all });
await queryClient.refetchQueries({ queryKey: authKeys.getAuthToken });
await queryClient.refetchQueries({ queryKey: adminQueryKeys.serverConfig() });
@@ -304,9 +309,11 @@ export const Navbar = () => {
const isServerAdminPanel = location.pathname.startsWith("/admin");
- const isPamScope = location.pathname.startsWith(`/organizations/${currentOrg.id}/pam/`);
+ const orgScopedProduct = getOrgScopedProductFromPath(location.pathname);
+ const isPamScope = orgScopedProduct === ProjectType.PAM;
+ const isAgentVaultScope = orgScopedProduct === ProjectType.AgentVault;
const isProjectScope =
- isPamScope ||
+ Boolean(orgScopedProduct) ||
(location.pathname.startsWith(`/organizations/${currentOrg.id}/projects`) &&
location.pathname !== `/organizations/${currentOrg.id}/projects`);
@@ -344,7 +351,8 @@ export const Navbar = () => {
"z-10 flex min-h-12 items-center border-b border-border bg-gradient-to-br to-transparent",
isServerAdminPanel && "from-admin/5",
!isServerAdminPanel && isPamScope && "from-product-pam/5",
- !isServerAdminPanel && isProjectScope && !isPamScope && "from-project/5",
+ !isServerAdminPanel && isAgentVaultScope && "from-product-av/5",
+ !isServerAdminPanel && isProjectScope && !orgScopedProduct && "from-project/5",
!isServerAdminPanel && !isProjectScope && isSubOrganization && "from-sub-org/5",
!isServerAdminPanel && !isProjectScope && !isSubOrganization && "from-org/5"
)}
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
new file mode 100644
index 0000000000..c5fb4be733
--- /dev/null
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
@@ -0,0 +1,46 @@
+import { FileText, IdCard, Package, Route, Shield } from "lucide-react";
+
+import { SidebarCollapsibleGroup } from "@app/components/v3";
+import { useProjectPermission } from "@app/context";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { ProjectNavList } from "./ProjectNavLink";
+import type { NavItem, Submenu } from "./types";
+
+export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) => void }) => {
+ const { hasProjectRole } = useProjectPermission();
+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+
+ const accessItems: NavItem[] = [
+ { label: "Sessions", icon: IdCard, pathSuffix: "sessions" },
+ { label: "Access Bundles", icon: Package, pathSuffix: "access-bundles" }
+ ];
+
+ const governanceItems: NavItem[] = isAdmin
+ ? [
+ { label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },
+ {
+ label: "Access Control",
+ icon: Shield,
+ pathSuffix: "access-management",
+ activeMatch: /\/access-management|\/groups\/|\/identities\/|\/members\/|\/roles\//
+ }
+ ]
+ : [];
+
+ const infrastructureItems: NavItem[] = [{ label: "Proxies", icon: Route, pathSuffix: "proxies" }];
+
+ return (
+ <>
+ <ProjectNavList items={accessItems} onSubmenuOpen={onSubmenuOpen} />
+ {governanceItems.length > 0 && (
+ <SidebarCollapsibleGroup label="Governance">
+ <ProjectNavList items={governanceItems} onSubmenuOpen={onSubmenuOpen} />
+ </SidebarCollapsibleGroup>
+ )}
+ <SidebarCollapsibleGroup label="Infrastructure">
+ <ProjectNavList items={infrastructureItems} onSubmenuOpen={onSubmenuOpen} />
+ </SidebarCollapsibleGroup>
+ </>
+ );
+};
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx
index b1995167cf..b649e5199b 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx
@@ -7,6 +7,8 @@ import {
parseProjectSlugFromPath,
urlSlugToProjectType
} from "@app/helpers/project";
+import { useImplicitProduct } from "@app/hooks";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { OrgNav } from "./OrgNav";
import { ProjectNav } from "./ProjectNav";
@@ -23,8 +25,8 @@ export const OrgSidebar = () => {
})
});
const { pathname } = useLocation();
- const isPamRoute = pathname.includes("/pam/");
- const isInsideProject = Boolean(projectId) || isPamRoute;
+ const orgScopedProduct = useImplicitProduct();
+ const isInsideProject = Boolean(projectId) || Boolean(orgScopedProduct);
// The org-wide KMIP servers and Secret Sharing pages live at literal /projects/<slug>/<resource>
// paths with no $type route param, so fall back to parsing the product slug from the pathname.
const effectiveTypeSlug = typeSlug ?? parseProjectSlugFromPath(pathname);
@@ -33,8 +35,9 @@ export const OrgSidebar = () => {
!isInsideProject && Boolean(projectType) && hasIntermediateProjectsView(projectType!);
const { isSubOrganization } = useOrganization();
- let scope: "project" | "sub-org" | "org" | "pam" = "org";
- if (isPamRoute) scope = "pam";
+ let scope: "project" | "sub-org" | "org" | "pam" | "agent-vault" = "org";
+ if (orgScopedProduct === ProjectType.PAM) scope = "pam";
+ else if (orgScopedProduct === ProjectType.AgentVault) scope = "agent-vault";
else if (isInsideProject || isOnProjectTypeListing) scope = "project";
else if (isSubOrganization) scope = "sub-org";
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
index 443448cfd2..b85015e012 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
@@ -5,9 +5,14 @@ import { AnimatePresence, motion } from "motion/react";
import { SidebarGroup, SidebarGroupLabel } from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
-import { hasIntermediateProjectsView, projectTypeToUrlSlug } from "@app/helpers/project";
+import {
+ hasIntermediateProjectsView,
+ isOrgScopedProduct,
+ projectTypeToUrlSlug
+} from "@app/helpers/project";
import { ProjectType } from "@app/hooks/api/projects/types";
+import { AgentVaultNav } from "./AgentVaultNav";
import { CertManagerNav } from "./CertManagerNav";
import { KmsNav } from "./KmsNav";
import { PamNav } from "./PamNav";
@@ -33,7 +38,8 @@ const PROJECT_NAV_COMPONENT: Record<
[ProjectType.KMS]: KmsNav,
[ProjectType.CertificateManager]: CertManagerNav,
[ProjectType.PAM]: PamNav,
- [ProjectType.SecretScanning]: SecretScanningNav
+ [ProjectType.SecretScanning]: SecretScanningNav,
+ [ProjectType.AgentVault]: AgentVaultNav
};
// --- Project nav wrapper ---
@@ -72,6 +78,7 @@ export const ProjectNav = () => {
if (isLegacyView || hasApplicationContext || isFromRootRequests || hasSignerContext)
return null;
if (isCertManager && (isOnAccessControl || pathname.includes("/discovery"))) return null;
+ if (isOnAccessControl && currentProject.type === ProjectType.AgentVault) return null;
// PAM navigation is handled separately by PamNav.
if (currentProject.type === ProjectType.PAM) return null;
// Secret manager renders access control as in-page tabs (no secondary submenu).
@@ -96,17 +103,17 @@ export const ProjectNav = () => {
const handleSubmenuOpen = (submenu: Submenu) => {
setActiveSubmenu(submenu);
const typePath = PROJECT_TYPE_PATH[currentProject.type];
- const isPam = currentProject.type === ProjectType.PAM;
+ const isOrgScoped = isOrgScopedProduct(currentProject.type);
// Already on this submenu's page (e.g. after collapsing via the "< back" button):
// re-navigating to the same URL would push a duplicate history entry, so just re-expand.
- const submenuPath = isPam
- ? `/organizations/${currentOrg.id}/pam/${submenu.pathSuffix}`
+ const submenuPath = isOrgScoped
+ ? `/organizations/${currentOrg.id}/${typePath}/${submenu.pathSuffix}`
: `/organizations/${currentOrg.id}/projects/${typePath}/${currentProject.id}/${submenu.pathSuffix}`;
if (pathname === submenuPath || pathname.startsWith(`${submenuPath}/`)) return;
navigate({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- to: isPam
- ? (`/organizations/$orgId/pam/${submenu.pathSuffix}` as any)
+ to: isOrgScoped
+ ? (`/organizations/$orgId/${typePath}/${submenu.pathSuffix}` as any)
: (`/organizations/$orgId/projects/${typePath}/$projectId/${submenu.pathSuffix}` as any),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: { orgId: currentOrg.id, projectId: currentProject.id } as any,
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx
index 8fcc01f9b3..0f1984f434 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx
@@ -10,7 +10,7 @@ import {
useSidebarScope
} from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
-import { ProjectType } from "@app/hooks/api/projects/types";
+import { isOrgScopedProduct } from "@app/helpers/project";
import type { NavItem, Submenu } from "./types";
import { PROJECT_TYPE_PATH } from "./types";
@@ -30,9 +30,9 @@ export const ProjectNavLink = ({
const sidebarScope = useSidebarScope();
const typePath = PROJECT_TYPE_PATH[currentProject.type];
- const isPam = currentProject.type === ProjectType.PAM;
- const basePath = isPam
- ? `/organizations/${currentOrg.id}/pam`
+ const isOrgScoped = isOrgScopedProduct(currentProject.type);
+ const basePath = isOrgScoped
+ ? `/organizations/${currentOrg.id}/${typePath}`
: `/organizations/${currentOrg.id}/projects/${typePath}/${currentProject.id}`;
const fullPath = `${basePath}/${item.pathSuffix}`;
@@ -89,8 +89,8 @@ export const ProjectNavLink = ({
<Link
// eslint-disable-next-line @typescript-eslint/no-explicit-any
to={
- isPam
- ? (`/organizations/$orgId/pam/${item.pathSuffix}` as any)
+ isOrgScoped
+ ? (`/organizations/$orgId/${typePath}/${item.pathSuffix}` as any)
: (`/organizations/$orgId/projects/${typePath}/$projectId/${item.pathSuffix}` as any)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/SubmenuViews.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/SubmenuViews.tsx
index c5d2c241c2..16670a197a 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/SubmenuViews.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/SubmenuViews.tsx
@@ -11,7 +11,7 @@ import {
useSidebarScope
} from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
-import { ProjectType } from "@app/hooks/api/projects/types";
+import { isOrgScopedProduct } from "@app/helpers/project";
import type { Submenu } from "./types";
import { PROJECT_TYPE_PATH } from "./types";
@@ -32,9 +32,9 @@ export const ProjectSubmenuView = ({
const typePath = PROJECT_TYPE_PATH[currentProject.type];
const sidebarScope = useSidebarScope();
- const isPam = currentProject.type === ProjectType.PAM;
- const basePath = isPam
- ? `/organizations/${currentOrg.id}/pam`
+ const isOrgScoped = isOrgScopedProduct(currentProject.type);
+ const basePath = isOrgScoped
+ ? `/organizations/${currentOrg.id}/${typePath}`
: `/organizations/${currentOrg.id}/projects/${typePath}/${currentProject.id}`;
const isOnExactPage = pathname.startsWith(`${basePath}/${submenu.pathSuffix}`);
const currentTab = searchParams?.selectedTab;
@@ -74,8 +74,8 @@ export const ProjectSubmenuView = ({
<Link
// eslint-disable-next-line @typescript-eslint/no-explicit-any
to={
- isPam
- ? (`/organizations/$orgId/pam/${submenu.pathSuffix}` as any)
+ isOrgScoped
+ ? (`/organizations/$orgId/${typePath}/${submenu.pathSuffix}` as any)
: (`/organizations/$orgId/projects/${typePath}/$projectId/${submenu.pathSuffix}` as any)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts
index 9bf958623f..50d4c0fe12 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts
@@ -5,7 +5,8 @@ export const PROJECT_TYPE_PATH: Record<ProjectType, string> = {
[ProjectType.CertificateManager]: "cert-manager",
[ProjectType.KMS]: "kms",
[ProjectType.PAM]: "pam",
- [ProjectType.SecretScanning]: "secret-scanning"
+ [ProjectType.SecretScanning]: "secret-scanning",
+ [ProjectType.AgentVault]: "agent-vault"
};
export type SubmenuItem = {
diff --git a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
index d397a74903..61033e5d70 100644
--- a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
+++ b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
@@ -1,5 +1,5 @@
import { useMemo, useState } from "react";
-import { Link, linkOptions, useLocation, useParams } from "@tanstack/react-router";
+import { Link, linkOptions, useParams } from "@tanstack/react-router";
import { Check, Plus, Star } from "lucide-react";
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
@@ -24,8 +24,8 @@ import {
useProject,
useSubscription
} from "@app/context";
-import { getProjectHomePage } from "@app/helpers/project";
-import { usePopUp } from "@app/hooks";
+import { getProjectHomePage, isOrgScopedProduct } from "@app/helpers/project";
+import { useImplicitProduct, usePopUp } from "@app/hooks";
import { useGetUserProjects } from "@app/hooks/api";
import { ProjectType } from "@app/hooks/api/projects/types";
import { useUpdateUserProjectFavorites } from "@app/hooks/api/users/mutation";
@@ -126,7 +126,7 @@ const ProjectSelectInner = () => {
if (
currentWorkspace.type === ProjectType.CertificateManager ||
- currentWorkspace.type === ProjectType.PAM
+ isOrgScopedProduct(currentWorkspace.type)
) {
return null;
}
@@ -272,11 +272,9 @@ const ProjectSelectInner = () => {
export const ProjectSelect = () => {
const params = useParams({ strict: false });
- const { pathname } = useLocation();
+ const orgScopedProduct = useImplicitProduct();
- const isPamRoute = pathname.includes("/pam/");
-
- if (!params.projectId && !isPamRoute) {
+ if (!params.projectId && !orgScopedProduct) {
return null;
}
diff --git a/frontend/src/layouts/ProjectLayout/components/TypeSelect/TypeSelect.tsx b/frontend/src/layouts/ProjectLayout/components/TypeSelect/TypeSelect.tsx
index 0931fff130..7f8b2c609b 100644
--- a/frontend/src/layouts/ProjectLayout/components/TypeSelect/TypeSelect.tsx
+++ b/frontend/src/layouts/ProjectLayout/components/TypeSelect/TypeSelect.tsx
@@ -7,8 +7,11 @@ import { Command, CommandGroup, CommandItem, CommandList } from "@app/components
import { useOrganization } from "@app/context";
import { getCertManagerActiveProjectCookie } from "@app/helpers/certManagerActiveProject";
import {
+ getOrgScopedProductFromPath,
+ getProjectHomePage,
getProjectLucideIcon,
getProjectTitle,
+ isOrgScopedProduct,
projectTypeToUrlSlug,
urlSlugToProjectType
} from "@app/helpers/project";
@@ -26,7 +29,8 @@ const PRODUCT_TYPES: ProjectType[] = [
ProjectType.CertificateManager,
ProjectType.KMS,
ProjectType.SecretScanning,
- ProjectType.PAM
+ ProjectType.PAM,
+ ProjectType.AgentVault
];
const TypeSelectInner = ({
@@ -85,9 +89,9 @@ const TypeSelectInner = ({
return;
}
- if (type === ProjectType.PAM) {
+ if (isOrgScopedProduct(type)) {
navigate({
- to: "/organizations/$orgId/pam/access",
+ to: getProjectHomePage(type, []),
params: { orgId }
});
return;
@@ -113,9 +117,9 @@ const TypeSelectInner = ({
onClick={() => {
if (currentType === ProjectType.CertificateManager) {
navigateToCertManager();
- } else if (currentType === ProjectType.PAM) {
+ } else if (isOrgScopedProduct(currentType)) {
navigate({
- to: "/organizations/$orgId/pam/access",
+ to: getProjectHomePage(currentType, []),
params: { orgId: currentOrg?.id || "" }
});
} else {
@@ -187,8 +191,9 @@ export const TypeSelect = () => {
}
}
- if (!params.projectId && pathname.includes("/pam/")) {
- return <TypeSelectInner currentType={ProjectType.PAM} />;
+ const orgScopedProduct = getOrgScopedProductFromPath(pathname);
+ if (!params.projectId && orgScopedProduct) {
+ return <TypeSelectInner currentType={orgScopedProduct} />;
}
if (params.projectId) {
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
new file mode 100644
index 0000000000..b4896553a4
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
@@ -0,0 +1,172 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { Link, useNavigate, useParams } from "@tanstack/react-router";
+import {
+ ChevronLeftIcon,
+ EllipsisIcon,
+ PackageIcon,
+ PencilIcon,
+ TrashIcon,
+ UsersIcon
+} from "lucide-react";
+
+import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";
+import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";
+import { ServiceSheet } from "@app/components/agent-vault/service-sheet";
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ PageHeader,
+ PageLoader
+} from "@app/components/v3";
+import { useOrganization, useProjectPermission } from "@app/context";
+import { useGetAgentVaultAccessBundle } from "@app/hooks/api/agentVault";
+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+import { DeleteAccessBundleDialog } from "@app/pages/agent-vault/AgentVaultAccessBundlesPage/components/DeleteAccessBundleDialog";
+
+import { ServicesCard } from "./components/ServicesCard";
+
+export const AgentVaultAccessBundleDetailPage = () => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+ const { hasProjectRole } = useProjectPermission();
+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+
+ const accessBundleId = useParams({
+ strict: false,
+ select: (params) => params.accessBundleId as string
+ });
+
+ const { data: accessBundle, isPending } = useGetAgentVaultAccessBundle(accessBundleId);
+
+ const [isEditOpen, setIsEditOpen] = useState(false);
+ const [isManageAccessOpen, setIsManageAccessOpen] = useState(false);
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+ const [isServiceSheetOpen, setIsServiceSheetOpen] = useState(false);
+ const [serviceToEdit, setServiceToEdit] = useState<TAgentVaultService | null>(null);
+
+ if (isPending) return <PageLoader />;
+ if (!accessBundle) {
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>Access bundle not found</EmptyTitle>
+ <EmptyDescription>It was deleted or is no longer granted to you.</EmptyDescription>
+ </EmptyHeader>
+ <Button variant="av" asChild>
+ <Link
+ to="/organizations/$orgId/agent-vault/access-bundles"
+ params={{ orgId: currentOrg.id }}
+ >
+ Back to Access Bundles
+ </Link>
+ </Button>
+ </Empty>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Helmet>
+ <title>{t("common.head-title", { title: accessBundle.name })}</title>
+ </Helmet>
+
+ <Link
+ to="/organizations/$orgId/agent-vault/access-bundles"
+ params={{ orgId: currentOrg.id }}
+ className="mb-4 flex w-fit items-center gap-x-1 text-sm text-mineshaft-400 transition hover:text-mineshaft-400/80"
+ >
+ <ChevronLeftIcon size={16} />
+ Access Bundles
+ </Link>
+
+ <PageHeader
+ scope={ProjectType.AgentVault}
+ icon={PackageIcon}
+ title={accessBundle.name}
+ description={accessBundle.description || "No description"}
+ >
+ {isAdmin && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline">
+ Options
+ <EllipsisIcon />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setIsManageAccessOpen(true)}>
+ <UsersIcon />
+ Manage Access
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setIsEditOpen(true)}>
+ <PencilIcon />
+ Edit Access Bundle
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="danger" onClick={() => setIsDeleteOpen(true)}>
+ <TrashIcon />
+ Delete Access Bundle
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </PageHeader>
+
+ <ServicesCard
+ accessBundleId={accessBundle.id}
+ services={accessBundle.services}
+ canManage={isAdmin}
+ onAdd={() => {
+ setServiceToEdit(null);
+ setIsServiceSheetOpen(true);
+ }}
+ onEdit={(service) => {
+ setServiceToEdit(service);
+ setIsServiceSheetOpen(true);
+ }}
+ />
+
+ <ManageAccessSheet
+ accessBundle={isManageAccessOpen ? accessBundle : null}
+ onOpenChange={setIsManageAccessOpen}
+ />
+
+ <ServiceSheet
+ isOpen={isServiceSheetOpen}
+ onOpenChange={setIsServiceSheetOpen}
+ accessBundleId={accessBundle.id}
+ service={serviceToEdit}
+ />
+
+ <AccessBundleFormDialog
+ isOpen={isEditOpen}
+ onOpenChange={setIsEditOpen}
+ accessBundle={accessBundle}
+ />
+
+ <DeleteAccessBundleDialog
+ accessBundle={isDeleteOpen ? accessBundle : null}
+ onOpenChange={setIsDeleteOpen}
+ onDeleted={() =>
+ navigate({
+ to: "/organizations/$orgId/agent-vault/access-bundles",
+ params: { orgId: currentOrg.id }
+ })
+ }
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
new file mode 100644
index 0000000000..4c71e7065f
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
@@ -0,0 +1,312 @@
+import { useMemo, useState } from "react";
+import { format } from "date-fns";
+import {
+ ChevronDownIcon,
+ MoreHorizontalIcon,
+ PencilIcon,
+ PlusIcon,
+ SearchIcon,
+ TrashIcon
+} from "lucide-react";
+import { twMerge } from "tailwind-merge";
+
+import {
+ CREDENTIAL_LABELS,
+ displayHostPattern
+} from "@app/components/agent-vault/service-sheet/serviceSchema";
+import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DeleteConfirmDialog,
+ DocumentationLinkBadge,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useDeleteAgentVaultService } from "@app/hooks/api/agentVault";
+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
+
+import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";
+
+enum SortColumn {
+ Name = "name",
+ Credential = "credential",
+ Hosts = "hosts",
+ Created = "created"
+}
+
+const SORT_COMPARATORS: Record<
+ SortColumn,
+ (a: TAgentVaultService, b: TAgentVaultService) => number
+> = {
+ [SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),
+ [SortColumn.Credential]: (a, b) =>
+ CREDENTIAL_LABELS[a.credential.type].localeCompare(CREDENTIAL_LABELS[b.credential.type]),
+ [SortColumn.Hosts]: (a, b) => a.hostPattern.localeCompare(b.hostPattern),
+ [SortColumn.Created]: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
+};
+
+type Props = {
+ accessBundleId: string;
+ services: TAgentVaultService[];
+ canManage: boolean;
+ onAdd: () => void;
+ onEdit: (service: TAgentVaultService) => void;
+};
+
+// Two hosts is what the column fits comfortably; the rest go behind the count so the table keeps its
+// width no matter how many a service covers.
+const HOSTS_SHOWN = 2;
+
+const HostsCell = ({ hostPattern }: { hostPattern: string }) => {
+ const hosts = displayHostPattern(hostPattern).split(", ");
+ const hidden = hosts.slice(HOSTS_SHOWN);
+
+ return (
+ <div className="flex max-w-72 items-center gap-1.5 text-sm">
+ <span className="truncate">{hosts.slice(0, HOSTS_SHOWN).join(", ")}</span>
+ {hidden.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger className="shrink-0 text-muted">+{hidden.length}</TooltipTrigger>
+ <TooltipContent>{hidden.join(", ")}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+};
+
+export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdit }: Props) => {
+ const [search, setSearch] = useState("");
+ const [serviceToDelete, setServiceToDelete] = useState<TAgentVaultService | null>(null);
+ const deleteService = useDeleteAgentVaultService();
+
+ const [sortColumn, setSortColumn] = useState(SortColumn.Created);
+ const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("descending");
+
+ const displayed = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ const filtered = services.filter(
+ (service) =>
+ service.name.toLowerCase().includes(term) ||
+ service.hostPattern.toLowerCase().includes(term)
+ );
+
+ const ordered = [...filtered].sort(SORT_COMPARATORS[sortColumn]);
+ return sortDirection === "ascending" ? ordered : ordered.reverse();
+ }, [services, search, sortColumn, sortDirection]);
+
+ const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {
+ if (direction === "none") {
+ setSortColumn(SortColumn.Created);
+ setSortDirection("descending");
+ return;
+ }
+ setSortColumn(column);
+ setSortDirection(direction);
+ };
+
+ const sortIconClassName = (column: SortColumn) =>
+ twMerge(
+ "size-3.5 transition-transform",
+ sortColumn === column && sortDirection === "descending" && "rotate-180",
+ sortColumn !== column && "opacity-30"
+ );
+
+ const handleDelete = async () => {
+ try {
+ if (!serviceToDelete) return;
+
+ await deleteService.mutateAsync({
+ accessBundleId,
+ serviceId: serviceToDelete.id
+ });
+ createNotification({
+ text: `Service "${serviceToDelete.name}" deleted`,
+ type: "success"
+ });
+ setServiceToDelete(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Services
+ <DocumentationLinkBadge href={AgentVaultDocsUrls.accessBundles} />
+ </CardTitle>
+ <CardDescription>
+ A service names one API the agent may reach, the hosts it answers on, and the credential
+ the proxy attaches.
+ </CardDescription>
+ {canManage && (
+ <CardAction>
+ <Button variant="av" onClick={onAdd}>
+ <PlusIcon />
+ Add Service
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+
+ {services.length > 0 && (
+ <CardContent>
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search services..."
+ />
+ </InputGroup>
+ </CardContent>
+ )}
+
+ {displayed.length === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>
+ {services.length === 0 ? "No services yet" : "No services match your search"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {services.length === 0
+ ? "Add a service to give this bundle a host and a credential."
+ : "Try a different search term."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Name ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Name, direction)}
+ >
+ Name
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Name)} />
+ </TableHead>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Credential ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Credential, direction)}
+ >
+ Credential
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Credential)} />
+ </TableHead>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Hosts ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Hosts, direction)}
+ >
+ Hosts
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Hosts)} />
+ </TableHead>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Created ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Created, direction)}
+ >
+ Created
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Created)} />
+ </TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {displayed.map((service) => (
+ <TableRow key={service.id}>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <ServiceIcon hostPattern={service.hostPattern} />
+ {service.name}
+ </div>
+ </TableCell>
+ <TableCell>{CREDENTIAL_LABELS[service.credential.type]}</TableCell>
+ <TableCell>
+ <HostsCell hostPattern={service.hostPattern} />
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">
+ {format(new Date(service.createdAt), "MMM d, yyyy")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {format(new Date(service.createdAt), "MMM d, yyyy h:mm a")}
+ </TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell variant="action">
+ {canManage && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open service actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem onClick={() => onEdit(service)}>
+ <PencilIcon />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setServiceToDelete(service)}
+ >
+ <TrashIcon />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+
+ <DeleteConfirmDialog
+ isOpen={Boolean(serviceToDelete)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setServiceToDelete(null);
+ }}
+ title={`Delete "${serviceToDelete?.name}"`}
+ description="Agents lose this credential at the next proxy poll. This cannot be undone."
+ confirmKey={serviceToDelete?.name ?? ""}
+ isPending={deleteService.isPending}
+ onConfirm={handleDelete}
+ />
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsx
new file mode 100644
index 0000000000..864b8e4f82
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AgentVaultAccessBundleDetailPage } from "./AgentVaultAccessBundleDetailPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId"
+)({
+ component: AgentVaultAccessBundleDetailPage,
+ beforeLoad: ({ context }) => {
+ return { breadcrumbs: [...context.breadcrumbs, { label: "Access Bundle" }] };
+ }
+});
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx
new file mode 100644
index 0000000000..249a52b58a
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx
@@ -0,0 +1,377 @@
+import { useMemo, useState } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { useNavigate } from "@tanstack/react-router";
+import { format } from "date-fns";
+import {
+ ChevronDownIcon,
+ MoreHorizontalIcon,
+ PackageIcon,
+ PencilIcon,
+ PlusIcon,
+ SearchIcon,
+ TrashIcon,
+ UsersIcon
+} from "lucide-react";
+import { twMerge } from "tailwind-merge";
+
+import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";
+import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";
+import { ServiceIconStack } from "@app/components/agent-vault/ServiceIconStack";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DocumentationLinkBadge,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ PageHeader,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useOrganization, useProjectPermission } from "@app/context";
+import { useListAgentVaultAccessBundles } from "@app/hooks/api/agentVault";
+import { TAgentVaultAccessBundleListItem } from "@app/hooks/api/agentVault/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { AgentVaultDocsUrls } from "../agent-vault-docs-urls";
+import { DeleteAccessBundleDialog } from "./components/DeleteAccessBundleDialog";
+
+enum SortColumn {
+ Name = "name",
+ Services = "services",
+ Created = "created"
+}
+
+const SORT_COMPARATORS: Record<
+ SortColumn,
+ (a: TAgentVaultAccessBundleListItem, b: TAgentVaultAccessBundleListItem) => number
+> = {
+ [SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),
+ [SortColumn.Services]: (a, b) => a.serviceCount - b.serviceCount,
+ [SortColumn.Created]: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
+};
+
+export const AgentVaultAccessBundlesPage = () => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+ const { hasProjectRole } = useProjectPermission();
+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+
+ const [search, setSearch] = useState("");
+ const [sortColumn, setSortColumn] = useState(SortColumn.Created);
+ const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("descending");
+ const [isCreateOpen, setIsCreateOpen] = useState(false);
+ const [bundleToEdit, setBundleToEdit] = useState<TAgentVaultAccessBundleListItem | null>(null);
+ const [bundleToDelete, setBundleToDelete] = useState<TAgentVaultAccessBundleListItem | null>(
+ null
+ );
+ const [bundleToManage, setBundleToManage] = useState<TAgentVaultAccessBundleListItem | null>(
+ null
+ );
+
+ const { data: accessBundles, isPending } = useListAgentVaultAccessBundles();
+
+ const displayedBundles = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ const filtered = (accessBundles ?? []).filter(
+ (bundle) =>
+ bundle.name.toLowerCase().includes(term) ||
+ (bundle.description ?? "").toLowerCase().includes(term)
+ );
+
+ const ordered = [...filtered].sort(SORT_COMPARATORS[sortColumn]);
+
+ return sortDirection === "ascending" ? ordered : ordered.reverse();
+ }, [accessBundles, search, sortColumn, sortDirection]);
+
+ const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {
+ if (direction === "none") {
+ setSortColumn(SortColumn.Created);
+ setSortDirection("descending");
+ return;
+ }
+
+ setSortColumn(column);
+ setSortDirection(direction);
+ };
+
+ const sortIconClassName = (column: SortColumn) =>
+ twMerge(
+ "transition-transform",
+ sortColumn === column && sortDirection === "descending" && "rotate-180",
+ sortColumn !== column && "opacity-30"
+ );
+
+ const isFiltered = Boolean(search.trim());
+
+ let emptyTitle: string;
+ let emptyDescription: string;
+ if (isFiltered) {
+ emptyTitle = "No access bundles match your search";
+ emptyDescription = "Try a different search term.";
+ } else if (isAdmin) {
+ emptyTitle = "No access bundles yet";
+ emptyDescription = "Create one to group the services an agent may use.";
+ } else {
+ emptyTitle = "No access bundles available";
+ emptyDescription = "Ask an admin to grant you an access bundle.";
+ }
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Helmet>
+ <title>{t("common.head-title", { title: "Access Bundles" })}</title>
+ </Helmet>
+ <PageHeader
+ scope={ProjectType.AgentVault}
+ icon={PackageIcon}
+ title="Access Bundles"
+ description="Define what's included and who can use it."
+ />
+
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Access Bundles
+ <DocumentationLinkBadge href={AgentVaultDocsUrls.accessBundles} />
+ </CardTitle>
+ <CardDescription>
+ Each bundle holds the services an agent may use and the members who can mint a session
+ over it.
+ </CardDescription>
+ {isAdmin && (
+ <CardAction>
+ <Button variant="av" onClick={() => setIsCreateOpen(true)}>
+ <PlusIcon />
+ Create Access Bundle
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+ <CardContent>
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search access bundles..."
+ />
+ </InputGroup>
+ </CardContent>
+
+ {!isPending && displayedBundles.length === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>{emptyTitle}</EmptyTitle>
+ <EmptyDescription>{emptyDescription}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead
+ isTruncatable
+ className="w-2/5"
+ sortDirection={sortColumn === SortColumn.Name ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Name, direction)}
+ >
+ Name
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Name)} />
+ </TableHead>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Services ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Services, direction)}
+ >
+ Services
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Services)} />
+ </TableHead>
+ <TableHead>Members</TableHead>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Created ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Created, direction)}
+ >
+ Created
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Created)} />
+ </TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 3 }).map((_, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`bundle-skeleton-${index}`}>
+ {Array.from({ length: 4 }).map((__, cell) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableCell key={`bundle-skeleton-${index}-${cell}`}>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {!isPending &&
+ displayedBundles.map((bundle) => (
+ <TableRow
+ key={bundle.id}
+ onClick={() =>
+ navigate({
+ to: "/organizations/$orgId/agent-vault/access-bundles/$accessBundleId",
+ params: { orgId: currentOrg.id, accessBundleId: bundle.id }
+ })
+ }
+ >
+ <TableCell isTruncatable className="min-w-64">
+ <div className="flex items-center gap-2.5">
+ <span className="truncate" title={bundle.name}>
+ {bundle.name}
+ </span>
+ {bundle.description && (
+ <span
+ className="min-w-0 flex-1 truncate text-sm text-muted"
+ title={bundle.description}
+ >
+ {bundle.description}
+ </span>
+ )}
+ </div>
+ </TableCell>
+ <TableCell>
+ <ServiceIconStack hostPatterns={bundle.hostPatterns} />
+ </TableCell>
+ <TableCell>
+ {isAdmin ? (
+ <button
+ type="button"
+ className="cursor-pointer underline decoration-muted underline-offset-2 hover:decoration-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToManage(bundle);
+ }}
+ >
+ {bundle.memberCount} member{bundle.memberCount === 1 ? "" : "s"}
+ </button>
+ ) : (
+ <>
+ {bundle.memberCount} member{bundle.memberCount === 1 ? "" : "s"}
+ </>
+ )}
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">
+ {format(new Date(bundle.createdAt), "MMM d, yyyy")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {format(new Date(bundle.createdAt), "MMM d, yyyy h:mm a")}
+ </TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell variant="action">
+ {isAdmin && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Open access bundle actions"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToManage(bundle);
+ }}
+ >
+ <UsersIcon />
+ Manage Access
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToEdit(bundle);
+ }}
+ >
+ <PencilIcon />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToDelete(bundle);
+ }}
+ >
+ <TrashIcon />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </Card>
+
+ <AccessBundleFormDialog isOpen={isCreateOpen} onOpenChange={setIsCreateOpen} />
+ <AccessBundleFormDialog
+ isOpen={Boolean(bundleToEdit)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setBundleToEdit(null);
+ }}
+ accessBundle={bundleToEdit ?? undefined}
+ />
+ <ManageAccessSheet
+ accessBundle={bundleToManage}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setBundleToManage(null);
+ }}
+ />
+
+ <DeleteAccessBundleDialog
+ accessBundle={bundleToDelete}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setBundleToDelete(null);
+ }}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/components/DeleteAccessBundleDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/components/DeleteAccessBundleDialog.tsx
new file mode 100644
index 0000000000..810ccc5310
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/components/DeleteAccessBundleDialog.tsx
@@ -0,0 +1,39 @@
+import { createNotification } from "@app/components/notifications";
+import { DeleteConfirmDialog } from "@app/components/v3";
+import { useDeleteAgentVaultAccessBundle } from "@app/hooks/api/agentVault";
+import { TAgentVaultAccessBundle } from "@app/hooks/api/agentVault/types";
+
+type Props = {
+ accessBundle: TAgentVaultAccessBundle | null;
+ onOpenChange: (isOpen: boolean) => void;
+ onDeleted?: () => void;
+};
+
+export const DeleteAccessBundleDialog = ({ accessBundle, onOpenChange, onDeleted }: Props) => {
+ const deleteAccessBundle = useDeleteAgentVaultAccessBundle();
+
+ const handleDelete = async () => {
+ try {
+ if (!accessBundle) return;
+
+ await deleteAccessBundle.mutateAsync(accessBundle.id);
+ createNotification({ text: `Access bundle "${accessBundle.name}" deleted`, type: "success" });
+ onOpenChange(false);
+ onDeleted?.();
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <DeleteConfirmDialog
+ isOpen={Boolean(accessBundle)}
+ onOpenChange={onOpenChange}
+ title={`Delete "${accessBundle?.name}"`}
+ description="Its services and every grant on it go with it. Any live session carrying it loses them at the next proxy poll. This cannot be undone."
+ confirmKey={accessBundle?.name ?? ""}
+ isPending={deleteAccessBundle.isPending}
+ onConfirm={handleDelete}
+ />
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/route.tsx
new file mode 100644
index 0000000000..13a3e30833
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/route.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AgentVaultAccessBundlesPage } from "./AgentVaultAccessBundlesPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/"
+)({
+ component: AgentVaultAccessBundlesPage,
+ beforeLoad: ({ context }) => {
+ return { breadcrumbs: [...context.breadcrumbs, { label: "Access Bundles" }] };
+ }
+});
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsx
new file mode 100644
index 0000000000..ea7f12c15d
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsx
@@ -0,0 +1,88 @@
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import { ShieldIcon } from "lucide-react";
+
+import { PageHeader, Tabs, TabsContent, TabsList, TabsTrigger } from "@app/components/v3";
+import {
+ ProjectPermissionMemberActions,
+ ProjectPermissionSub,
+ useOrganization
+} from "@app/context";
+import { withProjectPermission } from "@app/hoc";
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+import { GroupsTab } from "./components/GroupsTab";
+import { IdentitiesTab } from "./components/IdentitiesTab";
+import { MembersTab } from "./components/MembersTab";
+
+export enum AgentVaultAccessControlTab {
+ // "members" is the shared tab vocabulary (ProjectAccessControlTabs.Member) that both the access
+ // request notification link and the member-details breadcrumb send; only the label says "Users".
+ Users = "members",
+ MachineIdentities = "identities",
+ Groups = "groups"
+}
+
+const AgentVaultAccessControlPageContent = () => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+
+ const selectedTab =
+ useSearch({
+ strict: false,
+ select: (el) => (el as { selectedTab?: string })?.selectedTab
+ }) || AgentVaultAccessControlTab.Users;
+
+ const updateTab = (tab: string) => {
+ navigate({
+ to: "/organizations/$orgId/agent-vault/access-management",
+ search: (prev) => ({ ...prev, selectedTab: tab }),
+ params: { orgId: currentOrg.id }
+ });
+ };
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Helmet>
+ <title>{t("common.head-title", { title: "Access Control" })}</title>
+ </Helmet>
+ <PageHeader
+ scope={ProjectType.AgentVault}
+ icon={ShieldIcon}
+ title="Access Control"
+ description="Manage access for users, machine identities, and groups."
+ />
+ <Tabs value={selectedTab} onValueChange={updateTab}>
+ <TabsList variant="av" aria-label="Agent Vault access control sections">
+ <TabsTrigger value={AgentVaultAccessControlTab.Users}>Users</TabsTrigger>
+ <TabsTrigger value={AgentVaultAccessControlTab.MachineIdentities}>
+ Machine Identities
+ </TabsTrigger>
+ <TabsTrigger value={AgentVaultAccessControlTab.Groups}>Groups</TabsTrigger>
+ </TabsList>
+ <TabsContent value={AgentVaultAccessControlTab.Users}>
+ <MembersTab />
+ </TabsContent>
+ <TabsContent value={AgentVaultAccessControlTab.MachineIdentities}>
+ <IdentitiesTab />
+ </TabsContent>
+ <TabsContent value={AgentVaultAccessControlTab.Groups}>
+ <GroupsTab />
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+};
+
+// Built at module scope: wrapping inside the render makes a new component type each pass, which
+// remounts the tabs and replays the gate.
+export const AgentVaultAccessControlPage = withProjectPermission(
+ AgentVaultAccessControlPageContent,
+ {
+ action: ProjectPermissionMemberActions.Read,
+ subject: ProjectPermissionSub.Member,
+ accessRestrictedMode: "dialog"
+ }
+);
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx
new file mode 100644
index 0000000000..14e9695a7f
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx
@@ -0,0 +1,109 @@
+import { useMemo, useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel,
+ FilterableSelect
+} from "@app/components/v3";
+import { useOrganization } from "@app/context";
+import { useGetOrganizationGroups } from "@app/hooks/api";
+import {
+ useAddAgentVaultProductMember,
+ useListAgentVaultProductGroupMembers
+} from "@app/hooks/api/agentVault";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { ProductRoleField } from "./ProductRoleField";
+
+type TOption = { value: string; label: string };
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {
+ const { currentOrg } = useOrganization();
+ const { data: orgGroups = [] } = useGetOrganizationGroups(currentOrg.id);
+ const { data: projectGroups = [] } = useListAgentVaultProductGroupMembers();
+ const addMember = useAddAgentVaultProductMember();
+
+ const [group, setGroup] = useState<TOption | null>(null);
+ const [role, setRole] = useState<string>(ProjectMembershipRole.Member);
+
+ const options = useMemo(() => {
+ const attached = new Set(projectGroups.map((membership) => membership.groupId));
+ return orgGroups
+ .filter((orgGroup) => !attached.has(orgGroup.id))
+ .map((orgGroup) => ({ value: orgGroup.id, label: orgGroup.name }));
+ }, [orgGroups, projectGroups]);
+
+ const handleAdd = async () => {
+ try {
+ if (!group) return;
+ await addMember.mutateAsync({ groupId: group.value, role });
+ createNotification({ text: `"${group.label}" added`, type: "success" });
+ setGroup(null);
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add Group</DialogTitle>
+ <DialogDescription>
+ Everyone in the group gets access, including people added to it later.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Field>
+ <FieldLabel>Group</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={group}
+ onChange={(value) => setGroup((value ?? null) as TOption | null)}
+ options={options}
+ placeholder="Search groups..."
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Product Role</FieldLabel>
+ <FieldContent>
+ <ProductRoleField value={role} onChange={setRole} idPrefix="add-group-role" />
+ </FieldContent>
+ </Field>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="av"
+ isPending={addMember.isPending}
+ isDisabled={!group}
+ onClick={handleAdd}
+ >
+ Add Group
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsx
new file mode 100644
index 0000000000..4371e5615a
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsx
@@ -0,0 +1,198 @@
+import { useMemo, useState } from "react";
+import { MoreHorizontalIcon, PencilIcon, PlusIcon, SearchIcon, Trash2Icon } from "lucide-react";
+
+import { ProductRoleBadge } from "@app/components/agent-vault/ProductRoleBadge";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { HighlightText } from "@app/components/v2/HighlightText";
+import {
+ Button,
+ Card,
+ CardContent,
+ DeleteConfirmDialog,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
+import {
+ useListAgentVaultProductGroupMembers,
+ useRemoveAgentVaultProductMember
+} from "@app/hooks/api/agentVault";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { AddGroupDialog } from "./AddGroupDialog";
+import { ProductRoleDialog } from "./ProductRoleDialog";
+
+type TGroupRow = { id: string; name: string; role: string };
+
+export const GroupsTab = () => {
+ const { data: groups = [], isPending } = useListAgentVaultProductGroupMembers();
+ const removeMember = useRemoveAgentVaultProductMember();
+
+ const [search, setSearch] = useState("");
+ const [isAddOpen, setIsAddOpen] = useState(false);
+ const [groupToEdit, setGroupToEdit] = useState<TGroupRow | null>(null);
+ const [groupToRemove, setGroupToRemove] = useState<TGroupRow | null>(null);
+
+ const rows = useMemo<TGroupRow[]>(() => {
+ const term = search.trim().toLowerCase();
+ return groups
+ .filter((membership) => membership.groupId)
+ .map((membership) => ({
+ id: membership.groupId as string,
+ name: membership.name,
+ role: membership.role
+ }))
+ .filter((row) => row.name.toLowerCase().includes(term));
+ }, [groups, search]);
+
+ const handleRemove = async () => {
+ try {
+ if (!groupToRemove) return;
+ await removeMember.mutateAsync({ groupId: groupToRemove.id });
+ createNotification({
+ text: `"${groupToRemove.name}" removed`,
+ type: "success"
+ });
+ setGroupToRemove(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Card>
+ <CardContent className="flex items-center gap-3">
+ <InputGroup className="flex-1">
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search groups..."
+ />
+ </InputGroup>
+ <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Groups}>
+ {(isAllowed) => (
+ <Button variant="av" isDisabled={!isAllowed} onClick={() => setIsAddOpen(true)}>
+ <PlusIcon />
+ Add Group
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </CardContent>
+
+ {!isPending && rows.length === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>{search ? "No groups match your search" : "No groups yet"}</EmptyTitle>
+ <EmptyDescription>
+ {search
+ ? "Try a different search term."
+ : "Add a group to give everyone in it access."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead isTruncatable className="w-2/3">
+ Name
+ </TableHead>
+ <TableHead>Product Role</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 3 }).map((_, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`group-skeleton-${index}`}>
+ {Array.from({ length: 3 }).map((__, cell) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableCell key={`group-skeleton-${index}-${cell}`}>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {!isPending &&
+ rows.map((row) => (
+ <TableRow key={row.id}>
+ <TableCell isTruncatable className="min-w-32" title={row.name}>
+ <HighlightText text={row.name} highlight={search} />
+ </TableCell>
+ <TableCell>
+ <ProductRoleBadge role={row.role} />
+ </TableCell>
+ <TableCell variant="action">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open group actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem onClick={() => setGroupToEdit(row)}>
+ <PencilIcon />
+ Change Role
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="danger" onClick={() => setGroupToRemove(row)}>
+ <Trash2Icon />
+ Remove
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+
+ <AddGroupDialog isOpen={isAddOpen} onOpenChange={setIsAddOpen} />
+
+ <ProductRoleDialog
+ isOpen={Boolean(groupToEdit)}
+ onOpenChange={() => setGroupToEdit(null)}
+ subject={groupToEdit?.name ?? ""}
+ currentRole={groupToEdit?.role ?? ProjectMembershipRole.Member}
+ actor={groupToEdit ? { groupId: groupToEdit.id } : {}}
+ />
+
+ <DeleteConfirmDialog
+ isOpen={Boolean(groupToRemove)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setGroupToRemove(null);
+ }}
+ title={`Remove "${groupToRemove?.name ?? ""}"`}
+ description="Everyone in the group loses access, along with every bundle granted to it."
+ confirmKey={groupToRemove?.name ?? ""}
+ confirmLabel="Remove"
+ isPending={removeMember.isPending}
+ onConfirm={handleRemove}
+ />
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsx
new file mode 100644
index 0000000000..7b0f05bcc9
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsx
@@ -0,0 +1,284 @@
+import { useMemo, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
+import {
+ MoreHorizontalIcon,
+ PencilIcon,
+ PlusIcon,
+ SearchIcon,
+ Trash2Icon,
+ VaultIcon
+} from "lucide-react";
+
+import { ProductRoleBadge } from "@app/components/agent-vault/ProductRoleBadge";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { HighlightText } from "@app/components/v2/HighlightText";
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ DeleteConfirmDialog,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ OrgIcon,
+ Skeleton,
+ SubOrgIcon,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ ProjectPermissionIdentityActions,
+ ProjectPermissionSub,
+ useOrganization,
+ useProject
+} from "@app/context";
+import {
+ agentVaultKeys,
+ useListAgentVaultProductIdentityMembers,
+ useRemoveAgentVaultProductMember
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultProductIdentityMember } from "@app/hooks/api/agentVault/types";
+import { useDeleteProjectIdentity, useUpdateProjectIdentity } from "@app/hooks/api/projectIdentity";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+import { CreateProjectIdentitySheet } from "@app/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentitySheet";
+
+import { ProductRoleDialog } from "./ProductRoleDialog";
+
+export const IdentitiesTab = () => {
+ const { currentProject } = useProject();
+ const { currentOrg, isSubOrganization } = useOrganization();
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const { data: identities = [], isPending } = useListAgentVaultProductIdentityMembers();
+ const removeMember = useRemoveAgentVaultProductMember();
+ const deleteIdentity = useDeleteProjectIdentity();
+ const updateIdentity = useUpdateProjectIdentity();
+
+ const [search, setSearch] = useState("");
+ const [isAddOpen, setIsAddOpen] = useState(false);
+ const [toEdit, setToEdit] = useState<TAgentVaultProductIdentityMember | null>(null);
+ const [toRemove, setToRemove] = useState<TAgentVaultProductIdentityMember | null>(null);
+
+ const filtered = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ return identities.filter((identity) => identity.name.toLowerCase().includes(term));
+ }, [identities, search]);
+
+ // An identity created here is scoped to the Agent Vault project, so detaching it would orphan it.
+ // Those are deleted outright.
+ const isAgentVaultManaged = (identity: TAgentVaultProductIdentityMember) =>
+ identity.identityProjectId === currentProject.id;
+
+ const renderManagedByBadge = (identity: TAgentVaultProductIdentityMember) => {
+ if (isAgentVaultManaged(identity)) {
+ return (
+ <Badge variant="av">
+ <VaultIcon />
+ Agent Vault
+ </Badge>
+ );
+ }
+ if (isSubOrganization && currentOrg.id === identity.identityOrgId) {
+ return (
+ <Badge variant="sub-org">
+ <SubOrgIcon />
+ Sub-Organization
+ </Badge>
+ );
+ }
+ return (
+ <Badge variant="org">
+ <OrgIcon />
+ Organization
+ </Badge>
+ );
+ };
+
+ const handleRemove = async () => {
+ try {
+ if (!toRemove?.identityId) return;
+
+ if (isAgentVaultManaged(toRemove)) {
+ // Identities are created here with delete protection on, which the delete endpoint refuses.
+ await updateIdentity.mutateAsync({
+ identityId: toRemove.identityId,
+ projectId: currentProject.id,
+ hasDeleteProtection: false
+ });
+ await deleteIdentity.mutateAsync({
+ identityId: toRemove.identityId,
+ projectId: currentProject.id
+ });
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.productMembers(currentOrg.id) });
+ createNotification({ text: `"${toRemove.name}" deleted`, type: "success" });
+ } else {
+ await removeMember.mutateAsync({ identityId: toRemove.identityId });
+ createNotification({ text: `"${toRemove.name}" removed`, type: "success" });
+ }
+
+ setToRemove(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Card>
+ <CardContent className="flex items-center gap-3">
+ <InputGroup className="flex-1">
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search machine identities..."
+ />
+ </InputGroup>
+ <ProjectPermissionCan
+ I={ProjectPermissionIdentityActions.Create}
+ a={ProjectPermissionSub.Identity}
+ >
+ {(isAllowed) => (
+ <Button variant="av" isDisabled={!isAllowed} onClick={() => setIsAddOpen(true)}>
+ <PlusIcon />
+ Add Machine Identity
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </CardContent>
+
+ {!isPending && filtered.length === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>
+ {search ? "No machine identities match your search" : "No machine identities yet"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {search
+ ? "Try a different search term."
+ : "Add a machine identity to give it access."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead isTruncatable className="w-2/3">
+ Name
+ </TableHead>
+ <TableHead>Product Role</TableHead>
+ <TableHead>Managed By</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 3 }).map((_, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`identity-skeleton-${index}`}>
+ {Array.from({ length: 4 }).map((__, cell) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableCell key={`identity-skeleton-${index}-${cell}`}>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {!isPending &&
+ filtered.map((identity) => (
+ <TableRow
+ key={identity.membershipId}
+ className={identity.identityId ? "cursor-pointer" : undefined}
+ onClick={() => {
+ if (!identity.identityId) return;
+ navigate({
+ to: "/organizations/$orgId/agent-vault/identities/$identityId",
+ params: { orgId: currentOrg.id, identityId: identity.identityId }
+ });
+ }}
+ >
+ <TableCell isTruncatable className="min-w-32" title={identity.name}>
+ <HighlightText text={identity.name} highlight={search} />
+ </TableCell>
+ <TableCell>
+ <ProductRoleBadge role={identity.role} />
+ </TableCell>
+ <TableCell>{renderManagedByBadge(identity)}</TableCell>
+ <TableCell variant="action" onClick={(event) => event.stopPropagation()}>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open identity actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem onClick={() => setToEdit(identity)}>
+ <PencilIcon />
+ Change Role
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="danger" onClick={() => setToRemove(identity)}>
+ <Trash2Icon />
+ {isAgentVaultManaged(identity) ? "Delete" : "Remove"}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+
+ <CreateProjectIdentitySheet isOpen={isAddOpen} onOpenChange={setIsAddOpen} />
+
+ <ProductRoleDialog
+ isOpen={Boolean(toEdit)}
+ onOpenChange={() => setToEdit(null)}
+ subject={toEdit?.name ?? ""}
+ currentRole={toEdit?.role ?? ProjectMembershipRole.Member}
+ actor={toEdit?.identityId ? { identityId: toEdit.identityId } : {}}
+ />
+
+ <DeleteConfirmDialog
+ isOpen={Boolean(toRemove)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setToRemove(null);
+ }}
+ title={
+ toRemove && isAgentVaultManaged(toRemove)
+ ? `Delete "${toRemove.name}"`
+ : `Remove "${toRemove?.name ?? ""}"`
+ }
+ description={
+ toRemove && isAgentVaultManaged(toRemove)
+ ? "This identity lives in Agent Vault, so it is deleted along with its access. This cannot be undone."
+ : "The identity itself is left alone. It loses access and every bundle granted to it."
+ }
+ confirmKey={toRemove?.name ?? ""}
+ confirmLabel={toRemove && isAgentVaultManaged(toRemove) ? "Delete" : "Remove"}
+ isPending={removeMember.isPending || updateIdentity.isPending || deleteIdentity.isPending}
+ onConfirm={handleRemove}
+ />
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx
new file mode 100644
index 0000000000..cf96717386
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx
@@ -0,0 +1,206 @@
+import { useEffect, useMemo, useState } from "react";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Alert,
+ AlertDescription,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel,
+ FilterableSelect
+} from "@app/components/v3";
+import { useOrganization } from "@app/context";
+import { useGetOrgUsers } from "@app/hooks/api";
+import {
+ useAddAgentVaultProductUserMembers,
+ useListAgentVaultProductUserMembers
+} from "@app/hooks/api/agentVault";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+import { getRequesterStatus } from "@app/lib/fn/requesterStatus";
+
+import { ProductRoleField } from "./ProductRoleField";
+
+type TCandidate = { value: string; label: string; email: string };
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {
+ const { currentOrg } = useOrganization();
+ const { data: orgUsers = [] } = useGetOrgUsers(currentOrg.id);
+ const { data: projectUsers = [] } = useListAgentVaultProductUserMembers();
+ const addMembers = useAddAgentVaultProductUserMembers();
+ const navigate = useNavigate({ from: "" });
+ const requesterEmail = useSearch({
+ strict: false,
+ select: (el) => (el as { requesterEmail?: string })?.requesterEmail
+ });
+
+ const [selected, setSelected] = useState<TCandidate[]>([]);
+ const [role, setRole] = useState<string>(ProjectMembershipRole.Member);
+
+ const candidates = useMemo(() => {
+ const attached = new Set(projectUsers.map((member) => member.userId));
+ return orgUsers
+ .filter((orgUser) => !attached.has(orgUser.user.id))
+ .map((orgUser) => {
+ const name = `${orgUser.user.firstName ?? ""} ${orgUser.user.lastName ?? ""}`.trim();
+ const email = orgUser.user.email || orgUser.user.username || "";
+ return { value: orgUser.user.id, label: name || email, email };
+ });
+ }, [orgUsers, projectUsers]);
+
+ const memberUsernames = useMemo(
+ () => new Set(projectUsers.map((member) => member.username)),
+ [projectUsers]
+ );
+
+ const requesterStatus = useMemo(
+ () => getRequesterStatus(requesterEmail, orgUsers, memberUsernames),
+ [requesterEmail, orgUsers, memberUsernames]
+ );
+ // getRequesterStatus returns the org membership id; this select is keyed by user id.
+ const requesterUserId = useMemo(
+ () => orgUsers.find((orgUser) => orgUser.id === requesterStatus.userId)?.user.id,
+ [orgUsers, requesterStatus.userId]
+ );
+
+ // Deps stay primitive on purpose: keying off the candidate list would re-run on any refetch and
+ // re-select a requester the admin had just removed.
+ useEffect(() => {
+ if (!requesterEmail) return;
+ // The org-user and project-user queries settle independently, so isProjectUser can flip true
+ // after a preselect. Drop it rather than leave them chipped in under the "already has access"
+ // warning, which would submit a no-op add.
+ if (requesterStatus.isProjectUser) {
+ setSelected([]);
+ return;
+ }
+ if (!requesterUserId) return;
+ setSelected([
+ { value: requesterUserId, label: requesterStatus.userLabel, email: requesterEmail }
+ ]);
+ }, [requesterEmail, requesterUserId, requesterStatus.isProjectUser, requesterStatus.userLabel]);
+
+ const clearRequesterEmail = () => {
+ if (requesterEmail) navigate({ search: (prev) => ({ ...prev, requesterEmail: "" }) });
+ };
+
+ const handleClose = () => {
+ setSelected([]);
+ setRole(ProjectMembershipRole.Member);
+ clearRequesterEmail();
+ onOpenChange(false);
+ };
+
+ const handleAdd = () => {
+ addMembers.mutate(
+ {
+ userIds: selected.map((candidate) => candidate.value),
+ emails: [],
+ role
+ },
+ {
+ onSuccess: ({ members }) => {
+ createNotification({
+ text: `${members.length} user${members.length === 1 ? "" : "s"} added`,
+ type: "success"
+ });
+ handleClose();
+ }
+ }
+ );
+ };
+
+ return (
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ handleClose();
+ return;
+ }
+ onOpenChange(open);
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add Users</DialogTitle>
+ <DialogDescription>Add existing members of {currentOrg.name}.</DialogDescription>
+ </DialogHeader>
+
+ <Field>
+ <FieldLabel>Users</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ isMulti
+ value={selected}
+ onChange={(value) => setSelected((value ?? []) as TCandidate[])}
+ options={candidates}
+ placeholder="Search by name or email..."
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Product Role</FieldLabel>
+ <FieldContent>
+ <ProductRoleField value={role} onChange={setRole} idPrefix="invite-role" />
+ </FieldContent>
+ </Field>
+
+ {requesterEmail && requesterStatus.isProjectUser && (
+ <Alert variant="danger">
+ <AlertDescription>Requested user already has access to Agent Vault.</AlertDescription>
+ </Alert>
+ )}
+ {requesterEmail && !requesterStatus.isProjectUser && requesterUserId && (
+ <Alert>
+ {/* AlertDescription is a grid, so a bare text node would land on its own row */}
+ <AlertDescription>
+ <span>
+ Assign a role to provide access to requesting user{" "}
+ <b>{requesterStatus.userLabel}</b>.
+ </span>
+ </AlertDescription>
+ </Alert>
+ )}
+ {requesterEmail && !requesterStatus.isProjectUser && !requesterUserId && (
+ <Alert>
+ <AlertDescription>
+ <span>
+ No member of {currentOrg.name} matches <b>{requesterEmail}</b>.
+ </span>
+ </AlertDescription>
+ </Alert>
+ )}
+
+ <DialogFooter>
+ <Button variant="outline" onClick={handleClose}>
+ Cancel
+ </Button>
+ <Button
+ variant="av"
+ isPending={addMembers.isPending}
+ isDisabled={selected.length === 0}
+ onClick={handleAdd}
+ >
+ Add Users
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsx
new file mode 100644
index 0000000000..a6c56b0387
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsx
@@ -0,0 +1,250 @@
+import { useEffect, useMemo, useState } from "react";
+import { useSearch } from "@tanstack/react-router";
+import { MoreHorizontalIcon, PencilIcon, PlusIcon, SearchIcon, Trash2Icon } from "lucide-react";
+
+import { PendingInvitationBadge } from "@app/components/agent-vault/PendingInvitationBadge";
+import { ProductRoleBadge } from "@app/components/agent-vault/ProductRoleBadge";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { HighlightText } from "@app/components/v2/HighlightText";
+import {
+ Button,
+ Card,
+ CardContent,
+ DeleteConfirmDialog,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionMemberActions,
+ ProjectPermissionSub,
+ useProjectPermission,
+ useUser
+} from "@app/context";
+import {
+ useListAgentVaultProductUserMembers,
+ useRemoveAgentVaultProductMember
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultProductUserMember } from "@app/hooks/api/agentVault/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { InviteMembersDialog } from "./InviteMembersDialog";
+import { ProductRoleDialog } from "./ProductRoleDialog";
+
+const fullName = (member: TAgentVaultProductUserMember) =>
+ `${member.firstName ?? ""} ${member.lastName ?? ""}`.trim();
+
+const displayName = (member: TAgentVaultProductUserMember) =>
+ fullName(member) || member.username || member.email || "";
+
+export const MembersTab = () => {
+ const { user } = useUser();
+ const { data: members = [], isPending } = useListAgentVaultProductUserMembers();
+ const removeMember = useRemoveAgentVaultProductMember();
+
+ const [search, setSearch] = useState("");
+ const [isInviteOpen, setIsInviteOpen] = useState(false);
+ const [memberToEdit, setMemberToEdit] = useState<TAgentVaultProductUserMember | null>(null);
+ const [memberToRemove, setMemberToRemove] = useState<TAgentVaultProductUserMember | null>(null);
+
+ const { permission } = useProjectPermission();
+ const canAddMembers = permission.can(
+ ProjectPermissionMemberActions.Create,
+ ProjectPermissionSub.Member
+ );
+ const requesterEmail = useSearch({
+ strict: false,
+ select: (el) => (el as { requesterEmail?: string })?.requesterEmail
+ });
+
+ // An access-request notification links here with the requester in the URL.
+ useEffect(() => {
+ if (requesterEmail && canAddMembers) setIsInviteOpen(true);
+ }, [requesterEmail, canAddMembers]);
+
+ const filtered = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ if (!term) return members;
+ return members.filter(
+ (member) =>
+ displayName(member).toLowerCase().includes(term) ||
+ (member.email ?? "").toLowerCase().includes(term)
+ );
+ }, [members, search]);
+
+ const handleRemove = async () => {
+ try {
+ if (!memberToRemove?.userId) return;
+ await removeMember.mutateAsync({ userId: memberToRemove.userId });
+ createNotification({
+ text: `${displayName(memberToRemove)} removed`,
+ type: "success"
+ });
+ setMemberToRemove(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Card>
+ <CardContent className="flex items-center gap-3">
+ <InputGroup className="flex-1">
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search users..."
+ />
+ </InputGroup>
+ <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Member}>
+ {(isAllowed) => (
+ <Button variant="av" isDisabled={!isAllowed} onClick={() => setIsInviteOpen(true)}>
+ <PlusIcon />
+ Add Users
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </CardContent>
+
+ {!isPending && filtered.length === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>{search ? "No users match your search" : "No users yet"}</EmptyTitle>
+ <EmptyDescription>
+ {search ? "Try a different search term." : "Add users to give them access."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead isTruncatable className="w-1/3">
+ Name
+ </TableHead>
+ <TableHead isTruncatable className="w-1/3">
+ Email
+ </TableHead>
+ <TableHead>Product Role</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 3 }).map((_, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`member-skeleton-${index}`}>
+ {Array.from({ length: 4 }).map((__, cell) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableCell key={`member-skeleton-${index}-${cell}`}>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {!isPending &&
+ filtered.map((member) => {
+ const isSelf = member.userId === user?.id;
+ const name = fullName(member);
+
+ return (
+ <TableRow key={member.membershipId}>
+ <TableCell isTruncatable className="min-w-32" title={name || undefined}>
+ {name ? (
+ <HighlightText text={name} highlight={search} />
+ ) : (
+ <span className="text-muted">—</span>
+ )}
+ </TableCell>
+ <TableCell
+ isTruncatable
+ className="min-w-32 text-sm"
+ title={member.email || member.username}
+ >
+ <HighlightText text={member.email || member.username} highlight={search} />
+ </TableCell>
+ <TableCell>
+ <ProductRoleBadge role={member.role} />
+ </TableCell>
+ <TableCell variant="action">
+ <div className="flex items-center justify-end gap-2">
+ <PendingInvitationBadge isPending={member.isOrgMembershipPending} />
+ {!isSelf && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open user actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem onClick={() => setMemberToEdit(member)}>
+ <PencilIcon />
+ Change Role
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setMemberToRemove(member)}
+ >
+ <Trash2Icon />
+ Remove
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+
+ <InviteMembersDialog isOpen={isInviteOpen} onOpenChange={setIsInviteOpen} />
+
+ <ProductRoleDialog
+ isOpen={Boolean(memberToEdit)}
+ onOpenChange={() => setMemberToEdit(null)}
+ subject={memberToEdit ? displayName(memberToEdit) : ""}
+ currentRole={memberToEdit?.role ?? ProjectMembershipRole.Member}
+ actor={memberToEdit?.userId ? { userId: memberToEdit.userId } : {}}
+ />
+
+ <DeleteConfirmDialog
+ isOpen={Boolean(memberToRemove)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setMemberToRemove(null);
+ }}
+ title={`Remove "${memberToRemove ? displayName(memberToRemove) : ""}"`}
+ description="They lose every access bundle granted to them, and any live session stops reaching its hosts at the next proxy poll."
+ confirmKey={memberToRemove ? displayName(memberToRemove) : ""}
+ confirmLabel="Remove"
+ isPending={removeMember.isPending}
+ onConfirm={handleRemove}
+ />
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsx
new file mode 100644
index 0000000000..0eaf1dcf2f
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsx
@@ -0,0 +1,79 @@
+import { useEffect, useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel
+} from "@app/components/v3";
+import { useUpdateAgentVaultProductMemberRole } from "@app/hooks/api/agentVault";
+import { TAgentVaultProductMemberActor } from "@app/hooks/api/agentVault/types";
+
+import { ProductRoleField } from "./ProductRoleField";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ subject: string;
+ currentRole: string;
+ actor: TAgentVaultProductMemberActor;
+};
+
+export const ProductRoleDialog = ({ isOpen, onOpenChange, subject, currentRole, actor }: Props) => {
+ const updateRole = useUpdateAgentVaultProductMemberRole();
+ const [role, setRole] = useState(currentRole);
+
+ useEffect(() => {
+ if (isOpen) setRole(currentRole);
+ }, [isOpen, currentRole]);
+
+ const handleSave = async () => {
+ try {
+ await updateRole.mutateAsync({ ...actor, role });
+ createNotification({
+ text: `${subject} is now ${role === "admin" ? "an Admin" : "a Member"}`,
+ type: "success"
+ });
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Change Role</DialogTitle>
+ <DialogDescription>What {subject} can do here.</DialogDescription>
+ </DialogHeader>
+ <Field>
+ <FieldLabel>Product Role</FieldLabel>
+ <FieldContent>
+ <ProductRoleField value={role} onChange={setRole} idPrefix="change-role" />
+ </FieldContent>
+ </Field>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="av"
+ isPending={updateRole.isPending}
+ isDisabled={role === currentRole}
+ onClick={handleSave}
+ >
+ Save
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleField.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleField.tsx
new file mode 100644
index 0000000000..9376ec2983
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleField.tsx
@@ -0,0 +1,36 @@
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldLabel,
+ FieldTitle,
+ RadioGroup,
+ RadioGroupItem
+} from "@app/components/v3";
+import { AGENT_VAULT_PRODUCT_ROLE_OPTIONS } from "@app/helpers/roles";
+
+type Props = {
+ value: string;
+ onChange: (role: string) => void;
+ idPrefix: string;
+};
+
+export const ProductRoleField = ({ value, onChange, idPrefix }: Props) => (
+ <RadioGroup value={value} onValueChange={onChange}>
+ {AGENT_VAULT_PRODUCT_ROLE_OPTIONS.map((role) => {
+ const id = `${idPrefix}-${role.value}`;
+
+ return (
+ <FieldLabel key={role.value} htmlFor={id} variant="av">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>{role.label}</FieldTitle>
+ <FieldDescription>{role.description}</FieldDescription>
+ </FieldContent>
+ <RadioGroupItem id={id} value={role.value} />
+ </Field>
+ </FieldLabel>
+ );
+ })}
+ </RadioGroup>
+);
diff --git a/frontend/src/pages/agent-vault/AgentVaultAuditLogsPage/AgentVaultAuditLogsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAuditLogsPage/AgentVaultAuditLogsPage.tsx
new file mode 100644
index 0000000000..c307808519
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAuditLogsPage/AgentVaultAuditLogsPage.tsx
@@ -0,0 +1,28 @@
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { FileText } from "lucide-react";
+
+import { PageHeader } from "@app/components/v3";
+import { useProject } from "@app/context";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { LogsSection } from "@app/pages/organization/AuditLogsPage/components";
+
+export const AgentVaultAuditLogsPage = () => {
+ const { t } = useTranslation();
+ const { currentProject } = useProject();
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Helmet>
+ <title>{t("common.head-title", { title: "Audit Logs" })}</title>
+ </Helmet>
+ <PageHeader
+ scope={ProjectType.AgentVault}
+ icon={FileText}
+ title="Audit Logs"
+ description="Audit logs for security and compliance teams to monitor information access."
+ />
+ <LogsSection pageView project={currentProject} />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultAuditLogsPage/index.tsx b/frontend/src/pages/agent-vault/AgentVaultAuditLogsPage/index.tsx
new file mode 100644
index 0000000000..a530b37df1
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultAuditLogsPage/index.tsx
@@ -0,0 +1 @@
+export { AgentVaultAuditLogsPage } from "./AgentVaultAuditLogsPage";
diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx
new file mode 100644
index 0000000000..91f689bace
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx
@@ -0,0 +1,480 @@
+import { ReactNode, useMemo, useState } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { format } from "date-fns";
+import {
+ BanIcon,
+ ChevronDownIcon,
+ MoreHorizontalIcon,
+ PencilIcon,
+ PlusIcon,
+ RefreshCwIcon,
+ RouteIcon,
+ TrashIcon,
+ TriangleAlertIcon
+} from "lucide-react";
+import { twMerge } from "tailwind-merge";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ CopyButton,
+ DeleteConfirmDialog,
+ DocumentationLinkBadge,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ PageHeader,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useProjectPermission } from "@app/context";
+import {
+ AgentVaultTrafficPolicy,
+ useDeleteAgentVaultProxy,
+ useListAgentVaultProxies,
+ useReissueAgentVaultProxyEnrollmentToken,
+ useRevokeAgentVaultProxyAccess
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultEnrollment, TAgentVaultProxy } from "@app/hooks/api/agentVault/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { AgentVaultDocsUrls } from "../agent-vault-docs-urls";
+import { ProxyEnrollmentDialog } from "./components/ProxyEnrollmentDialog";
+import { ProxyFormDialog } from "./components/ProxyFormDialog";
+import { ProxyStatusBadge } from "./components/ProxyStatusBadge";
+
+const allowedHostsOf = (proxy: TAgentVaultProxy) =>
+ proxy.allowedHosts
+ ? proxy.allowedHosts
+ .split(",")
+ .map((host) => host.trim())
+ .filter(Boolean)
+ : [];
+
+const TrafficPolicyCell = ({ proxy }: { proxy: TAgentVaultProxy }) => {
+ const isBundleOnly = proxy.trafficPolicy === AgentVaultTrafficPolicy.BundleHosts;
+ const allowedHosts = isBundleOnly ? allowedHostsOf(proxy) : [];
+
+ const cell = (
+ <span>
+ {isBundleOnly ? "Access bundle hosts only" : "Any host"}
+ {allowedHosts.length > 0 &&
+ ` · ${allowedHosts.length} ${allowedHosts.length === 1 ? "exception" : "exceptions"}`}
+ </span>
+ );
+
+ if (allowedHosts.length === 0) return cell;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>{cell}</TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ <ul className="font-mono text-xs">
+ {allowedHosts.map((host) => (
+ <li key={host}>{host}</li>
+ ))}
+ </ul>
+ </TooltipContent>
+ </Tooltip>
+ );
+};
+
+const HeadWithHint = ({ hint, children }: { hint: string; children: ReactNode }) => (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-help underline decoration-muted decoration-dotted underline-offset-4">
+ {children}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">{hint}</TooltipContent>
+ </Tooltip>
+);
+
+enum SortColumn {
+ Name = "name",
+ Created = "created"
+}
+
+const SORT_COMPARATORS: Record<SortColumn, (a: TAgentVaultProxy, b: TAgentVaultProxy) => number> = {
+ [SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),
+ [SortColumn.Created]: (a, b) =>
+ new Date(a.createdAt ?? 0).getTime() - new Date(b.createdAt ?? 0).getTime()
+};
+
+const truncateFingerprint = (fingerprint: string) =>
+ `${fingerprint.split(":").slice(0, 5).join(":")}…`;
+
+export const AgentVaultProxiesPage = () => {
+ const { t } = useTranslation();
+ const { hasProjectRole } = useProjectPermission();
+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+
+ const { data: proxies, isPending } = useListAgentVaultProxies();
+ const deleteProxy = useDeleteAgentVaultProxy();
+ const revokeProxy = useRevokeAgentVaultProxyAccess();
+ const reissueToken = useReissueAgentVaultProxyEnrollmentToken();
+
+ const [isCreateOpen, setIsCreateOpen] = useState(false);
+ const [proxyToEdit, setProxyToEdit] = useState<TAgentVaultProxy | null>(null);
+ const [proxyToDelete, setProxyToDelete] = useState<TAgentVaultProxy | null>(null);
+ const [proxyToRevoke, setProxyToRevoke] = useState<TAgentVaultProxy | null>(null);
+ const [proxyToReissue, setProxyToReissue] = useState<TAgentVaultProxy | null>(null);
+ const [enrollment, setEnrollment] = useState<TAgentVaultEnrollment | null>(null);
+ const [sortColumn, setSortColumn] = useState(SortColumn.Created);
+ const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("descending");
+
+ const displayed = useMemo(() => {
+ const ordered = [...(proxies ?? [])].sort(SORT_COMPARATORS[sortColumn]);
+ return sortDirection === "ascending" ? ordered : ordered.reverse();
+ }, [proxies, sortColumn, sortDirection]);
+
+ const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {
+ if (direction === "none") {
+ setSortColumn(SortColumn.Created);
+ setSortDirection("descending");
+ return;
+ }
+ setSortColumn(column);
+ setSortDirection(direction);
+ };
+
+ const sortIconClassName = (column: SortColumn) =>
+ twMerge(
+ "size-3 transition-transform",
+ sortColumn === column && sortDirection === "descending" && "rotate-180",
+ sortColumn !== column && "opacity-30"
+ );
+
+ const handleDelete = async () => {
+ try {
+ if (!proxyToDelete) return;
+ await deleteProxy.mutateAsync(proxyToDelete.id);
+ createNotification({ text: `Proxy "${proxyToDelete.name}" deleted`, type: "success" });
+ setProxyToDelete(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ const handleRevoke = async () => {
+ if (!proxyToRevoke) return;
+
+ try {
+ await revokeProxy.mutateAsync(proxyToRevoke.id);
+ createNotification({ text: `Proxy "${proxyToRevoke.name}" revoked`, type: "success" });
+ setProxyToRevoke(null);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ const handleReissue = async () => {
+ if (!proxyToReissue) return;
+
+ try {
+ const result = await reissueToken.mutateAsync(proxyToReissue.id);
+ setProxyToReissue(null);
+ setEnrollment(result);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Helmet>
+ <title>{t("common.head-title", { title: "Proxies" })}</title>
+ </Helmet>
+ <PageHeader
+ scope={ProjectType.AgentVault}
+ icon={RouteIcon}
+ title="Proxies"
+ description="Manage the proxies your agents route through."
+ />
+
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Proxies
+ <DocumentationLinkBadge href={AgentVaultDocsUrls.proxies} />
+ </CardTitle>
+ <CardDescription>An agent points its HTTP traffic at one of these.</CardDescription>
+ {isAdmin && (
+ <CardAction>
+ <Button variant="av" onClick={() => setIsCreateOpen(true)}>
+ <PlusIcon />
+ Create Proxy
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+
+ {!isPending && (proxies?.length ?? 0) === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No proxies yet</EmptyTitle>
+ <EmptyDescription>
+ Create a proxy and enroll it where agent traffic leaves your network.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Name ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Name, direction)}
+ >
+ Name
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Name)} />
+ </TableHead>
+ <TableHead>Status</TableHead>
+ {isAdmin && (
+ <TableHead>
+ <HeadWithHint hint="Which hosts an agent may reach through this proxy.">
+ Traffic Policy
+ </HeadWithHint>
+ </TableHead>
+ )}
+ <TableHead>
+ <HeadWithHint hint="Pass it to infisical agent-vault run --ca-fingerprint so the agent refuses any proxy but this one.">
+ Certificate Authority
+ </HeadWithHint>
+ </TableHead>
+ {isAdmin && (
+ <TableHead
+ sortDirection={sortColumn === SortColumn.Created ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.Created, direction)}
+ >
+ Created
+ <ChevronDownIcon className={sortIconClassName(SortColumn.Created)} />
+ </TableHead>
+ )}
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 3 }).map((_, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`proxy-skeleton-${index}`}>
+ {Array.from({ length: isAdmin ? 6 : 4 }).map((__, cell) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableCell key={`proxy-skeleton-${index}-${cell}`}>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {!isPending &&
+ displayed.map((proxy) => (
+ <TableRow key={proxy.id}>
+ <TableCell>{proxy.name}</TableCell>
+ <TableCell>
+ <ProxyStatusBadge proxy={proxy} />
+ </TableCell>
+ {isAdmin && (
+ <TableCell>
+ <TrafficPolicyCell proxy={proxy} />
+ </TableCell>
+ )}
+ <TableCell>
+ {proxy.rootCaFingerprint ? (
+ <div className="flex items-center gap-1">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="font-mono text-xs">
+ {truncateFingerprint(proxy.rootCaFingerprint)}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{proxy.rootCaFingerprint}</TooltipContent>
+ </Tooltip>
+ <CopyButton
+ value={proxy.rootCaFingerprint}
+ ariaLabel="Copy certificate authority fingerprint"
+ variant="ghost"
+ size="xs"
+ />
+ </div>
+ ) : (
+ <span className="text-muted">&mdash;</span>
+ )}
+ </TableCell>
+ {isAdmin && (
+ <TableCell>
+ {proxy.createdAt ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">
+ {format(new Date(proxy.createdAt), "MMM d, yyyy")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {format(new Date(proxy.createdAt), "MMM d, yyyy h:mm a")}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="text-muted">&mdash;</span>
+ )}
+ </TableCell>
+ )}
+ <TableCell variant="action">
+ {isAdmin && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open proxy actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem onClick={() => setProxyToEdit(proxy)}>
+ <PencilIcon />
+ Edit Settings
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setProxyToReissue(proxy)}>
+ <RefreshCwIcon />
+ New Enrollment Token
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setProxyToRevoke(proxy)}
+ >
+ <BanIcon />
+ Revoke Access
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setProxyToDelete(proxy)}
+ >
+ <TrashIcon />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </Card>
+
+ <ProxyFormDialog
+ isOpen={isCreateOpen}
+ onOpenChange={setIsCreateOpen}
+ onCreated={setEnrollment}
+ />
+
+ <ProxyFormDialog
+ isOpen={Boolean(proxyToEdit)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setProxyToEdit(null);
+ }}
+ proxy={proxyToEdit ?? undefined}
+ />
+
+ <ProxyEnrollmentDialog
+ enrollment={enrollment}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setEnrollment(null);
+ }}
+ />
+
+ <AlertDialog
+ open={Boolean(proxyToReissue)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setProxyToReissue(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <TriangleAlertIcon />
+ </AlertDialogMedia>
+ <AlertDialogTitle>
+ New enrollment token for &quot;{proxyToReissue?.name}&quot;
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ The proxy keeps serving until it re-enrolls with the new token. Re-enrolling gives it
+ a new certificate authority, so every agent running through it has to trust the new
+ one before its requests work again.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="av"
+ isPending={reissueToken.isPending}
+ onClick={async (event) => {
+ event.preventDefault();
+ await handleReissue();
+ }}
+ >
+ Generate Token
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <DeleteConfirmDialog
+ isOpen={Boolean(proxyToRevoke)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setProxyToRevoke(null);
+ }}
+ title={`Revoke "${proxyToRevoke?.name}"`}
+ description="Its token stops working at its next poll. Every agent routed through it loses its credentials until the proxy enrolls again."
+ confirmKey={proxyToRevoke?.name ?? ""}
+ confirmLabel="Revoke Access"
+ isPending={revokeProxy.isPending}
+ onConfirm={handleRevoke}
+ />
+
+ <DeleteConfirmDialog
+ isOpen={Boolean(proxyToDelete)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setProxyToDelete(null);
+ }}
+ title={`Delete "${proxyToDelete?.name}"`}
+ description="Agents routed through it lose their credentials. This cannot be undone."
+ confirmKey={proxyToDelete?.name ?? ""}
+ isPending={deleteProxy.isPending}
+ onConfirm={handleDelete}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyEnrollmentDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyEnrollmentDialog.tsx
new file mode 100644
index 0000000000..c9b31e82d6
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyEnrollmentDialog.tsx
@@ -0,0 +1,128 @@
+import { ReactNode } from "react";
+import { TriangleAlertIcon } from "lucide-react";
+
+import {
+ Alert,
+ AlertDescription,
+ Badge,
+ Button,
+ CodeBlock,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger
+} from "@app/components/v3";
+import { useTimeRemaining } from "@app/hooks";
+import { TAgentVaultEnrollment } from "@app/hooks/api/agentVault/types";
+
+const cliCommand = (token: string, siteUrl: string) =>
+ `infisical agent-vault proxy \\
+ --enrollment-token ${token} \\
+ --domain ${siteUrl}`;
+
+const dockerCommand = (token: string, siteUrl: string) =>
+ `docker run -d --name agent-vault-proxy \\
+ -p 17323:17323 \\
+ -v agent-vault-proxy:/etc/infisical/agent-vault \\
+ infisical/cli agent-vault proxy \\
+ --enrollment-token ${token} \\
+ --domain ${siteUrl}`;
+
+const systemdUnit = (token: string, siteUrl: string) =>
+ `[Unit]
+Description=Infisical Agent Vault proxy
+After=network-online.target
+
+[Service]
+ExecStart=/usr/local/bin/infisical agent-vault proxy --enrollment-token ${token} --domain ${siteUrl}
+Restart=always
+
+[Install]
+WantedBy=multi-user.target`;
+
+type Props = {
+ enrollment: TAgentVaultEnrollment | null;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const ProxyEnrollmentDialog = ({ enrollment, onOpenChange }: Props) => {
+ const token = enrollment?.token ?? "";
+ const { protocol, hostname, port } = window.location;
+ const siteUrl = `${protocol}//${hostname}${port && port !== "80" ? `:${port}` : ""}`;
+ const { label: expiryLabel, isExpired } = useTimeRemaining(enrollment?.expiresAt);
+
+ const labelWithExpiry = (text: string): ReactNode => (
+ <span className="flex w-full items-center justify-between gap-2">
+ <span>{text}</span>
+ <Badge className="tabular-nums" variant={isExpired ? "danger" : "neutral"}>
+ {expiryLabel}
+ </Badge>
+ </span>
+ );
+
+ return (
+ <Dialog open={Boolean(enrollment)} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-2xl" onInteractOutside={(event) => event.preventDefault()}>
+ <DialogHeader>
+ <DialogTitle>Enrollment Token</DialogTitle>
+ <DialogDescription>
+ Run this where the proxy lives. It enrolls once and keeps its own certificate after
+ that.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4">
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertDescription>
+ {isExpired
+ ? "This token has expired. Generate a new one from the proxy's menu."
+ : "This token is shown once and expires in an hour. Copy it now, it cannot be retrieved later."}
+ </AlertDescription>
+ </Alert>
+
+ <Tabs defaultValue="cli">
+ <TabsList variant="av" aria-label="Deployment target">
+ <TabsTrigger value="cli">CLI</TabsTrigger>
+ <TabsTrigger value="docker">Docker</TabsTrigger>
+ <TabsTrigger value="systemd">systemd</TabsTrigger>
+ </TabsList>
+ <TabsContent value="cli">
+ <CodeBlock
+ value={cliCommand(token, siteUrl)}
+ label={labelWithExpiry("Command")}
+ isCopyable={!isExpired}
+ />
+ </TabsContent>
+ <TabsContent value="docker">
+ <CodeBlock
+ value={dockerCommand(token, siteUrl)}
+ label={labelWithExpiry("Command")}
+ isCopyable={!isExpired}
+ />
+ </TabsContent>
+ <TabsContent value="systemd">
+ <CodeBlock
+ value={systemdUnit(token, siteUrl)}
+ label={labelWithExpiry("Unit file")}
+ isCopyable={!isExpired}
+ />
+ </TabsContent>
+ </Tabs>
+ </div>
+
+ <DialogFooter>
+ <Button variant="av" onClick={() => onOpenChange(false)}>
+ Done
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx
new file mode 100644
index 0000000000..e5877b6b69
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx
@@ -0,0 +1,261 @@
+import { useEffect } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { InfoIcon } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Alert,
+ AlertDescription,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldTitle,
+ Input,
+ RadioGroup,
+ RadioGroupItem,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { addHostListIssues } from "@app/helpers/agentVaultHostPattern";
+import {
+ AgentVaultTrafficPolicy,
+ useCreateAgentVaultProxy,
+ useUpdateAgentVaultProxy
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultEnrollment, TAgentVaultProxy } from "@app/hooks/api/agentVault/types";
+import { slugSchema } from "@app/lib/schemas";
+
+const TRAFFIC_POLICY_CHOICES = [
+ {
+ value: AgentVaultTrafficPolicy.AnyHost,
+ title: "Any host",
+ description: "Allow requests to reach any host."
+ },
+ {
+ value: AgentVaultTrafficPolicy.BundleHosts,
+ title: "Access bundle hosts only",
+ description: "Only allow requests to reach hosts specified in access bundles."
+ }
+];
+
+const schema = z
+ .object({
+ name: slugSchema({ max: 64, field: "Name" }),
+ trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy),
+ allowedHosts: z.string().trim().max(1024).optional(),
+ // Guarded before coercion: z.coerce turns "" into 0, which would report the range error instead.
+ pollInterval: z
+ .string()
+ .or(z.number())
+ .refine((value) => String(value).trim() !== "", "Poll interval is required")
+ .pipe(
+ z.coerce
+ .number({ invalid_type_error: "Poll interval is required" })
+ .int("Poll interval must be a whole number of seconds")
+ .min(10, "Poll interval must be at least 10 seconds")
+ .max(300, "Poll interval must be at most 300 seconds")
+ )
+ })
+ // Only under the bundle-hosts policy, where the field is on screen: an any-host proxy ignores the
+ // list, and a stale value in a hidden field would block Save with an error nothing shows.
+ .superRefine((data, ctx) => {
+ if (data.trafficPolicy !== AgentVaultTrafficPolicy.BundleHosts) return;
+ addHostListIssues(data.allowedHosts, ctx, ["allowedHosts"]);
+ });
+
+type FormData = z.infer<typeof schema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ proxy?: TAgentVaultProxy;
+ onCreated?: (enrollment: TAgentVaultEnrollment) => void;
+};
+
+export const ProxyFormDialog = ({ isOpen, onOpenChange, proxy, onCreated }: Props) => {
+ const createProxy = useCreateAgentVaultProxy();
+ const updateProxy = useUpdateAgentVaultProxy();
+ const isUpdate = Boolean(proxy);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ formState: { isSubmitting }
+ } = useForm<FormData>({ resolver: zodResolver(schema) });
+
+ const isBundleOnly = watch("trafficPolicy") === AgentVaultTrafficPolicy.BundleHosts;
+
+ const saveDelayNote = (() => {
+ if (!proxy?.heartbeat) return null;
+ return proxy.isHealthy
+ ? "This proxy picks up the change on its next poll."
+ : "This proxy is not connected right now. It picks up the change when it reconnects.";
+ })();
+
+ useEffect(() => {
+ if (!isOpen) return;
+
+ reset({
+ name: proxy?.name ?? "",
+ trafficPolicy: proxy?.trafficPolicy ?? AgentVaultTrafficPolicy.AnyHost,
+ allowedHosts: proxy?.allowedHosts ?? "",
+ pollInterval: proxy?.pollInterval ?? 60
+ });
+ }, [isOpen, proxy, reset]);
+
+ const onSubmit = async (data: FormData) => {
+ try {
+ const payload = {
+ name: data.name,
+ trafficPolicy: data.trafficPolicy,
+ allowedHosts: data.allowedHosts ? data.allowedHosts : null,
+ pollInterval: data.pollInterval
+ };
+
+ if (proxy) {
+ await updateProxy.mutateAsync({ proxyId: proxy.id, ...payload });
+ createNotification({ text: `Proxy "${data.name}" updated`, type: "success" });
+ } else {
+ const result = await createProxy.mutateAsync(payload);
+ createNotification({ text: `Proxy "${data.name}" created`, type: "success" });
+ onCreated?.({ token: result.token, expiresAt: result.expiresAt });
+ }
+
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ {/* DialogContent spaces its own children; the form is the only one, so it has to carry the layout. */}
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-6">
+ <DialogHeader>
+ <DialogTitle>{isUpdate ? "Edit Settings" : "Create Proxy"}</DialogTitle>
+ <DialogDescription>
+ Set how this proxy handles your agents&apos; requests.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="egress-1" isError={Boolean(fieldState.error)} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="trafficPolicy"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Traffic Policy</FieldLabel>
+ <FieldContent>
+ <RadioGroup value={field.value} onValueChange={field.onChange}>
+ {TRAFFIC_POLICY_CHOICES.map((choice) => {
+ const id = `traffic-policy-${choice.value}`;
+
+ return (
+ <FieldLabel key={choice.value} htmlFor={id} variant="av">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>{choice.title}</FieldTitle>
+ <FieldDescription>{choice.description}</FieldDescription>
+ </FieldContent>
+ <RadioGroupItem id={id} value={choice.value} />
+ </Field>
+ </FieldLabel>
+ );
+ })}
+ </RadioGroup>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ {isBundleOnly && (
+ <Controller
+ control={control}
+ name="allowedHosts"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Exceptions</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ placeholder="registry.npmjs.org, proxy.golang.org"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+ <Controller
+ control={control}
+ name="pollInterval"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Poll Interval
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ How often the proxy asks for its configuration, in seconds. It is how long a
+ change here takes to reach a running agent.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} type="number" isError={Boolean(fieldState.error)} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ {saveDelayNote && (
+ <Alert variant="info">
+ <InfoIcon />
+ <AlertDescription>{saveDelayNote}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="av" isPending={isSubmitting}>
+ {isUpdate ? "Save" : "Create"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsx
new file mode 100644
index 0000000000..e694cc88c9
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsx
@@ -0,0 +1,33 @@
+import { format, formatDistanceToNowStrict } from "date-fns";
+import { CircleCheckIcon, CircleDashedIcon, CircleSlashIcon } from "lucide-react";
+
+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+import { TAgentVaultProxy } from "@app/hooks/api/agentVault/types";
+
+export const ProxyStatusBadge = ({ proxy }: { proxy: TAgentVaultProxy }) => {
+ if (!proxy.heartbeat) {
+ return (
+ <Badge variant="neutral">
+ <CircleDashedIcon />
+ {proxy.rootCaFingerprint ? "Not connected" : "Never enrolled"}
+ </Badge>
+ );
+ }
+
+ const heartbeat = new Date(proxy.heartbeat);
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant={proxy.isHealthy ? "success" : "warning"}>
+ {proxy.isHealthy ? <CircleCheckIcon /> : <CircleSlashIcon />}
+ {proxy.isHealthy ? "Healthy" : "Unreachable"}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ Last seen {formatDistanceToNowStrict(heartbeat)} ago,{" "}
+ {format(heartbeat, "MMM d, yyyy h:mm a")}
+ </TooltipContent>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/route.tsx
new file mode 100644
index 0000000000..4a4878db00
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/route.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AgentVaultProxiesPage } from "./AgentVaultProxiesPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies"
+)({
+ component: AgentVaultProxiesPage,
+ beforeLoad: ({ context }) => {
+ return { breadcrumbs: [...context.breadcrumbs, { label: "Proxies" }] };
+ }
+});
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
new file mode 100644
index 0000000000..46d8d29216
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
@@ -0,0 +1,396 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { Link, linkOptions } from "@tanstack/react-router";
+import { format } from "date-fns";
+import {
+ BanIcon,
+ BotIcon,
+ IdCardIcon,
+ MoreHorizontalIcon,
+ PackageIcon,
+ PlusIcon,
+ SearchIcon,
+ UserIcon
+} from "lucide-react";
+
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DocumentationLinkBadge,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ OverflowBadgeList,
+ PageHeader,
+ Pagination,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useOrganization, useProjectPermission } from "@app/context";
+import {
+ getUserTablePreference,
+ PreferenceKey,
+ setUserTablePreference
+} from "@app/helpers/userTablePreferences";
+import { useDebounce, useResetPageHelper } from "@app/hooks";
+import {
+ AgentVaultSessionScope,
+ AgentVaultSessionStatus,
+ useListAgentVaultAccessBundles,
+ useListAgentVaultSessions
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultMintedSession, TAgentVaultSession } from "@app/hooks/api/agentVault/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+
+import { AgentVaultDocsUrls } from "../agent-vault-docs-urls";
+import { CreateSessionDialog } from "./components/CreateSessionDialog";
+import { RevokeSessionDialog } from "./components/RevokeSessionDialog";
+import { SessionCreatedDialog } from "./components/SessionCreatedDialog";
+import { SessionExpiry } from "./components/SessionExpiry";
+import { SessionStatusBadge } from "./components/SessionStatusBadge";
+
+const ALL_STATUSES = "all";
+
+export const AgentVaultSessionsPage = () => {
+ const { t } = useTranslation();
+ const { currentOrg } = useOrganization();
+ const { hasProjectRole } = useProjectPermission();
+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
+ const [statusFilter, setStatusFilter] = useState<AgentVaultSessionStatus | typeof ALL_STATUSES>(
+ ALL_STATUSES
+ );
+ const [scope, setScope] = useState(AgentVaultSessionScope.Mine);
+ const [page, setPage] = useState(1);
+ const [perPage, setPerPage] = useState(() =>
+ getUserTablePreference("agentVaultSessionsTable", PreferenceKey.PerPage, 20)
+ );
+ const [sessionToRevoke, setSessionToRevoke] = useState<TAgentVaultSession | null>(null);
+ const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
+ const [mintedSession, setMintedSession] = useState<TAgentVaultMintedSession | null>(null);
+
+ const { data, isPending } = useListAgentVaultSessions({
+ scope: isAdmin ? scope : AgentVaultSessionScope.Mine,
+ status: statusFilter === ALL_STATUSES ? undefined : statusFilter,
+ search: debouncedSearch.trim() || undefined,
+ limit: perPage,
+ offset: (page - 1) * perPage
+ });
+ const { data: accessBundles } = useListAgentVaultAccessBundles();
+
+ const sessions = data?.sessions ?? [];
+ const totalCount = data?.totalCount ?? 0;
+
+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });
+
+ // The debounced term, not the typed one: the rows on screen were fetched with this, so keying the copy
+ // off the live input would caption a stale result set.
+ const isFiltered = Boolean(debouncedSearch.trim()) || statusFilter !== ALL_STATUSES;
+ const hasReachableBundles = (accessBundles?.length ?? 0) > 0;
+
+ let emptyTitle: string;
+ let emptyDescription: string;
+ if (isFiltered) {
+ emptyTitle = "No sessions match these filters";
+ emptyDescription = "Try a different search term or status.";
+ } else if (!hasReachableBundles) {
+ emptyTitle = isAdmin ? "No sessions yet" : "No access bundles granted to you";
+ emptyDescription = isAdmin
+ ? "Create an access bundle first, then mint a session over it. Agents also need a proxy to route through."
+ : "Ask an admin to grant you an access bundle.";
+ } else {
+ emptyTitle = "No sessions yet";
+ emptyDescription = "Create a session to get a token an agent can run with.";
+ }
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Helmet>
+ <title>{t("common.head-title", { title: "Sessions" })}</title>
+ </Helmet>
+ <PageHeader
+ scope={ProjectType.AgentVault}
+ icon={IdCardIcon}
+ title="Sessions"
+ description="What an agent runs with. Each session carries one access bundle."
+ />
+
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Sessions
+ <DocumentationLinkBadge href={AgentVaultDocsUrls.sessions} />
+ </CardTitle>
+ <CardDescription>
+ A session names one actor, the access bundle it carries, and when it expires.
+ </CardDescription>
+ <CardAction>
+ <Button
+ variant="av"
+ isDisabled={!hasReachableBundles}
+ onClick={() => setIsCreateDialogOpen(true)}
+ >
+ <PlusIcon />
+ Create Session
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex items-center gap-4">
+ <div className="flex-1">
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setPage(1);
+ }}
+ placeholder="Search by identity, email, or access bundle..."
+ />
+ </InputGroup>
+ </div>
+ <Select
+ value={statusFilter}
+ onValueChange={(value) => {
+ setStatusFilter(value as AgentVaultSessionStatus | typeof ALL_STATUSES);
+ setPage(1);
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={ALL_STATUSES}>All Statuses</SelectItem>
+ <SelectItem value={AgentVaultSessionStatus.Active}>Active</SelectItem>
+ <SelectItem value={AgentVaultSessionStatus.Revoked}>Revoked</SelectItem>
+ <SelectItem value={AgentVaultSessionStatus.Expired}>Expired</SelectItem>
+ </SelectContent>
+ </Select>
+ {isAdmin && (
+ <Select
+ value={scope}
+ onValueChange={(value) => {
+ setScope(value as AgentVaultSessionScope);
+ setPage(1);
+ }}
+ >
+ <SelectTrigger aria-label="Session scope">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={AgentVaultSessionScope.All}>All Sessions</SelectItem>
+ <SelectItem value={AgentVaultSessionScope.Mine}>My Sessions</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ </CardContent>
+
+ {!isPending && sessions.length === 0 ? (
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>{emptyTitle}</EmptyTitle>
+ <EmptyDescription>{emptyDescription}</EmptyDescription>
+ </EmptyHeader>
+ {!isFiltered && !hasReachableBundles && isAdmin && (
+ <Button variant="av" asChild>
+ <Link
+ to="/organizations/$orgId/agent-vault/access-bundles"
+ params={{ orgId: currentOrg.id }}
+ >
+ Go to Access Bundles
+ </Link>
+ </Button>
+ )}
+ </Empty>
+ </CardContent>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Identity</TableHead>
+ <TableHead>Access Bundle</TableHead>
+ <TableHead>Created</TableHead>
+ <TableHead>Expires</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 5 }).map((_, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`session-skeleton-${index}`}>
+ {Array.from({ length: 6 }).map((__, cell) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableCell key={`session-skeleton-${index}-${cell}`}>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {!isPending &&
+ sessions.map((session) => (
+ <TableRow key={session.id}>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex w-fit items-center gap-2">
+ {session.identityId ? (
+ <BotIcon className="size-4 text-muted" />
+ ) : (
+ <UserIcon className="size-4 text-muted" />
+ )}
+ {session.actorName}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {session.identityId
+ ? `${session.identityId} (machine identity)`
+ : session.actorEmail}
+ </TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell>
+ <div className="max-w-72">
+ <OverflowBadgeList
+ items={session.accessBundles}
+ getKey={(bundle) => bundle.id ?? bundle.name}
+ getLabel={(bundle) => bundle.name}
+ icon={<PackageIcon />}
+ getClassName={(bundle) => (bundle.id ? undefined : "text-muted")}
+ getTooltip={(bundle) =>
+ bundle.id ? bundle.name : `${bundle.name} (deleted)`
+ }
+ getLinkProps={(bundle) =>
+ bundle.id
+ ? linkOptions({
+ to: "/organizations/$orgId/agent-vault/access-bundles/$accessBundleId",
+ params: { orgId: currentOrg.id, accessBundleId: bundle.id }
+ })
+ : undefined
+ }
+ />
+ </div>
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">
+ {format(new Date(session.createdAt), "MMM d, yyyy")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {format(new Date(session.createdAt), "MMM d, yyyy h:mm a")}
+ </TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell>
+ <SessionExpiry expiresAt={session.expiresAt} />
+ </TableCell>
+ <TableCell>
+ <SessionStatusBadge status={session.status} />
+ </TableCell>
+ <TableCell variant="action">
+ {session.status === AgentVaultSessionStatus.Active && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open session actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setSessionToRevoke(session)}
+ >
+ <BanIcon />
+ Revoke Session
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+
+ {totalCount > 0 && (
+ // The card lays its children out with gap-5, which reads as a gap under the table.
+ <CardContent className="-mt-5 pt-0">
+ <Pagination
+ count={totalCount}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={(newPerPage) => {
+ setPerPage(newPerPage);
+ setPage(1);
+ setUserTablePreference(
+ "agentVaultSessionsTable",
+ PreferenceKey.PerPage,
+ newPerPage
+ );
+ }}
+ />
+ </CardContent>
+ )}
+ </Card>
+
+ <CreateSessionDialog
+ isOpen={isCreateDialogOpen}
+ onOpenChange={setIsCreateDialogOpen}
+ onCreated={setMintedSession}
+ />
+
+ <SessionCreatedDialog
+ session={mintedSession}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setMintedSession(null);
+ }}
+ />
+
+ <RevokeSessionDialog
+ session={sessionToRevoke}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setSessionToRevoke(null);
+ }}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
new file mode 100644
index 0000000000..dbb424b5b0
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
@@ -0,0 +1,249 @@
+import { useEffect, useRef, useState } from "react";
+import { PackageIcon } from "lucide-react";
+import ms from "ms";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Combobox,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DiscardChangesAlertDialog,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useDiscardChangesGuard } from "@app/hooks";
+import {
+ useCreateAgentVaultSession,
+ useListAgentVaultAccessBundles
+} from "@app/hooks/api/agentVault";
+import {
+ TAgentVaultAccessBundleListItem,
+ TAgentVaultMintedSession
+} from "@app/hooks/api/agentVault/types";
+
+const NEVER_TTL = "never";
+const CUSTOM_TTL = "custom";
+
+const TTL_PRESETS = [
+ { value: "1h", label: "1 hour" },
+ { value: "8h", label: "8 hours" },
+ { value: "24h", label: "24 hours" },
+ { value: "7d", label: "7 days" },
+ { value: NEVER_TTL, label: "Never" },
+ { value: CUSTOM_TTL, label: "Custom" }
+];
+const DEFAULT_TTL_PRESET = "7d";
+
+const MIN_TTL_MS = 60 * 1000;
+// Mirrors the API's ceiling: past it the expiry overflows and the request fails with a 500.
+const MAX_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
+
+const getCustomTtlError = (value: string) => {
+ let parsed: number | undefined;
+ try {
+ parsed = ms(value.trim() as Parameters<typeof ms>[0]);
+ } catch {
+ parsed = undefined;
+ }
+
+ if (typeof parsed !== "number" || Number.isNaN(parsed)) return "Not a valid duration.";
+ if (parsed < MIN_TTL_MS) return "At least 1 minute.";
+ if (parsed > MAX_TTL_MS) return "At most 100 years. Pick Never for no expiry.";
+ return null;
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ onCreated: (session: TAgentVaultMintedSession) => void;
+};
+
+export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props) => {
+ const { data: accessBundles } = useListAgentVaultAccessBundles();
+ const createSession = useCreateAgentVaultSession();
+
+ const [selectedBundle, setSelectedBundle] = useState<TAgentVaultAccessBundleListItem | null>(
+ null
+ );
+ const [ttlPreset, setTtlPreset] = useState(DEFAULT_TTL_PRESET);
+ const [customTtl, setCustomTtl] = useState("");
+ const customTtlInputRef = useRef<HTMLInputElement>(null);
+ const shouldFocusCustomTtlRef = useRef(false);
+
+ const isCustomTtl = ttlPreset === CUSTOM_TTL;
+ const ttl = isCustomTtl ? customTtl.trim() : ttlPreset;
+ const customTtlError = isCustomTtl ? getCustomTtlError(customTtl) : null;
+ const isTtlValid = customTtlError === null;
+ const visibleTtlError = customTtl.length > 0 ? customTtlError : null;
+
+ const isDirty = Boolean(selectedBundle) || customTtl.length > 0;
+ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =
+ useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });
+
+ useEffect(() => {
+ if (isOpen) {
+ setSelectedBundle(null);
+ setTtlPreset(DEFAULT_TTL_PRESET);
+ setCustomTtl("");
+ }
+ }, [isOpen]);
+
+ const handleCreate = async () => {
+ if (!selectedBundle) return;
+
+ try {
+ const session = await createSession.mutateAsync({
+ accessBundles: [selectedBundle.name],
+ ttl
+ });
+ createNotification({ text: "Session created", type: "success" });
+ onCreated(session);
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog
+ open={isOpen}
+ onOpenChange={(nextOpen) => {
+ if (nextOpen) {
+ onOpenChange(true);
+ return;
+ }
+ requestDiscard();
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Create Session</DialogTitle>
+ <DialogDescription>
+ An agent running with this session reaches the hosts in this access bundle and nothing
+ else.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4">
+ <Field>
+ <FieldLabel htmlFor="agent-vault-session-bundle">Access Bundle</FieldLabel>
+ <FieldContent>
+ <Combobox
+ id="agent-vault-session-bundle"
+ options={accessBundles ?? []}
+ value={selectedBundle}
+ getOptionValue={(bundle) => bundle.id}
+ getOptionLabel={(bundle) => bundle.name}
+ placeholder="Pick an access bundle"
+ searchPlaceholder="Search access bundles..."
+ emptyMessage="No access bundle matches."
+ modal
+ renderOption={(bundle) => (
+ <span className="flex min-w-0 items-center gap-2">
+ <PackageIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate">{bundle.name}</span>
+ </span>
+ )}
+ renderValue={(bundle) => (
+ <span className="flex min-w-0 items-center gap-2">
+ <PackageIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate">{bundle.name}</span>
+ </span>
+ )}
+ onValueChange={setSelectedBundle}
+ onClear={() => setSelectedBundle(null)}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Expires</FieldLabel>
+ <FieldContent>
+ <Select
+ value={ttlPreset}
+ onValueChange={(value) => {
+ shouldFocusCustomTtlRef.current = value === CUSTOM_TTL;
+ setTtlPreset(value);
+ }}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ position="popper"
+ onCloseAutoFocus={(e) => {
+ if (!shouldFocusCustomTtlRef.current) return;
+ shouldFocusCustomTtlRef.current = false;
+ e.preventDefault();
+ customTtlInputRef.current?.focus();
+ }}
+ >
+ {TTL_PRESETS.map((preset) => (
+ <SelectItem key={preset.value} value={preset.value}>
+ {preset.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {isCustomTtl && (
+ <>
+ <Input
+ ref={customTtlInputRef}
+ className="mt-2"
+ value={customTtl}
+ onChange={(e) => setCustomTtl(e.target.value)}
+ placeholder="90m"
+ isError={visibleTtlError !== null}
+ />
+ <FieldDescription>A duration such as 30m, 8h, or 7d.</FieldDescription>
+ <FieldError>{visibleTtlError}</FieldError>
+ </>
+ )}
+ {ttlPreset === NEVER_TTL && (
+ <FieldDescription>
+ This session keeps working until someone revokes it.
+ </FieldDescription>
+ )}
+ </FieldContent>
+ </Field>
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={requestDiscard}>
+ Cancel
+ </Button>
+ <Button
+ variant="av"
+ isDisabled={!selectedBundle || !isTtlValid}
+ isPending={createSession.isPending}
+ onClick={async () => handleCreate()}
+ >
+ Create Session
+ </Button>
+ </DialogFooter>
+
+ <DiscardChangesAlertDialog
+ open={isDiscardDialogOpen}
+ onOpenChange={setIsDiscardDialogOpen}
+ onDiscard={confirmDiscard}
+ title="Discard Changes?"
+ description="The access bundle and expiry you picked will be lost."
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx
new file mode 100644
index 0000000000..9c5de2062f
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx
@@ -0,0 +1,38 @@
+import { createNotification } from "@app/components/notifications";
+import { DeleteConfirmDialog } from "@app/components/v3";
+import { useRevokeAgentVaultSession } from "@app/hooks/api/agentVault";
+import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";
+
+type Props = {
+ session: TAgentVaultSession | null;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const RevokeSessionDialog = ({ session, onOpenChange }: Props) => {
+ const revokeSession = useRevokeAgentVaultSession();
+
+ const handleRevoke = async () => {
+ if (!session) return;
+
+ try {
+ await revokeSession.mutateAsync(session.id);
+ createNotification({ text: `Session for "${session.actorName}" revoked`, type: "success" });
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <DeleteConfirmDialog
+ isOpen={Boolean(session)}
+ onOpenChange={onOpenChange}
+ title={`Revoke Session for "${session?.actorName}"`}
+ description="Proxies stop attaching credentials for this session at their next poll. This cannot be undone."
+ confirmKey="revoke"
+ confirmLabel="Revoke Session"
+ isPending={revokeSession.isPending}
+ onConfirm={handleRevoke}
+ />
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx
new file mode 100644
index 0000000000..56859747fc
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx
@@ -0,0 +1,85 @@
+import { TriangleAlertIcon } from "lucide-react";
+
+import {
+ Alert,
+ AlertDescription,
+ Button,
+ CodeBlock,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from "@app/components/v3";
+import { TAgentVaultMintedSession } from "@app/hooks/api/agentVault/types";
+
+import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";
+import { SessionExpiry } from "./SessionExpiry";
+
+type Props = {
+ session: TAgentVaultMintedSession | null;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+const runCommand = (token: string) =>
+ `infisical agent-vault run \\
+ --session-token ${token} \\
+ --proxy <proxy-host>:17323 \\
+ -- <agent-command>`;
+
+export const SessionCreatedDialog = ({ session, onOpenChange }: Props) => (
+ <Dialog open={Boolean(session)} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl" onInteractOutside={(event) => event.preventDefault()}>
+ <DialogHeader>
+ <DialogTitle>Session Created</DialogTitle>
+ <DialogDescription>
+ Run this where your agent runs. Its traffic reaches the proxy with the credentials this
+ session carries.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4">
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertDescription>
+ This command is shown once. Copy it now, the session token cannot be retrieved later.
+ </AlertDescription>
+ </Alert>
+
+ <div className="flex flex-col gap-2">
+ <CodeBlock label="Run an agent with it" value={runCommand(session?.token ?? "")} />
+ <p className="text-xs text-accent">
+ Replace <span className="font-mono">&lt;proxy-host&gt;</span> with the host your proxy
+ runs on and <span className="font-mono">&lt;agent-command&gt;</span> with the agent to
+ run, such as <span className="font-mono">claude</span>.
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <span className="text-xs text-accent">Expires</span>
+ <SessionExpiry expiresAt={session?.expiresAt ?? null} />
+ </div>
+
+ <p className="mt-2 text-xs text-accent">
+ Learn how to{" "}
+ <a
+ href={AgentVaultDocsUrls.sessions}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:opacity-80"
+ >
+ create a session using the CLI or a machine identity
+ </a>
+ .
+ </p>
+ </div>
+
+ <DialogFooter>
+ <Button variant="av" onClick={() => onOpenChange(false)}>
+ Done
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+);
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsx
new file mode 100644
index 0000000000..b075e63133
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsx
@@ -0,0 +1,35 @@
+import { format, formatDistanceToNowStrict } from "date-fns";
+
+import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+
+type Props = {
+ expiresAt: string | null;
+};
+
+export const SessionExpiry = ({ expiresAt }: Props) => {
+ if (!expiresAt) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">Never</span>
+ </TooltipTrigger>
+ <TooltipContent>This session works until it is revoked.</TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ const expiry = new Date(expiresAt);
+ const hasPassed = expiry.getTime() <= Date.now();
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">
+ {hasPassed ? "" : "in "}
+ {formatDistanceToNowStrict(expiry, { addSuffix: hasPassed })}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{format(expiry, "MMM d, yyyy h:mm a")}</TooltipContent>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsx
new file mode 100644
index 0000000000..cedff31319
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsx
@@ -0,0 +1,21 @@
+import { BanIcon, CircleCheckIcon, CircleSlashIcon } from "lucide-react";
+
+import { Badge } from "@app/components/v3";
+import { AgentVaultSessionStatus } from "@app/hooks/api/agentVault";
+
+const STATUS_PRESENTATION = {
+ [AgentVaultSessionStatus.Active]: { label: "Active", variant: "success", icon: CircleCheckIcon },
+ [AgentVaultSessionStatus.Revoked]: { label: "Revoked", variant: "danger", icon: BanIcon },
+ [AgentVaultSessionStatus.Expired]: { label: "Expired", variant: "neutral", icon: CircleSlashIcon }
+} as const;
+
+export const SessionStatusBadge = ({ status }: { status: AgentVaultSessionStatus }) => {
+ const { label, variant, icon: Icon } = STATUS_PRESENTATION[status];
+
+ return (
+ <Badge variant={variant}>
+ <Icon />
+ {label}
+ </Badge>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsx
new file mode 100644
index 0000000000..d9b9c64ac0
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AgentVaultSessionsPage } from "./AgentVaultSessionsPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions"
+)({
+ component: AgentVaultSessionsPage,
+ beforeLoad: ({ context }) => {
+ return { breadcrumbs: [...context.breadcrumbs, { label: "Sessions" }] };
+ }
+});
diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
new file mode 100644
index 0000000000..b6f685faaa
--- /dev/null
+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
@@ -0,0 +1,9 @@
+const AGENT_VAULT_DOCS_BASE_URL = "https://infisical.com/docs/documentation/platform/agent-vault";
+
+export const AgentVaultDocsUrls = {
+ overview: `${AGENT_VAULT_DOCS_BASE_URL}/overview`,
+ quickstart: `${AGENT_VAULT_DOCS_BASE_URL}/quickstart`,
+ accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,
+ sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,
+ proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`
+} as const;
diff --git a/frontend/src/pages/agent-vault/layout.tsx b/frontend/src/pages/agent-vault/layout.tsx
new file mode 100644
index 0000000000..158fe5fd37
--- /dev/null
+++ b/frontend/src/pages/agent-vault/layout.tsx
@@ -0,0 +1,98 @@
+import { createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";
+import { unpackRules } from "@casl/ability/extra";
+import { createFileRoute, redirect } from "@tanstack/react-router";
+import axios from "axios";
+
+import { BreadcrumbTypes } from "@app/components/v2";
+import {
+ OrgPermissionAdminConsoleAction,
+ OrgPermissionSet,
+ OrgPermissionSubjects
+} from "@app/context/OrgPermissionContext/types";
+import { projectKeys } from "@app/hooks/api";
+import { fetchAgentVaultProjectId } from "@app/hooks/api/agentVault/queries";
+import { grantOrgAdminProjectAccess } from "@app/hooks/api/orgAdmin";
+import { organizationKeys } from "@app/hooks/api/organization/queries";
+import { Organization } from "@app/hooks/api/organization/types";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { conditionsMatcher } from "@app/hooks/api/roles/permission-matcher";
+import {
+ fetchUserOrgPermissions,
+ fetchUserProjectPermissions,
+ roleQueryKeys
+} from "@app/hooks/api/roles/queries";
+import { AgentVaultLayout } from "@app/layouts/AgentVaultLayout";
+import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+)({
+ component: AgentVaultLayout,
+ beforeLoad: async ({ params, context }) => {
+ const org = context.queryClient.getQueryData<Organization>(
+ organizationKeys.getOrgById(params.orgId)
+ );
+
+ let agentVaultProjectId = org?.agentVaultProjectId;
+ if (!agentVaultProjectId) {
+ // Patch the returned id into the cached org so the Project contexts pick it up, without a refetch
+ // that could race read-replica lag.
+ const resolvedAgentVaultProjectId = await fetchAgentVaultProjectId();
+ agentVaultProjectId = resolvedAgentVaultProjectId;
+ context.queryClient.setQueryData<Organization>(
+ organizationKeys.getOrgById(params.orgId),
+ (old) => (old ? { ...old, agentVaultProjectId: resolvedAgentVaultProjectId } : old)
+ );
+ }
+
+ if (!agentVaultProjectId) {
+ throw redirect({ to: "/organizations/$orgId/projects", params: { orgId: params.orgId } });
+ }
+
+ // The project is bootstrapped with no members, so an org admin arriving by link (not the product tile,
+ // which joins them itself) is not a member yet. Join them here rather than showing the error page.
+ const loadPermissions = () =>
+ context.queryClient.ensureQueryData({
+ queryKey: roleQueryKeys.getUserProjectPermissions({ projectId: agentVaultProjectId }),
+ queryFn: () => fetchUserProjectPermissions({ projectId: agentVaultProjectId }),
+ retry: false
+ });
+ const isNotAMember = (err: unknown) =>
+ axios.isAxiosError(err) && err.response?.data?.error === "ProjectMembershipNotFound";
+ const isOrgAdmin = async () => {
+ const orgPermissions = await context.queryClient.ensureQueryData({
+ queryKey: roleQueryKeys.getUserOrgPermissions({ orgId: params.orgId }),
+ queryFn: () => fetchUserOrgPermissions({ orgId: params.orgId })
+ });
+ const ability = createMongoAbility<OrgPermissionSet>(
+ unpackRules<RawRuleOf<MongoAbility<OrgPermissionSet>>>(orgPermissions.permissions),
+ { conditionsMatcher }
+ );
+ return ability.can(
+ OrgPermissionAdminConsoleAction.AccessAllProjects,
+ OrgPermissionSubjects.AdminConsole
+ );
+ };
+
+ try {
+ await loadPermissions();
+ } catch (err) {
+ if (!isNotAMember(err) || !(await isOrgAdmin())) throw err;
+ await grantOrgAdminProjectAccess({ projectId: agentVaultProjectId });
+ await context.queryClient.invalidateQueries({ queryKey: projectKeys.allProjectQueries() });
+ await loadPermissions();
+ }
+
+ await context.queryClient.ensureQueryData({
+ queryKey: projectKeys.getProjectById(agentVaultProjectId),
+ queryFn: () => fetchProjectById(agentVaultProjectId)
+ });
+
+ return {
+ implicitProjectId: agentVaultProjectId,
+ implicitProductType: ProjectType.AgentVault,
+ breadcrumbs: [{ type: BreadcrumbTypes.Component, component: ProjectSelect }]
+ };
+ }
+});
diff --git a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
index c88f6be3a8..c11e2707af 100644
--- a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
+++ b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
@@ -208,6 +208,7 @@ export const SignUpPage = ({ invite }: SignUpPageProps) => {
project ? [project.id] : []
)}
grantPamAccess={selectedProducts.includes(ProjectType.PAM)}
+ grantAgentVaultAccess={selectedProducts.includes(ProjectType.AgentVault)}
onComplete={handleInviteComplete}
/>
);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx
index 019e3a5cd5..4cc205667f 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx
@@ -43,6 +43,7 @@ import type { TCertificatePemSummary } from "@app/helpers/certificatePem";
import type { TPkcs12Entry } from "@app/helpers/pkcs12";
import { useImportCertificate, useImportPkcs12Entries } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { useWizardSteps } from "@app/hooks/useWizardSteps";
import {
CertificateProfileSelect,
@@ -52,7 +53,7 @@ import {
useCertificateImportReference
} from "./certificate-import-fields";
import { getCertificateImportReference } from "./certificate-import-linkage";
-import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
+import { CertificateWizardSheet, WizardStep } from "./CertificateWizardSheet";
import { CertificateImportFormData, certificateImportSchema } from "./types";
const MAX_KEYSTORE_BYTES = 1024 * 1024;
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index 4deaa9209e..ff29479d94 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -38,6 +38,7 @@ import { CertificateRequestStatus, CertKeyUsage } from "@app/hooks/api/certifica
import { useUnifiedCertificateIssuance } from "@app/hooks/api/certificates/mutations";
import { useListPkiApplicationProfiles } from "@app/hooks/api/pkiApplications";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { useWizardSteps } from "@app/hooks/useWizardSteps";
import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";
import {
CertSubjectAlternativeNameType,
@@ -53,7 +54,7 @@ import {
isExternalTemplateCa,
rowErrorsOf
} from "./certificateUtils";
-import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
+import { CertificateWizardSheet, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
index 79d17f2942..c644d4234e 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
@@ -33,6 +33,7 @@ import {
} from "@app/hooks/api/certificates/enums";
import { useGetCertificateById } from "@app/hooks/api/certificates/queries";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { useWizardSteps } from "@app/hooks/useWizardSteps";
import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";
import {
CertSubjectAlternativeNameType,
@@ -48,7 +49,7 @@ import {
unionUsageOptions
} from "./certificateRenewalUtils";
import { isExternalTemplateCa, rowErrorsOf } from "./certificateUtils";
-import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
+import { CertificateWizardSheet, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
index e7b74d154e..5b77ed807b 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
@@ -1,6 +1,5 @@
-import { ReactNode, useCallback, useMemo, useState } from "react";
+import { ReactNode, useMemo } from "react";
-import { createNotification } from "@app/components/notifications";
import {
Button,
DocumentationLinkBadge,
@@ -46,53 +45,6 @@ type Props = {
isContinuePending?: boolean;
};
-export const useWizardSteps = <TStepKey extends string>({
- stepKeys,
- stepFields,
- invalidMessage,
- validateStep
-}: {
- stepKeys: readonly TStepKey[];
- stepFields: Record<TStepKey, string[]>;
- invalidMessage: string;
- /** Gates Continue on the current step's fields, so errors surface where they can be fixed. */
- validateStep?: (fields: string[]) => Promise<boolean>;
-}) => {
- const [step, setStep] = useState(0);
- const activeStep = Math.min(step, stepKeys.length - 1);
-
- const goBack = useCallback(() => setStep(Math.max(0, activeStep - 1)), [activeStep]);
- const goNext = useCallback(async () => {
- if (validateStep && !(await validateStep(stepFields[stepKeys[activeStep]]))) {
- createNotification({ text: "Fix the errors on this step to continue.", type: "error" });
- return;
- }
- setStep(Math.min(stepKeys.length - 1, activeStep + 1));
- }, [stepKeys, stepFields, activeStep, validateStep]);
-
- const onFormInvalid = useCallback(
- (errors: Record<string, unknown>) => {
- const errorKeys = Object.keys(errors);
- const idx = stepKeys.findIndex((key) =>
- stepFields[key].some((name) => errorKeys.includes(name))
- );
- if (idx >= 0) setStep(idx);
- createNotification({ text: invalidMessage, type: "error" });
- },
- [stepKeys, stepFields, invalidMessage]
- );
-
- return {
- step: activeStep,
- setStep,
- currentStepKey: stepKeys[activeStep],
- isLastStep: activeStep === stepKeys.length - 1,
- goBack,
- goNext,
- onFormInvalid
- };
-};
-
export const CertificateWizardSheet = ({
isOpen,
onOpenChange,
diff --git a/frontend/src/pages/middlewares/inject-org-details.tsx b/frontend/src/pages/middlewares/inject-org-details.tsx
index d7c6f160d3..2f727bf336 100644
--- a/frontend/src/pages/middlewares/inject-org-details.tsx
+++ b/frontend/src/pages/middlewares/inject-org-details.tsx
@@ -7,6 +7,7 @@ import { authKeys, fetchAuthToken, selectOrganization } from "@app/hooks/api/aut
import { certManagerInstanceKeys } from "@app/hooks/api/certManagerInstance";
import { identitiesKeys } from "@app/hooks/api/identities/queries";
import { fetchOrganizationById, organizationKeys } from "@app/hooks/api/organization/queries";
+import { pamKeys } from "@app/hooks/api/pam";
import { projectKeys } from "@app/hooks/api/projects";
import { fetchUserOrgPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
import { subOrganizationsQuery } from "@app/hooks/api/subOrganizations";
@@ -51,6 +52,8 @@ export const Route = createFileRoute("/_authenticate/_inject-org-details")({
context.queryClient.removeQueries({ queryKey: identitiesKeys.searchIdentitiesRoot });
context.queryClient.removeQueries({ queryKey: identitiesKeys.countIdentitiesRoot });
context.queryClient.removeQueries({ queryKey: appConnectionKeys.all });
+ // PAM's keys carry no org, so a stale entry would render another org's data until it goes stale.
+ context.queryClient.removeQueries({ queryKey: pamKeys.all });
await context.queryClient.fetchQuery({
queryKey: authKeys.getAuthToken,
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModal.tsx
index 6fa90deb8b..3912cebae0 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModal.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModal.tsx
@@ -1,5 +1,4 @@
import { useState } from "react";
-import { useParams } from "@tanstack/react-router";
import {
Button,
@@ -9,7 +8,7 @@ import {
SheetHeader,
SheetTitle
} from "@app/components/v3";
-import { useOrganization } from "@app/context";
+import { useScopeVariant } from "@app/hooks";
import { IdentityAuthMethod } from "@app/hooks/api/identities";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -29,11 +28,7 @@ export const IdentityAuthMethodModal = ({ popUp, handlePopUpOpen, handlePopUpTog
const [selectedAuthMethod, setSelectedAuthMethod] = useState<IdentityAuthMethod | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
- const { projectId } = useParams({ strict: false });
- const { isSubOrganization } = useOrganization();
-
- // eslint-disable-next-line no-nested-ternary
- const primaryVariant = projectId ? "project" : isSubOrganization ? "sub-org" : "org";
+ const primaryVariant = useScopeVariant();
const initialAuthMethod = popUp?.identityAuthMethod?.data?.authMethod;
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectAssignmentFields.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectAssignmentFields.tsx
index 6dce931088..82c748c14f 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectAssignmentFields.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectAssignmentFields.tsx
@@ -23,6 +23,7 @@ import { useGetUserProjects } from "@app/hooks/api";
import { ProjectType, ProjectVersion } from "@app/hooks/api/projects/types";
import {
+ AGENT_VAULT_ROLES,
CERT_MANAGER_ROLES,
DEFAULT_PROJECT_ROLE,
getSingleSelectedProjectId,
@@ -61,6 +62,12 @@ const PRODUCT_DEFINITIONS: ProductDefinition[] = [
name: getProjectTitle(ProjectType.PAM),
isSingleton: true,
roles: PAM_ROLES
+ },
+ {
+ type: ProjectType.AgentVault,
+ name: getProjectTitle(ProjectType.AgentVault),
+ isSingleton: true,
+ roles: AGENT_VAULT_ROLES
}
];
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx
index aa0ff699b5..5c8d81ed58 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx
@@ -1,4 +1,5 @@
import { Combobox } from "@app/components/v3";
+import { AGENT_VAULT_PRODUCT_ROLE_OPTIONS } from "@app/helpers/roles";
import { useGetProjectRoles } from "@app/hooks/api";
import { ProjectType } from "@app/hooks/api/projects/types";
@@ -41,6 +42,10 @@ export const CERT_MANAGER_ROLES = [
}
];
+export const AGENT_VAULT_ROLES = AGENT_VAULT_PRODUCT_ROLE_OPTIONS.map(
+ ({ value, label, description }) => ({ slug: value, name: label, description })
+);
+
export const PAM_ROLES = [
{
slug: "admin",
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamProductsField.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamProductsField.tsx
index d49fa5a14a..560a7119b3 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamProductsField.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamProductsField.tsx
@@ -33,6 +33,7 @@ export const AUDIT_LOG_STREAM_PRODUCT_LABELS: Record<AuditLogStreamProduct, stri
[AuditLogStreamProduct.KMS]: "KMS",
[AuditLogStreamProduct.SecretScanning]: "Secret Scanning",
[AuditLogStreamProduct.PAM]: "PAM",
+ [AuditLogStreamProduct.AgentVault]: "Agent Vault",
[AuditLogStreamProduct.Organization]: "Organization"
};
@@ -44,6 +45,7 @@ export const PRODUCT_ICONS: Record<AuditLogStreamProduct, LucideIcon> = {
[AuditLogStreamProduct.KMS]: getProjectLucideIcon(ProjectType.KMS),
[AuditLogStreamProduct.SecretScanning]: getProjectLucideIcon(ProjectType.SecretScanning),
[AuditLogStreamProduct.PAM]: getProjectLucideIcon(ProjectType.PAM),
+ [AuditLogStreamProduct.AgentVault]: getProjectLucideIcon(ProjectType.AgentVault),
[AuditLogStreamProduct.Organization]: Building2Icon
};
@@ -53,7 +55,8 @@ const PRODUCTS = [
AuditLogStreamProduct.CertificateManager,
AuditLogStreamProduct.KMS,
AuditLogStreamProduct.SecretScanning,
- AuditLogStreamProduct.PAM
+ AuditLogStreamProduct.PAM,
+ AuditLogStreamProduct.AgentVault
];
// Sentinel for the pinned "All products" entry — the default (no filter = stream everything).
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx
index 29a197126c..df37fd2a92 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx
@@ -68,12 +68,14 @@ const GENERIC_FILTER_KEYS = ["event", "actor", "actor_id", "source"];
// Per-product filter keys. Products not listed fall back to the full set (secrets default)
const PRODUCT_FILTER_KEYS: Partial<Record<ProjectType, string[]>> = {
- [ProjectType.PAM]: GENERIC_FILTER_KEYS
+ [ProjectType.PAM]: GENERIC_FILTER_KEYS,
+ [ProjectType.AgentVault]: GENERIC_FILTER_KEYS
};
// Per-product example hints for the free-text event filter (products not listed use the default)
const PRODUCT_EVENT_HINTS: Partial<Record<ProjectType, string>> = {
- [ProjectType.PAM]: "pam-account-access, pam-session-start, ..."
+ [ProjectType.PAM]: "pam-account-access, pam-session-start, ...",
+ [ProjectType.AgentVault]: "agent-vault-session-mint, agent-vault-proxy-enroll, ..."
};
const getProductFilterProperties = (projectType?: ProjectType) => {
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx
index 76357bbdab..3a1f0cd1c8 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx
@@ -19,6 +19,7 @@ import {
Input
} from "@app/components/v3";
import { useOrganization } from "@app/context";
+import { isOrgScopedProduct } from "@app/helpers/project";
import { useScopeVariant } from "@app/hooks";
import { useGetUserProjects } from "@app/hooks/api";
import {
@@ -29,7 +30,7 @@ import {
} from "@app/hooks/api/auditLogs/constants";
import { EventType } from "@app/hooks/api/auditLogs/enums";
import { UserAgentType } from "@app/hooks/api/auth/types";
-import { Project, ProjectType } from "@app/hooks/api/projects/types";
+import { Project } from "@app/hooks/api/projects/types";
import { LogFilterItem } from "./LogFilterItem";
import { auditLogFilterFormSchema, Presets, TAuditLogFilterFormData } from "./types";
@@ -100,7 +101,7 @@ export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => {
secretEvents.includes(eventType)
);
const showSecretsSection =
- selectedProject?.type !== ProjectType.PAM &&
+ !(selectedProject?.type && isOrgScopedProduct(selectedProject.type)) &&
(hasSecretEventFilter || currentSelectedEventTypes.length === 0);
const filteredEventTypes = useMemo(() => {
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx
index 2429dd6050..8eb3603016 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx
@@ -17,6 +17,7 @@ import {
DateRangeQuickPresets,
DocumentationLinkBadge
} from "@app/components/v3";
+import { DateRangeFilterAccent } from "@app/components/v3/platform/DateRangeFilter/DateRangeFilter";
import {
OrgPermissionAuditLogsActions,
OrgPermissionSubjects,
@@ -26,6 +27,7 @@ import {
} from "@app/context";
import { Timezone } from "@app/helpers/datetime";
import { isInfisicalCloud } from "@app/helpers/platform";
+import { isOrgScopedProduct } from "@app/helpers/project";
import { withPermission, withProjectPermission } from "@app/hoc";
import { useGetAuditLogPostgresStorageStatus } from "@app/hooks/api/auditLogs";
import { Project, ProjectType } from "@app/hooks/api/projects/types";
@@ -99,7 +101,9 @@ const LogsSectionComponent = ({
});
const timezone = dateRange.isUtc ? Timezone.UTC : Timezone.Local;
- const dateRangeAccent = project ? "primary" : "secondary";
+ // An org-scoped product has its own colour, and "primary" would paint its chrome the secrets yellow.
+ let dateRangeAccent: DateRangeFilterAccent = project ? "primary" : "secondary";
+ if (project?.type === ProjectType.AgentVault) dateRangeAccent = "av";
useEffect(() => {
if (subscription && !subscription.auditLogs) {
@@ -146,7 +150,7 @@ const LogsSectionComponent = ({
<CardDescription>
Search and review a detailed history of events
{!project && " across your organization"}
- {project && project.type !== ProjectType.PAM && " in this project"}.
+ {project && !isOrgScopedProduct(project.type) && " in this project"}.
</CardDescription>
{showFilters && (
<CardAction>
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx
index ecfca05b7f..6a9dddd1e3 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx
@@ -86,6 +86,9 @@ export const LogsTableRow = ({ auditLog, rowNumber, timezone, onClick }: Props)
{auditLog.actor.type === ActorType.EST_ACCOUNT && (
<Tag label="est_profile_id" value={auditLog.actor.metadata.profileId} />
)}
+ {auditLog.actor.type === ActorType.AGENT_VAULT_PROXY && (
+ <Tag label="proxy_id" value={auditLog.actor.metadata.agentVaultProxyId} />
+ )}
</div>
</TableCell>
<TableCell variant="action">
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
index cc4bb08dc3..6f80cd6302 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
@@ -12,6 +12,7 @@ import {
SelectValue,
TabsContent
} from "@app/components/v3";
+import { useTimeRemaining } from "@app/hooks";
import { useGetRelays } from "@app/hooks/api/relays/queries";
type Props = {
@@ -27,18 +28,6 @@ const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };
const PLACEHOLDER_ADDRESS = "<gateway-address>:8443";
-const formatTimeRemaining = (expiresAt: string, now: number) => {
- const remainingSeconds = Math.max(0, Math.ceil((new Date(expiresAt).getTime() - now) / 1000));
- if (remainingSeconds === 0) return "Expired";
-
- const hours = Math.floor(remainingSeconds / 3600);
- const minutes = Math.floor((remainingSeconds % 3600) / 60);
- const seconds = remainingSeconds % 60;
-
- if (hours > 0) return `${hours}h ${minutes}m remaining`;
- return `${minutes}m ${seconds}s remaining`;
-};
-
// Renders a freshly minted token as inline deployment instructions.
export const EnrollmentTokenContent = ({
gatewayName,
@@ -55,12 +44,7 @@ export const EnrollmentTokenContent = ({
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
const [relay, setRelay] = useState<{ id: string; name: string }>(AUTO_RELAY_OPTION);
const [commandRelay, setCommandRelay] = useState<{ id: string; name: string }>(AUTO_RELAY_OPTION);
- const [now, setNow] = useState(Date.now());
-
- useEffect(() => {
- const timer = window.setInterval(() => setNow(Date.now()), 1000);
- return () => window.clearInterval(timer);
- }, []);
+ const { label: expiryLabel, isExpired } = useTimeRemaining(expiresAt);
useEffect(() => {
setCommandRelay(relay);
@@ -75,8 +59,6 @@ export const EnrollmentTokenContent = ({
}, [isCommandDirty, onCommandDirtyChange]);
const resolvedRelayName = isDirect || commandRelay.id === "_auto" ? "" : commandRelay.name;
- const expiryLabel = formatTimeRemaining(expiresAt, now);
- const isExpired = expiryLabel === "Expired";
const cliCommand = useMemo(() => {
const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
index 0c327b2f91..40ef4868a1 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
@@ -178,6 +178,7 @@ export const GatewayPageHeader = ({ gateway, orgId }: { gateway: TGatewayV2; org
</AlertDialog>
<AlertDialog
open={popUp.revokeGateway.isOpen}
+ confirmationValue={gateway.name}
onOpenChange={(open) => handlePopUpToggle("revokeGateway", open)}
>
<AlertDialogContent>
@@ -188,6 +189,7 @@ export const GatewayPageHeader = ({ gateway, orgId }: { gateway: TGatewayV2; org
re-authenticate to reconnect.
</AlertDialogDescription>
</AlertDialogHeader>
+ <AlertDialogConfirmationField inputProps={{ placeholder: gateway.name }} />
<AlertDialogFooter>
<AlertDialogCancel isDisabled={isRevoking}>Cancel</AlertDialogCancel>
<AlertDialogAction
diff --git a/frontend/src/pages/organization/NetworkingPage/RelayDetailsByIDPage/components/RelayPageHeader/RelayPageHeader.tsx b/frontend/src/pages/organization/NetworkingPage/RelayDetailsByIDPage/components/RelayPageHeader/RelayPageHeader.tsx
index fdda7c4a2f..550714282b 100644
--- a/frontend/src/pages/organization/NetworkingPage/RelayDetailsByIDPage/components/RelayPageHeader/RelayPageHeader.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/RelayDetailsByIDPage/components/RelayPageHeader/RelayPageHeader.tsx
@@ -164,6 +164,7 @@ export const RelayPageHeader = ({
</AlertDialog>
<AlertDialog
open={popUp.revokeRelay.isOpen}
+ confirmationValue={relay.name}
onOpenChange={(open) => handlePopUpToggle("revokeRelay", open)}
>
<AlertDialogContent>
@@ -174,6 +175,7 @@ export const RelayPageHeader = ({
to reconnect.
</AlertDialogDescription>
</AlertDialogHeader>
+ <AlertDialogConfirmationField inputProps={{ placeholder: relay.name }} />
<AlertDialogFooter>
<AlertDialogCancel isDisabled={isRevoking}>Cancel</AlertDialogCancel>
<AlertDialogAction
diff --git a/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx b/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx
index 3409ff4bae..64dee37f51 100644
--- a/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx
@@ -133,6 +133,17 @@ export const ProjectTypePage = () => {
}
}, [projectType, orgId, navigate]);
+ // An org-scoped product has one implicit project, so listing it here would offer a project view we
+ // hide everywhere else, plus a create button the backend refuses.
+ useEffect(() => {
+ if (projectType === ProjectType.AgentVault) {
+ navigate({
+ to: "/organizations/$orgId/agent-vault/sessions",
+ params: { orgId }
+ });
+ }
+ }, [projectType, orgId, navigate]);
+
if (projectType === ProjectType.CertificateManager) {
return (
<CertManagerNotConfiguredModal
@@ -150,7 +161,7 @@ export const ProjectTypePage = () => {
);
}
- if (projectType === ProjectType.PAM) {
+ if (projectType === ProjectType.PAM || projectType === ProjectType.AgentVault) {
return null;
}
diff --git a/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx b/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
index 5c64c9e283..b07db1dd8a 100644
--- a/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
@@ -32,6 +32,7 @@ import {
projectTypeToUrlSlug
} from "@app/helpers/project";
import { useGetOrgProductStats, useGetUserProjects } from "@app/hooks/api";
+import { fetchAgentVaultProjectId } from "@app/hooks/api/agentVault/queries";
import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
import { useOrgAdminAccessProject } from "@app/hooks/api/orgAdmin/mutation";
import { resolvePamProjectId } from "@app/hooks/api/pam/queries";
@@ -44,7 +45,8 @@ const PRODUCT_TYPES: ActiveProducts[] = [
ProjectType.CertificateManager,
ProjectType.KMS,
ProjectType.SecretScanning,
- ProjectType.PAM
+ ProjectType.PAM,
+ ProjectType.AgentVault
];
const PRODUCT_STYLES: Record<
@@ -90,6 +92,13 @@ const PRODUCT_STYLES: Record<
"border-product-pam/30 bg-gradient-to-br from-product-pam/20 to-product-pam/5 group-hover:border-product-pam/50 group-hover:from-product-pam/25 group-hover:to-product-pam/10",
cardClassName: "hover:bg-gradient-to-br hover:from-product-pam/[0.04] hover:to-transparent",
titleUnderlineClassName: "decoration-product-pam/60"
+ },
+ [ProjectType.AgentVault]: {
+ iconClassName: "h-4.5 w-4.5 text-product-av",
+ containerClassName:
+ "border-product-av/30 bg-gradient-to-br from-product-av/20 to-product-av/5 group-hover:border-product-av/50 group-hover:from-product-av/25 group-hover:to-product-av/10",
+ cardClassName: "hover:bg-gradient-to-br hover:from-product-av/[0.04] hover:to-transparent",
+ titleUnderlineClassName: "decoration-product-av/60"
}
};
@@ -102,6 +111,9 @@ type ProductStat = {
value: number;
};
+// Derived so the placeholder count cannot drift from the products again.
+const PRODUCT_TILE_COUNT = Object.keys(ProjectType).length;
+
export const ProjectCategoryOverview = () => {
const navigate = useNavigate();
const { currentOrg } = useOrganization();
@@ -123,6 +135,8 @@ export const ProjectCategoryOverview = () => {
);
const [isPamRequestAccessOpen, setIsPamRequestAccessOpen] = useState(false);
const [pendingPamProjectId, setPendingPamProjectId] = useState<string | null>(null);
+ const [isAgentVaultRequestAccessOpen, setIsAgentVaultRequestAccessOpen] = useState(false);
+ const [pendingAgentVaultProjectId, setPendingAgentVaultProjectId] = useState<string | null>(null);
const orgDefaultCertManagerProjectId = certManagerInstance?.activeProjectId ?? null;
const cmInstances = useMemo(
@@ -152,6 +166,20 @@ export const ProjectCategoryOverview = () => {
const isPamAccessBlocked =
Boolean(currentOrg?.pamProjectId) && !isOrgAdmin && !canRequestAccess && !isPamMember;
+ const isAgentVaultMember = useMemo(
+ () =>
+ Boolean(
+ currentOrg?.agentVaultProjectId &&
+ projects.some((project) => project.id === currentOrg.agentVaultProjectId)
+ ),
+ [currentOrg?.agentVaultProjectId, projects]
+ );
+ const isAgentVaultAccessBlocked =
+ Boolean(currentOrg?.agentVaultProjectId) &&
+ !isOrgAdmin &&
+ !canRequestAccess &&
+ !isAgentVaultMember;
+
const certManagerActiveProjectId = useMemo(() => {
const cookieValue = currentOrg?.id ? getCertManagerActiveProjectCookie(currentOrg.id) : null;
if (cookieValue && cmInstances.some((p) => p.id === cookieValue)) return cookieValue;
@@ -200,6 +228,12 @@ export const ProjectCategoryOverview = () => {
{ label: "account templates", value: productStats.pam.accountTemplatesCount },
{ label: "folders", value: productStats.pam.foldersCount }
];
+ case ProjectType.AgentVault:
+ return [
+ { label: "access bundles", value: productStats.agentVault.accessBundlesCount },
+ { label: "services", value: productStats.agentVault.servicesCount },
+ { label: "proxies", value: productStats.agentVault.proxiesCount }
+ ];
default:
return [];
}
@@ -300,6 +334,57 @@ export const ProjectCategoryOverview = () => {
}
};
+ const navigateToAgentVault = () => {
+ navigate({
+ to: "/organizations/$orgId/agent-vault/sessions",
+ params: { orgId: currentOrg?.id ?? "" }
+ });
+ };
+
+ const enterAgentVaultProject = async () => {
+ let agentVaultProjectId: string;
+ try {
+ agentVaultProjectId = currentOrg?.agentVaultProjectId ?? (await fetchAgentVaultProjectId());
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to resolve the Agent Vault project."
+ });
+ return;
+ }
+
+ const isMember = projects.some((p) => p.id === agentVaultProjectId);
+ if (isMember) {
+ navigateToAgentVault();
+ return;
+ }
+
+ setPendingAgentVaultProjectId(agentVaultProjectId);
+
+ if (isOrgAdmin) {
+ try {
+ await orgAdminAccessProject.mutateAsync({ projectId: agentVaultProjectId });
+ navigateToAgentVault();
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to join the Agent Vault project."
+ });
+ }
+ return;
+ }
+
+ if (canRequestAccess) {
+ setIsAgentVaultRequestAccessOpen(true);
+ return;
+ }
+
+ createNotification({
+ type: "error",
+ text: "You don't have access to Agent Vault. Ask an Agent Vault admin to add you."
+ });
+ };
+
const handleTileClick = async (type: ProjectType) => {
const orgId = currentOrg?.id || "";
@@ -322,6 +407,11 @@ export const ProjectCategoryOverview = () => {
return;
}
+ if (type === ProjectType.AgentVault) {
+ await enterAgentVaultProject();
+ return;
+ }
+
navigate({
to: "/organizations/$orgId/projects/$type",
params: { orgId, type: projectTypeToUrlSlug(type) }
@@ -331,7 +421,7 @@ export const ProjectCategoryOverview = () => {
if (isProjectsLoading) {
return (
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
- {Array.from({ length: 5 }).map((_, i) => (
+ {Array.from({ length: PRODUCT_TILE_COUNT }).map((_, i) => (
<Card key={`tile-loading-${i + 1}`}>
<CardHeader>
<div className="flex items-start gap-3">
@@ -369,6 +459,13 @@ export const ProjectCategoryOverview = () => {
} as Project)
: undefined;
+ const agentVaultRequestAccessProject: Project | undefined = pendingAgentVaultProjectId
+ ? ({
+ id: pendingAgentVaultProjectId,
+ name: "Agent Vault"
+ } as Project)
+ : undefined;
+
return (
<>
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
@@ -423,7 +520,8 @@ export const ProjectCategoryOverview = () => {
const isAccessBlocked =
(type === ProjectType.CertificateManager && isCertManagerAccessBlocked) ||
- (type === ProjectType.PAM && isPamAccessBlocked);
+ (type === ProjectType.PAM && isPamAccessBlocked) ||
+ (type === ProjectType.AgentVault && isAgentVaultAccessBlocked);
if (isAccessBlocked) {
return (
@@ -445,7 +543,11 @@ export const ProjectCategoryOverview = () => {
// Cert Manager and PAM resolve their destination asynchronously (instance picker,
// lazy project bootstrap, join-on-behalf), so they stay handler-driven.
- if (type === ProjectType.CertificateManager || type === ProjectType.PAM) {
+ if (
+ type === ProjectType.CertificateManager ||
+ type === ProjectType.PAM ||
+ type === ProjectType.AgentVault
+ ) {
return (
<Card
key={type}
@@ -492,6 +594,16 @@ export const ProjectCategoryOverview = () => {
subTitle="Requesting access to Privileged Access Manager. You may include an optional note for admins to review your request."
/>
+ <RequestProjectAccessModal
+ isOpen={isAgentVaultRequestAccessOpen}
+ onOpenChange={(isOpen) => {
+ setIsAgentVaultRequestAccessOpen(isOpen);
+ if (!isOpen) setPendingAgentVaultProjectId(null);
+ }}
+ project={agentVaultRequestAccessProject}
+ subTitle="Requesting access to Agent Vault. You may include an optional note for admins to review your request."
+ />
+
<CertManagerNotConfiguredModal
isOpen={isCertManagerSetupOpen}
onOpenChange={setIsCertManagerSetupOpen}
diff --git a/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx b/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx
index 2d70c4e682..4aa4470bb2 100644
--- a/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx
+++ b/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx
@@ -127,6 +127,7 @@ export const SignupOnboardingPage = () => {
project ? [project.id] : []
)}
grantPamAccess={selectedProducts.includes(ProjectType.PAM)}
+ grantAgentVaultAccess={selectedProducts.includes(ProjectType.AgentVault)}
onComplete={() => setSection(OnboardingSection.Complete)}
/>
);
diff --git a/frontend/src/pages/pam/layout.tsx b/frontend/src/pages/pam/layout.tsx
index e700caef4c..13b155fb5e 100644
--- a/frontend/src/pages/pam/layout.tsx
+++ b/frontend/src/pages/pam/layout.tsx
@@ -6,6 +6,7 @@ import { organizationKeys } from "@app/hooks/api/organization/queries";
import { Organization } from "@app/hooks/api/organization/types";
import { fetchPamProjectId } from "@app/hooks/api/pam/queries";
import { fetchProjectById } from "@app/hooks/api/projects/queries";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
import { PamLayout } from "@app/layouts/PamLayout";
import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
@@ -52,6 +53,8 @@ export const Route = createFileRoute(
]);
return {
+ implicitProjectId: pamProjectId,
+ implicitProductType: ProjectType.PAM,
breadcrumbs: [
{
type: BreadcrumbTypes.Component,
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx
index c017251ca1..5ca54067ff 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx
@@ -19,8 +19,9 @@ import {
TabsList,
TabsTrigger
} from "@app/components/v3";
+import { useOrganization } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
-import { PAM_PRODUCT_ROLE_OPTIONS } from "@app/helpers/roles";
+import { AGENT_VAULT_PRODUCT_ROLE_OPTIONS, PAM_PRODUCT_ROLE_OPTIONS } from "@app/helpers/roles";
import {
projectIdentityMembershipQuery,
useCreateIdentityProjectAdditionalPrivilege,
@@ -30,6 +31,7 @@ import {
useListProjectIdentityMemberships,
useUpdateProjectIdentityMembership
} from "@app/hooks/api";
+import { agentVaultKeys, useAddAgentVaultProductMember } from "@app/hooks/api/agentVault";
import { UNIVERSAL_AUTH_DEFAULTS, useAddIdentityUniversalAuth } from "@app/hooks/api/identities";
import { pamKeys, useAddPamProductIdentityMember } from "@app/hooks/api/pam";
import { ProjectType } from "@app/hooks/api/projects/types";
@@ -47,6 +49,11 @@ import {
TCreateProjectIdentityForm
} from "./schema";
+const SUBMIT_VARIANT_BY_PRODUCT: Partial<Record<ProjectType, "pam" | "av">> = {
+ [ProjectType.PAM]: "pam",
+ [ProjectType.AgentVault]: "av"
+};
+
const buildTemplatePermissions = (
projectType: ProjectType,
templateIds: string[]
@@ -89,24 +96,27 @@ export const CreateProjectIdentityForm = ({
const queryClient = useQueryClient();
const isCertManager = projectType === ProjectType.CertificateManager;
const isPam = projectType === ProjectType.PAM;
+ const isAgentVault = projectType === ProjectType.AgentVault;
+ const isProductScoped = isPam || isAgentVault;
+ const { currentOrg } = useOrganization();
const { data: projectRoles } = useGetProjectRoles(projectId, projectType);
- // PAM product membership is only ever Admin or Member, and PAM has no externally visible project, so
- // the generic role copy ("...over a project") is replaced with the product's own wording.
const roles = useMemo(() => {
- if (!isPam) return projectRoles;
+ if (!isProductScoped) return projectRoles;
+
+ const options = isPam ? PAM_PRODUCT_ROLE_OPTIONS : AGENT_VAULT_PRODUCT_ROLE_OPTIONS;
return (projectRoles ?? []).flatMap((role) => {
- const productRole = PAM_PRODUCT_ROLE_OPTIONS.find((option) => option.value === role.slug);
+ const productRole = options.find((option) => option.value === role.slug);
if (!productRole) return [];
return [{ ...role, name: productRole.label, description: productRole.description }];
});
- }, [projectRoles, isPam]);
+ }, [projectRoles, isProductScoped, isPam]);
const defaultRole =
- isCertManager || isPam
+ isCertManager || isProductScoped
? { slug: ProjectMembershipRole.Member, name: "Member" }
: { slug: ProjectMembershipRole.NoAccess, name: "No Access" };
@@ -152,6 +162,7 @@ export const CreateProjectIdentityForm = ({
const { mutateAsync: updateMembership } = useUpdateProjectIdentityMembership();
const { mutateAsync: createMembership } = useCreateProjectIdentityMembership();
const { mutateAsync: addPamProductIdentityMember } = useAddPamProductIdentityMember();
+ const { mutateAsync: addAgentVaultProductMember } = useAddAgentVaultProductMember();
const { mutateAsync: addUniversalAuth } = useAddIdentityUniversalAuth();
const { mutateAsync: createAdditionalPrivilege } = useCreateIdentityProjectAdditionalPrivilege();
@@ -162,17 +173,15 @@ export const CreateProjectIdentityForm = ({
let identityId: string;
if (data.mode === CreateProjectIdentityMode.Create) {
- // PAM's membership PATCH takes a single product role rather than the generic roles array, so
- // the role is set at creation time instead of through a follow-up membership update.
const created = await createProjectIdentity({
name: data.name!.trim(),
projectId,
hasDeleteProtection: true,
- ...(isPam && data.role?.slug ? { roles: [{ role: data.role.slug }] } : {})
+ ...(isProductScoped && data.role?.slug ? { roles: [{ role: data.role.slug }] } : {})
});
identityId = created.id;
- if (!isPam && data.role?.slug) {
+ if (!isProductScoped && data.role?.slug) {
await updateMembership({
roles: [{ role: data.role.slug }],
identityId,
@@ -191,7 +200,7 @@ export const CreateProjectIdentityForm = ({
} else {
identityId = data.identity!.id;
- // PAM keeps its own add-member endpoint, which enforces the product-admin check, the
+ // Each product keeps its own add-member endpoint, which enforces the product-admin check, the
// admin/member-only roles, and the rejection of identities scoped to another project.
if (isPam) {
await addPamProductIdentityMember({
@@ -199,6 +208,8 @@ export const CreateProjectIdentityForm = ({
identityId,
role: data.role.slug
});
+ } else if (isAgentVault) {
+ await addAgentVaultProductMember({ identityId, role: data.role.slug });
} else {
await createMembership({
projectId,
@@ -209,10 +220,12 @@ export const CreateProjectIdentityForm = ({
}
}
- // The PAM tab reads its own product-membership list, which the generic mutations don't know about.
if (isPam) {
queryClient.invalidateQueries({ queryKey: pamKeys.productIdentities() });
}
+ if (isAgentVault) {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.productMembers(currentOrg.id) });
+ }
const hasTemplateGrants = data.templateIds.length > 0;
let grantFailed = false;
@@ -386,7 +399,7 @@ export const CreateProjectIdentityForm = ({
<SheetFooter className="border-t">
<Button
type="submit"
- variant={isPam ? "pam" : "project"}
+ variant={SUBMIT_VARIANT_BY_PRODUCT[projectType] ?? "project"}
isPending={isSubmitting}
isDisabled={isSubmitting}
>
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentitySheet.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentitySheet.tsx
index 32c3e48b47..f154966eca 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentitySheet.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentitySheet.tsx
@@ -11,7 +11,8 @@ import { CreateProjectIdentityForm } from "./CreateProjectIdentityForm";
const PRODUCT_LABELS: Partial<Record<ProjectType, string>> = {
[ProjectType.CertificateManager]: "Certificate Manager",
- [ProjectType.PAM]: "PAM"
+ [ProjectType.PAM]: "PAM",
+ [ProjectType.AgentVault]: "Agent Vault"
};
type Props = {
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx
index 68f90685e2..94b32ae7a6 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx
@@ -19,6 +19,7 @@ import {
} from "@app/components/v3";
import { useProject } from "@app/context";
import { TProjectIdentity, useUpdateProjectIdentity } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
const schema = z.object({
name: z.string().min(1, "Required"),
@@ -41,6 +42,7 @@ type ContentProps = {
export const ProjectIdentityModal = ({ onClose, identity }: ContentProps) => {
const { currentProject } = useProject();
+ const accentVariant = currentProject.type === ProjectType.AgentVault ? "av" : "project";
const { mutateAsync: updateMutateAsync } = useUpdateProjectIdentity();
@@ -116,7 +118,7 @@ export const ProjectIdentityModal = ({ onClose, identity }: ContentProps) => {
<Field orientation="horizontal">
<Toggle
id="delete-protection-enabled"
- variant="project"
+ variant={accentVariant}
checked={value}
onCheckedChange={onChange}
/>
@@ -203,7 +205,12 @@ export const ProjectIdentityModal = ({ onClose, identity }: ContentProps) => {
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
- <Button type="submit" variant="project" isPending={isSubmitting} isDisabled={isSubmitting}>
+ <Button
+ type="submit"
+ variant={accentVariant}
+ isPending={isSubmitting}
+ isDisabled={isSubmitting}
+ >
Update
</Button>
</div>
diff --git a/frontend/src/pages/project/AccessControlPage/route-agent-vault.tsx b/frontend/src/pages/project/AccessControlPage/route-agent-vault.tsx
new file mode 100644
index 0000000000..0d34037082
--- /dev/null
+++ b/frontend/src/pages/project/AccessControlPage/route-agent-vault.tsx
@@ -0,0 +1,33 @@
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import {
+ AgentVaultAccessControlPage,
+ AgentVaultAccessControlTab
+} from "@app/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage";
+
+const AccessControlPageQuerySchema = z.object({
+ selectedTab: z.nativeEnum(AgentVaultAccessControlTab).catch(AgentVaultAccessControlTab.Users),
+ requesterEmail: z.string().catch("")
+});
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management"
+)({
+ component: AgentVaultAccessControlPage,
+ validateSearch: zodValidator(AccessControlPageQuerySchema),
+ search: {
+ middlewares: [stripSearchParams({ requesterEmail: "" })]
+ },
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Access Control"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/AuditLogsPage/route-agent-vault.tsx b/frontend/src/pages/project/AuditLogsPage/route-agent-vault.tsx
new file mode 100644
index 0000000000..8089d63993
--- /dev/null
+++ b/frontend/src/pages/project/AuditLogsPage/route-agent-vault.tsx
@@ -0,0 +1,19 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AgentVaultAuditLogsPage } from "@app/pages/agent-vault/AgentVaultAuditLogsPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs"
+)({
+ component: AgentVaultAuditLogsPage,
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Audit Logs"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx
index 121c675966..4d964649c8 100644
--- a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx
@@ -27,6 +27,8 @@ import {
TableHeader,
TableRow
} from "@app/components/v3";
+import { useProject } from "@app/context";
+import { supportsAssumePrivileges } from "@app/helpers/project";
import {
getUserTablePreference,
PreferenceKey,
@@ -52,6 +54,8 @@ type Props = {
export const GroupMembersTable = ({ groupMembership }: Props) => {
const navigate = useNavigate();
+ const { currentProject } = useProject();
+ const canAssumePrivileges = supportsAssumePrivileges(currentProject.type);
const {
search,
setSearch,
@@ -193,9 +197,11 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
/>
</TableHead>
<TableHead>Joined Group</TableHead>
- <TableHead className="w-5">
- <span className="sr-only">Actions</span>
- </TableHead>
+ {canAssumePrivileges && (
+ <TableHead className="w-5">
+ <span className="sr-only">Actions</span>
+ </TableHead>
+ )}
</TableRow>
</TableHeader>
<TableBody>
@@ -211,9 +217,11 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
<TableCell>
<Skeleton className="h-4 w-24" />
</TableCell>
- <TableCell>
- <Skeleton className="h-4 w-4" />
- </TableCell>
+ {canAssumePrivileges && (
+ <TableCell>
+ <Skeleton className="h-4 w-4" />
+ </TableCell>
+ )}
</TableRow>
))
: groupMemberships?.members?.map((userGroupMembership) => {
@@ -221,6 +229,7 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
<GroupMembershipUserRow
key={`user-group-membership-${userGroupMembership.id}`}
user={userGroupMembership}
+ canAssumePrivileges={canAssumePrivileges}
onAssumePrivileges={(userId) =>
handlePopUpOpen("assumePrivileges", {
actorId: userId,
@@ -232,6 +241,7 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
<GroupMembershipIdentityRow
key={`identity-group-membership-${userGroupMembership.id}`}
identity={userGroupMembership}
+ canAssumePrivileges={canAssumePrivileges}
onAssumePrivileges={(identityId) =>
handlePopUpOpen("assumePrivileges", {
actorId: identityId,
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipIdentityRow.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipIdentityRow.tsx
index bcbb16fd9e..4b6575ebcd 100644
--- a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipIdentityRow.tsx
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipIdentityRow.tsx
@@ -15,6 +15,7 @@ import { TGroupMemberMachineIdentity } from "@app/hooks/api/groups/types";
type Props = {
identity: TGroupMemberMachineIdentity;
+ canAssumePrivileges: boolean;
onAssumePrivileges: (identityId: string) => void;
};
@@ -24,6 +25,7 @@ export const GroupMembershipIdentityRow = ({
joinedGroupAt,
id
},
+ canAssumePrivileges,
onAssumePrivileges
}: Props) => {
return (
@@ -33,33 +35,38 @@ export const GroupMembershipIdentityRow = ({
</TableCell>
<TableCell isTruncatable>{name}</TableCell>
<TableCell>{new Date(joinedGroupAt).toLocaleDateString()}</TableCell>
- <TableCell>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- variant="ghost"
- size="xs"
- aria-label={`Actions for machine identity ${name}`}
- >
- <EllipsisIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <ProjectPermissionCan
- I={ProjectPermissionIdentityActions.AssumePrivileges}
- a={ProjectPermissionSub.Identity}
- >
- {(isAllowed) => {
- return (
- <DropdownMenuItem onClick={() => onAssumePrivileges(id)} isDisabled={!isAllowed}>
- Assume Privileges
- </DropdownMenuItem>
- );
- }}
- </ProjectPermissionCan>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
+ {canAssumePrivileges && (
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label={`Actions for machine identity ${name}`}
+ >
+ <EllipsisIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <ProjectPermissionCan
+ I={ProjectPermissionIdentityActions.AssumePrivileges}
+ a={ProjectPermissionSub.Identity}
+ >
+ {(isAllowed) => {
+ return (
+ <DropdownMenuItem
+ onClick={() => onAssumePrivileges(id)}
+ isDisabled={!isAllowed}
+ >
+ Assume Privileges
+ </DropdownMenuItem>
+ );
+ }}
+ </ProjectPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ )}
</TableRow>
);
};
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipUserRow.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipUserRow.tsx
index 6d9b0e6f80..db683abcf7 100644
--- a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipUserRow.tsx
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembershipUserRow.tsx
@@ -15,6 +15,7 @@ import { TGroupMemberUser } from "@app/hooks/api/groups/types";
type Props = {
user: TGroupMemberUser;
+ canAssumePrivileges: boolean;
onAssumePrivileges: (userId: string) => void;
};
@@ -24,6 +25,7 @@ export const GroupMembershipUserRow = ({
joinedGroupAt,
id
},
+ canAssumePrivileges,
onAssumePrivileges
}: Props) => {
return (
@@ -35,29 +37,34 @@ export const GroupMembershipUserRow = ({
{`${firstName ?? "-"} ${lastName ?? ""}`} <span className="text-muted">({email})</span>
</TableCell>
<TableCell>{new Date(joinedGroupAt).toLocaleDateString()}</TableCell>
- <TableCell>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton size="xs" variant="ghost" aria-label={`Actions for ${email}`}>
- <EllipsisIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <ProjectPermissionCan
- I={ProjectPermissionMemberActions.AssumePrivileges}
- a={ProjectPermissionSub.Member}
- >
- {(isAllowed) => {
- return (
- <DropdownMenuItem onClick={() => onAssumePrivileges(id)} isDisabled={!isAllowed}>
- Assume Privileges
- </DropdownMenuItem>
- );
- }}
- </ProjectPermissionCan>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
+ {canAssumePrivileges && (
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton size="xs" variant="ghost" aria-label={`Actions for ${email}`}>
+ <EllipsisIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <ProjectPermissionCan
+ I={ProjectPermissionMemberActions.AssumePrivileges}
+ a={ProjectPermissionSub.Member}
+ >
+ {(isAllowed) => {
+ return (
+ <DropdownMenuItem
+ onClick={() => onAssumePrivileges(id)}
+ isDisabled={!isAllowed}
+ >
+ Assume Privileges
+ </DropdownMenuItem>
+ );
+ }}
+ </ProjectPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ )}
</TableRow>
);
};
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/route-agent-vault.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/route-agent-vault.tsx
new file mode 100644
index 0000000000..d91c5254b9
--- /dev/null
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/route-agent-vault.tsx
@@ -0,0 +1,33 @@
+import { createFileRoute, linkOptions } from "@tanstack/react-router";
+
+import { ProjectAccessControlTabs } from "@app/types/project";
+
+import { GroupDetailsByIDPage } from "./GroupDetailsByIDPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId"
+)({
+ component: GroupDetailsByIDPage,
+ beforeLoad: ({ context, params }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Access Control",
+ link: linkOptions({
+ to: "/organizations/$orgId/agent-vault/access-management",
+ params: {
+ orgId: params.orgId
+ },
+ search: {
+ selectedTab: ProjectAccessControlTabs.Groups
+ }
+ })
+ },
+ {
+ label: "Group"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
index ea1fec7cfe..c4c52b4ca0 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
@@ -4,7 +4,16 @@ import { useTranslation } from "react-i18next";
import { subject } from "@casl/ability";
import { useQuery } from "@tanstack/react-query";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
-import { ChevronLeftIcon, EllipsisIcon, InfoIcon, ShieldIcon } from "lucide-react";
+import {
+ ChevronLeftIcon,
+ CopyIcon,
+ EllipsisIcon,
+ InfoIcon,
+ ShieldIcon,
+ TrashIcon,
+ UserRoundXIcon,
+ VenetianMaskIcon
+} from "lucide-react";
import { AssumePrivilegesDialog } from "@app/components/assume-privileges";
import { createNotification } from "@app/components/notifications";
@@ -45,12 +54,13 @@ import {
useProject,
useSubscription
} from "@app/context";
-import { getProjectBaseURL } from "@app/helpers/project";
+import { getProjectBaseURL, supportsAssumePrivileges } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
import {
useDeleteProjectIdentityMembership,
useGetProjectIdentityMembershipV2
} from "@app/hooks/api";
+import { useRemoveAgentVaultProductMember } from "@app/hooks/api/agentVault";
import { ActorType } from "@app/hooks/api/auditLogs/enums";
import { useRemovePamProductIdentityMember } from "@app/hooks/api/pam";
import { projectIdentityQuery, useDeleteProjectIdentity } from "@app/hooks/api/projectIdentity";
@@ -81,18 +91,23 @@ const Page = () => {
const { mutateAsync: removeIdentityMutateAsync } = useDeleteProjectIdentityMembership();
const { mutateAsync: removePamIdentityMutateAsync } = useRemovePamProductIdentityMember();
+ const { mutateAsync: removeAgentVaultIdentityMutateAsync } = useRemoveAgentVaultProductMember();
const isProjectIdentity = Boolean(identityMembershipDetails?.identity.projectId);
const isCertManager = currentProject?.type === ProjectType.CertificateManager;
const isPam = currentProject?.type === ProjectType.PAM;
+ const isAgentVault = currentProject?.type === ProjectType.AgentVault;
// Products where the underlying project is an internal detail the user never sees
- const isStandaloneProduct = isCertManager || isPam;
+ const isStandaloneProduct = isCertManager || isPam || isAgentVault;
+ const canAssumePrivileges = supportsAssumePrivileges(currentProject.type);
let removeMenuItemLabel = "Remove From Project";
if (isProjectIdentity) {
removeMenuItemLabel = "Delete Machine Identity";
} else if (isPam) {
removeMenuItemLabel = "Remove From PAM";
+ } else if (isAgentVault) {
+ removeMenuItemLabel = "Remove From Agent Vault";
}
let accessControlLabel = "project";
@@ -100,6 +115,8 @@ const Page = () => {
accessControlLabel = "certificate manager";
} else if (isPam) {
accessControlLabel = "PAM";
+ } else if (isAgentVault) {
+ accessControlLabel = "Agent Vault";
}
const pageDescription = `Configure and manage${
isProjectIdentity ? " machine identity and " : " "
@@ -134,6 +151,10 @@ const Page = () => {
identityId,
projectId
});
+ } else if (isAgentVault) {
+ // Same reason as PAM: the product route keeps the last-admin guard, emits the Agent Vault event
+ // and reaps the identity's bundle grants, none of which the generic route does.
+ await removeAgentVaultIdentityMutateAsync({ identityId });
} else {
await removeIdentityMutateAsync({
identityId,
@@ -141,7 +162,7 @@ const Page = () => {
});
}
createNotification({
- text: `Successfully removed machine identity from ${isPam ? "PAM" : "project"}`,
+ text: `Successfully removed machine identity from ${isStandaloneProduct ? accessControlLabel : "project"}`,
type: "success"
});
handlePopUpClose("removeIdentity");
@@ -251,34 +272,38 @@ const Page = () => {
});
}}
>
+ <CopyIcon />
Copy Machine Identity ID
</DropdownMenuItem>
- <ProjectPermissionCan
- I={ProjectPermissionIdentityActions.AssumePrivileges}
- a={subject(ProjectPermissionSub.Identity, {
- identityId: identityMembershipDetails?.identity.id
- })}
- >
- {(isAllowed) => (
- <Tooltip>
- <TooltipTrigger className="block w-full">
- <DropdownMenuItem
- isDisabled={!isAllowed}
- onClick={() => handlePopUpOpen("assumePrivileges")}
- >
- Assume Privileges
- {isAllowed && <InfoIcon className="text-muted" />}
- </DropdownMenuItem>
- </TooltipTrigger>
- {isAllowed && (
- <TooltipContent className="max-w-80" side="left">
- Assume the privileges of this machine identity, allowing you to
- replicate their access behavior.
- </TooltipContent>
- )}
- </Tooltip>
- )}
- </ProjectPermissionCan>
+ {canAssumePrivileges && (
+ <ProjectPermissionCan
+ I={ProjectPermissionIdentityActions.AssumePrivileges}
+ a={subject(ProjectPermissionSub.Identity, {
+ identityId: identityMembershipDetails?.identity.id
+ })}
+ >
+ {(isAllowed) => (
+ <Tooltip>
+ <TooltipTrigger className="block w-full">
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ onClick={() => handlePopUpOpen("assumePrivileges")}
+ >
+ <VenetianMaskIcon />
+ Assume Privileges
+ {isAllowed && <InfoIcon className="text-muted" />}
+ </DropdownMenuItem>
+ </TooltipTrigger>
+ {isAllowed && (
+ <TooltipContent className="max-w-80" side="left">
+ Assume the privileges of this machine identity, allowing you to
+ replicate their access behavior.
+ </TooltipContent>
+ )}
+ </Tooltip>
+ )}
+ </ProjectPermissionCan>
+ )}
<ProjectPermissionCan
I={ProjectPermissionActions.Delete}
a={subject(ProjectPermissionSub.Identity, {
@@ -295,6 +320,7 @@ const Page = () => {
: handlePopUpOpen("removeIdentity")
}
>
+ {isProjectIdentity ? <TrashIcon /> : <UserRoundXIcon />}
{removeMenuItemLabel}
</DropdownMenuItem>
)}
@@ -365,10 +391,12 @@ const Page = () => {
</CardContent>
</Card>
)}
- <IdentityRoleDetailsSection
- identityMembershipDetails={identityMembershipDetails}
- isMembershipDetailsLoading={isMembershipDetailsLoading}
- />
+ {!isAgentVault && (
+ <IdentityRoleDetailsSection
+ identityMembershipDetails={identityMembershipDetails}
+ isMembershipDetailsLoading={isMembershipDetailsLoading}
+ />
+ )}
{!isStandaloneProduct && currentProject.isLegacyAdditionalPrivilegesEnabled && (
<IdentityProjectAdditionalPrivilegeSection
identityMembershipDetails={identityMembershipDetails}
@@ -388,8 +416,12 @@ const Page = () => {
</div>
<IdentityActionConfirmationDialog
open={popUp.removeIdentity.isOpen}
- title={`Remove ${identityMembershipDetails.identity.name} from ${isPam ? "PAM" : "the project"}?`}
- description={`The machine identity will lose access to ${isPam ? "PAM" : "this project"} but remain available in its organization.`}
+ title={`Remove ${identityMembershipDetails.identity.name} from ${
+ isStandaloneProduct ? accessControlLabel : "the project"
+ }?`}
+ description={`The machine identity will lose access to ${
+ isStandaloneProduct ? accessControlLabel : "this project"
+ } but remain available in its organization.`}
descriptionAsAlert
confirmationText="remove"
actionLabel="Remove"
@@ -438,11 +470,17 @@ const Page = () => {
export const IdentityDetailsByIDPage = () => {
const { t } = useTranslation();
+ const { currentProject } = useProject();
+ const isAgentVault = currentProject?.type === ProjectType.AgentVault;
return (
<>
<Helmet>
- <title>{t("common.head-title", { title: t("settings.members.title") })}</title>
+ <title>
+ {t("common.head-title", {
+ title: isAgentVault ? "Machine Identity" : t("settings.members.title")
+ })}
+ </title>
<link rel="icon" href="/infisical.ico" />
</Helmet>
<ProjectPermissionCan
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityDetailsSection.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityDetailsSection.tsx
index 380a1c29a3..7ae2a6ec17 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityDetailsSection.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityDetailsSection.tsx
@@ -1,6 +1,6 @@
import { subject } from "@casl/ability";
import { format } from "date-fns";
-import { BanIcon, CheckIcon, ClipboardListIcon, PencilIcon } from "lucide-react";
+import { BanIcon, CheckIcon, ClipboardListIcon, PencilIcon, VaultIcon } from "lucide-react";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
@@ -52,12 +52,15 @@ export const ProjectIdentityDetailsSection = ({
const { currentProject } = useProject();
const isCertManager = currentProject?.type === ProjectType.CertificateManager;
const isPam = currentProject?.type === ProjectType.PAM;
+ const isAgentVault = currentProject?.type === ProjectType.AgentVault;
let productLabel = "Project";
if (isCertManager) {
productLabel = "Certificate Manager";
} else if (isPam) {
productLabel = "PAM";
+ } else if (isAgentVault) {
+ productLabel = "Agent Vault";
}
let joinedLabel = "Joined project";
@@ -65,6 +68,8 @@ export const ProjectIdentityDetailsSection = ({
joinedLabel = "Joined certificate manager";
} else if (isPam) {
joinedLabel = "Joined PAM";
+ } else if (isAgentVault) {
+ joinedLabel = "Joined Agent Vault";
}
// eslint-disable-next-line @typescript-eslint/naming-convention,@typescript-eslint/no-unused-vars
@@ -144,8 +149,8 @@ export const ProjectIdentityDetailsSection = ({
{isSubOrgIdentity ? "Sub-" : ""}Organization
</Badge>
) : (
- <Badge variant="project">
- <ProjectIcon />
+ <Badge variant={isAgentVault ? "av" : "project"}>
+ {isAgentVault ? <VaultIcon /> : <ProjectIcon />}
{productLabel}
</Badge>
)}
@@ -223,7 +228,7 @@ export const ProjectIdentityDetailsSection = ({
>
<DialogContent className="max-w-xl">
<DialogHeader>
- <DialogTitle>Edit Project Identity</DialogTitle>
+ <DialogTitle>Edit {isAgentVault ? "Machine" : "Project"} Identity</DialogTitle>
<DialogDescription>
Update the identity&apos;s name, delete protection, and metadata.
</DialogDescription>
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/route-agent-vault.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/route-agent-vault.tsx
new file mode 100644
index 0000000000..7c1b4641ef
--- /dev/null
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/route-agent-vault.tsx
@@ -0,0 +1,33 @@
+import { createFileRoute, linkOptions } from "@tanstack/react-router";
+
+import { ProjectAccessControlTabs } from "@app/types/project";
+
+import { IdentityDetailsByIDPage } from "./IdentityDetailsByIDPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId"
+)({
+ component: IdentityDetailsByIDPage,
+ beforeLoad: ({ context, params }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Access Control",
+ link: linkOptions({
+ to: "/organizations/$orgId/agent-vault/access-management",
+ params: {
+ orgId: params.orgId
+ },
+ search: {
+ selectedTab: ProjectAccessControlTabs.Identities
+ }
+ })
+ },
+ {
+ label: "Machine Identity"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
index a734a54a1d..7f3462cb90 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
@@ -45,7 +45,7 @@ import {
useSubscription,
useUser
} from "@app/context";
-import { getProjectBaseURL } from "@app/helpers/project";
+import { getProjectBaseURL, supportsAssumePrivileges } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
import { useDeleteUserFromWorkspace, useGetWorkspaceUserDetails } from "@app/hooks/api";
import { ActorType } from "@app/hooks/api/auditLogs/enums";
@@ -143,6 +143,7 @@ export const Page = () => {
const isOwnProjectMembershipDetails = currentUserId === membershipDetails?.user?.id;
const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const canAssumePrivileges = !isCertManager && supportsAssumePrivileges(currentProject.type);
let memberDisplayName = "Unnamed User";
if (membershipDetails) {
const { firstName, lastName, email, username } = membershipDetails.user;
@@ -219,7 +220,7 @@ export const Page = () => {
>
Copy User ID
</DropdownMenuItem>
- {!isCertManager && (
+ {canAssumePrivileges && (
<ProjectPermissionCan
I={ProjectPermissionMemberActions.AssumePrivileges}
a={ProjectPermissionSub.Member}
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/route-agent-vault.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/route-agent-vault.tsx
new file mode 100644
index 0000000000..726c260a5c
--- /dev/null
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/route-agent-vault.tsx
@@ -0,0 +1,33 @@
+import { createFileRoute, linkOptions } from "@tanstack/react-router";
+
+import { ProjectAccessControlTabs } from "@app/types/project";
+
+import { MemberDetailsByIDPage } from "./MemberDetailsByIDPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId"
+)({
+ component: MemberDetailsByIDPage,
+ beforeLoad: ({ context, params }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Access Control",
+ link: linkOptions({
+ to: "/organizations/$orgId/agent-vault/access-management",
+ params: {
+ orgId: params.orgId
+ },
+ search: {
+ selectedTab: ProjectAccessControlTabs.Member
+ }
+ })
+ },
+ {
+ label: "User"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index fc61d11e6a..68ba3954e3 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -13,6 +13,9 @@ import { z } from "zod";
import {
ProjectPermissionActions,
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionAgentVaultProxyActions,
+ ProjectPermissionAgentVaultSessionActions,
ProjectPermissionCertificateActions,
ProjectPermissionCertificateAuthorityActions,
ProjectPermissionCertificatePolicyActions,
@@ -284,6 +287,29 @@ const ApprovalRequestGrantPolicyActionSchema = z.object({
[ProjectPermissionApprovalRequestGrantActions.Revoke]: z.boolean().optional()
});
+const AgentVaultAccessBundlePolicyActionSchema = z.object({
+ [ProjectPermissionAgentVaultAccessBundleActions.Read]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultAccessBundleActions.Create]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultAccessBundleActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultAccessBundleActions.Delete]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultAccessBundleActions.ManageMembers]: z.boolean().optional()
+});
+
+const AgentVaultSessionPolicyActionSchema = z.object({
+ [ProjectPermissionAgentVaultSessionActions.Read]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultSessionActions.Create]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultSessionActions.Revoke]: z.boolean().optional()
+});
+
+const AgentVaultProxyPolicyActionSchema = z.object({
+ [ProjectPermissionAgentVaultProxyActions.Read]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultProxyActions.Create]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultProxyActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultProxyActions.Delete]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultProxyActions.IssueToken]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultProxyActions.Revoke]: z.boolean().optional()
+});
+
const ProjectFolderGrantPolicyActionSchema = z.object({
[ProjectPermissionProjectFolderGrantActions.ReadGrant]: z.boolean().optional(),
[ProjectPermissionProjectFolderGrantActions.CreateGrant]: z.boolean().optional(),
@@ -814,6 +840,13 @@ export const projectRoleFormSchema = z.object({
),
[ProjectPermissionSub.ApprovalRequestGrants]:
ApprovalRequestGrantPolicyActionSchema.array().default([]),
+ [ProjectPermissionSub.AgentVaultAccessBundles]:
+ AgentVaultAccessBundlePolicyActionSchema.array().default([]),
+ [ProjectPermissionSub.AgentVaultSessions]:
+ AgentVaultSessionPolicyActionSchema.array().default([]),
+ [ProjectPermissionSub.AgentVaultProxies]: AgentVaultProxyPolicyActionSchema.array().default(
+ []
+ ),
[ProjectPermissionSub.ProjectFolderGrant]: ProjectFolderGrantPolicyActionSchema.extend({
inverted: z.boolean().optional(),
conditions: ConditionSchema
@@ -2443,6 +2476,94 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
}
]
},
+ [ProjectPermissionSub.AgentVaultAccessBundles]: {
+ title: "Access Bundles",
+ description: "Manage what an agent can reach and who can reach it",
+ actions: [
+ {
+ label: "Read",
+ value: ProjectPermissionAgentVaultAccessBundleActions.Read,
+ description: "View access bundles and their connections"
+ },
+ {
+ label: "Create",
+ value: ProjectPermissionAgentVaultAccessBundleActions.Create,
+ description: "Create access bundles and add connections"
+ },
+ {
+ label: "Modify",
+ value: ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ description: "Update access bundles and their credentials"
+ },
+ {
+ label: "Remove",
+ value: ProjectPermissionAgentVaultAccessBundleActions.Delete,
+ description: "Delete access bundles"
+ },
+ {
+ label: "Manage Members",
+ value: ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ description: "Grant and revoke access to a bundle"
+ }
+ ]
+ },
+ [ProjectPermissionSub.AgentVaultSessions]: {
+ title: "Sessions",
+ description: "Mint and revoke the tokens agents run with",
+ actions: [
+ {
+ label: "Read",
+ value: ProjectPermissionAgentVaultSessionActions.Read,
+ description: "View sessions"
+ },
+ {
+ label: "Create",
+ value: ProjectPermissionAgentVaultSessionActions.Create,
+ description: "Mint a session over access bundles you can reach"
+ },
+ {
+ label: "Revoke",
+ value: ProjectPermissionAgentVaultSessionActions.Revoke,
+ description: "Revoke a session"
+ }
+ ]
+ },
+ [ProjectPermissionSub.AgentVaultProxies]: {
+ title: "Proxies",
+ description: "Manage the egress proxies that attach credentials",
+ actions: [
+ {
+ label: "Read",
+ value: ProjectPermissionAgentVaultProxyActions.Read,
+ description: "View proxies, their health and certificate authority fingerprints"
+ },
+ {
+ label: "Create",
+ value: ProjectPermissionAgentVaultProxyActions.Create,
+ description: "Register a proxy and issue its enrollment token"
+ },
+ {
+ label: "Modify",
+ value: ProjectPermissionAgentVaultProxyActions.Edit,
+ description: "Update proxy settings"
+ },
+ {
+ label: "Remove",
+ value: ProjectPermissionAgentVaultProxyActions.Delete,
+ description: "Delete proxies"
+ },
+ {
+ label: "Issue token",
+ value: ProjectPermissionAgentVaultProxyActions.IssueToken,
+ description: "Issue a replacement enrollment token for a proxy"
+ },
+ {
+ label: "Revoke",
+ value: ProjectPermissionAgentVaultProxyActions.Revoke,
+ description: "Revoke a proxy's access token"
+ }
+ ]
+ },
[ProjectPermissionSub.ProxiedServices]: {
title: "Proxied Services",
description: "Manage proxied services and route agent traffic through them",
@@ -3334,6 +3455,12 @@ const SecretScanningSubject = (enabled = false) => ({
[ProjectPermissionSub.SecretScanningConfigs]: enabled
});
+const AgentVaultPermissionSubjects = (enabled = false) => ({
+ [ProjectPermissionSub.AgentVaultAccessBundles]: enabled,
+ [ProjectPermissionSub.AgentVaultSessions]: enabled,
+ [ProjectPermissionSub.AgentVaultProxies]: enabled
+});
+
// scott: this structure ensures we don't forget to add project permissions to their relevant project type
export const ProjectTypePermissionSubjects: Record<
ProjectType,
@@ -3341,6 +3468,7 @@ export const ProjectTypePermissionSubjects: Record<
> = {
[ProjectType.SecretManager]: {
...SharedPermissionSubjects,
+ ...AgentVaultPermissionSubjects(),
...SecretsManagerPermissionSubjects(true),
...KmsPermissionSubjects(),
...CertificateManagerPermissionSubjects(),
@@ -3352,6 +3480,7 @@ export const ProjectTypePermissionSubjects: Record<
},
[ProjectType.KMS]: {
...SharedPermissionSubjects,
+ ...AgentVaultPermissionSubjects(),
...KmsPermissionSubjects(true),
...SecretsManagerPermissionSubjects(),
...CertificateManagerPermissionSubjects(),
@@ -3360,6 +3489,7 @@ export const ProjectTypePermissionSubjects: Record<
},
[ProjectType.CertificateManager]: {
...SharedPermissionSubjects,
+ ...AgentVaultPermissionSubjects(),
...CertificateManagerPermissionSubjects(true),
...KmsPermissionSubjects(),
...SecretsManagerPermissionSubjects(),
@@ -3368,6 +3498,7 @@ export const ProjectTypePermissionSubjects: Record<
},
[ProjectType.SecretScanning]: {
...SharedPermissionSubjects,
+ ...AgentVaultPermissionSubjects(),
...SecretScanningSubject(true),
...CertificateManagerPermissionSubjects(),
...KmsPermissionSubjects(),
@@ -3376,6 +3507,16 @@ export const ProjectTypePermissionSubjects: Record<
},
[ProjectType.PAM]: {
...SharedPermissionSubjects,
+ ...AgentVaultPermissionSubjects(),
+ ...SecretScanningSubject(),
+ ...CertificateManagerPermissionSubjects(),
+ ...KmsPermissionSubjects(),
+ ...SecretsManagerPermissionSubjects(),
+ [ProjectPermissionSub.AppConnections]: false
+ },
+ [ProjectType.AgentVault]: {
+ ...SharedPermissionSubjects,
+ ...AgentVaultPermissionSubjects(true),
...SecretScanningSubject(),
...CertificateManagerPermissionSubjects(),
...KmsPermissionSubjects(),
@@ -3813,5 +3954,6 @@ export const RoleTemplates: Record<ProjectType, RoleTemplate[]> = {
]
}
],
- [ProjectType.PAM]: [projectManagerTemplate()]
+ [ProjectType.PAM]: [projectManagerTemplate()],
+ [ProjectType.AgentVault]: [projectManagerTemplate()]
};
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/route-agent-vault.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/route-agent-vault.tsx
new file mode 100644
index 0000000000..276ab4cc72
--- /dev/null
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/route-agent-vault.tsx
@@ -0,0 +1,33 @@
+import { createFileRoute, linkOptions } from "@tanstack/react-router";
+
+import { AgentVaultAccessControlTab } from "@app/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage";
+
+import { RoleDetailsBySlugPage } from "./RoleDetailsBySlugPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug"
+)({
+ component: RoleDetailsBySlugPage,
+ beforeLoad: ({ context, params }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Access Control",
+ link: linkOptions({
+ to: "/organizations/$orgId/agent-vault/access-management",
+ params: {
+ orgId: params.orgId
+ },
+ search: {
+ selectedTab: AgentVaultAccessControlTab.Users
+ }
+ })
+ },
+ {
+ label: "Roles"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx b/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx
index 17fa890517..b5c920bf33 100644
--- a/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx
+++ b/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx
@@ -23,11 +23,15 @@ type ProjectAccessErrorProps = {
const getPamOrgIdFromPath = () =>
window.location.pathname.match(/\/organizations\/([^/]+)\/pam(\/|$)/)?.[1];
+const getAgentVaultOrgIdFromPath = () =>
+ window.location.pathname.match(/\/organizations\/([^/]+)\/agent-vault(\/|$)/)?.[1];
+
// Products users experience as a single app rather than something they pick a project for
// (ProjectSelect hides itself for both), so the copy names the product instead of "this project".
// Cert Manager still carries a $projectId in its route for legacy multi-instance orgs.
const PRODUCTS = [
{ pattern: /\/organizations\/[^/]+\/pam(\/|$)/, name: "Privileged Access Manager" },
+ { pattern: /\/organizations\/[^/]+\/agent-vault(\/|$)/, name: "Agent Vault" },
{
pattern: /\/organizations\/[^/]+\/projects\/cert-manager(\/|$)/,
name: "Certificate Manager"
@@ -55,11 +59,17 @@ export const ProjectAccessError = ({ projectId: projectIdProp }: ProjectAccessEr
const productName = getProductNameFromPath();
const needsPamFallback = !projectIdProp && !routeProjectId;
const pamOrgId = needsPamFallback ? getPamOrgIdFromPath() : undefined;
- const { data: pamOrg, isPending: isPamOrgPending } = useGetOrganizationById(pamOrgId ?? "", {
- enabled: Boolean(pamOrgId)
- });
+ const agentVaultOrgId = needsPamFallback && !pamOrgId ? getAgentVaultOrgIdFromPath() : undefined;
+ const orgScopedOrgId = pamOrgId ?? agentVaultOrgId;
+ const { data: pamOrg, isPending: isPamOrgPending } = useGetOrganizationById(
+ orgScopedOrgId ?? "",
+ {
+ enabled: Boolean(orgScopedOrgId)
+ }
+ );
- const projectId = projectIdProp ?? routeProjectId ?? pamOrg?.pamProjectId ?? undefined;
+ const orgScopedProjectId = agentVaultOrgId ? pamOrg?.agentVaultProjectId : pamOrg?.pamProjectId;
+ const projectId = projectIdProp ?? routeProjectId ?? orgScopedProjectId ?? undefined;
const { data, isPending: isProjectSearchPending } = useSearchProjects({
projectIds: projectId ? [projectId] : [],
@@ -71,7 +81,7 @@ export const ProjectAccessError = ({ projectId: projectIdProp }: ProjectAccessEr
const [project] = data?.projects ?? [];
// A disabled query reports isPending forever, so only an enabled query counts as in-flight
- const isResolvingProjectId = Boolean(pamOrgId) && isPamOrgPending;
+ const isResolvingProjectId = Boolean(orgScopedOrgId) && isPamOrgPending;
const isProjectResolving = isResolvingProjectId || (Boolean(projectId) && isProjectSearchPending);
// Nothing in flight and still no project: the search errored or returned nothing, or no id
// could be resolved. The request flow needs the resolved project (the modal renders nothing
diff --git a/frontend/src/pages/redirects/agent-vault-index-redirect.tsx b/frontend/src/pages/redirects/agent-vault-index-redirect.tsx
new file mode 100644
index 0000000000..a8171b5749
--- /dev/null
+++ b/frontend/src/pages/redirects/agent-vault-index-redirect.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute, redirect } from "@tanstack/react-router";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/"
+)({
+ beforeLoad: ({ params }) => {
+ throw redirect({
+ to: "/organizations/$orgId/agent-vault/sessions",
+ params: { orgId: params.orgId }
+ });
+ }
+});
diff --git a/frontend/src/pages/root.tsx b/frontend/src/pages/root.tsx
index e9c3b6c415..f48876860a 100644
--- a/frontend/src/pages/root.tsx
+++ b/frontend/src/pages/root.tsx
@@ -11,11 +11,16 @@ import { adminQueryKeys, fetchServerConfig } from "@app/hooks/api/admin/queries"
import { TServerConfig } from "@app/hooks/api/admin/types";
import { authKeys } from "@app/hooks/api/auth/queries";
import { fetchAuthToken, shouldRetryAuthTokenFetch } from "@app/hooks/api/auth/refresh";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { queryClient } from "@app/hooks/api/reactQuery";
type TRouterContext = {
serverConfig: TServerConfig | null;
queryClient: QueryClient;
+ // Published by the PAM and Agent Vault layouts, whose URLs carry no $projectId. Optional because
+ // only those two branches of the tree set them; see useImplicitProjectId and useImplicitProduct.
+ implicitProjectId?: string;
+ implicitProductType?: ProjectType;
};
const RootCommandMenuMount = () => {
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 9c35abf049..77cbc69fa4 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -68,6 +68,7 @@ import { Route as organizationAccessManagementPageRouteImport } from './pages/or
import { Route as redirectsGithubManifestCallbackRedirectImport } from './pages/redirects/github-manifest-callback-redirect'
import { Route as redirectsOauthCallbackRedirectImport } from './pages/redirects/oauth-callback-redirect'
import { Route as pamLayoutImport } from './pages/pam/layout'
+import { Route as agentVaultLayoutImport } from './pages/agent-vault/layout'
import { Route as secretManagerIntegrationsRouteVercelOauthRedirectImport } from './pages/secret-manager/integrations/route-vercel-oauth-redirect'
import { Route as secretManagerIntegrationsRouteNetlifyOauthRedirectImport } from './pages/secret-manager/integrations/route-netlify-oauth-redirect'
import { Route as secretManagerIntegrationsRouteHerokuOauthRedirectImport } from './pages/secret-manager/integrations/route-heroku-oauth-redirect'
@@ -88,6 +89,9 @@ import { Route as organizationAppConnectionsAppConnectionsPageRouteImport } from
import { Route as secretManagerRedirectsRedirectApprovalPageImport } from './pages/secret-manager/redirects/redirect-approval-page'
import { Route as projectAuditLogsPageRoutePamImport } from './pages/project/AuditLogsPage/route-pam'
import { Route as projectAccessControlPageRoutePamImport } from './pages/project/AccessControlPage/route-pam'
+import { Route as projectAuditLogsPageRouteAgentVaultImport } from './pages/project/AuditLogsPage/route-agent-vault'
+import { Route as projectAccessControlPageRouteAgentVaultImport } from './pages/project/AccessControlPage/route-agent-vault'
+import { Route as redirectsAgentVaultIndexRedirectImport } from './pages/redirects/agent-vault-index-redirect'
import { Route as organizationSettingsPageOauthCallbackPageRouteImport } from './pages/organization/SettingsPage/OauthCallbackPage/route'
import { Route as organizationSecretInsightsPageRouteImport } from './pages/organization/SecretInsightsPage/route'
import { Route as pamPamTemplatesPageRouteImport } from './pages/pam/PamTemplatesPage/route'
@@ -96,6 +100,8 @@ import { Route as pamPamDiscoveryPageRouteImport } from './pages/pam/PamDiscover
import { Route as pamPamApprovalRequestsPageRouteImport } from './pages/pam/PamApprovalRequestsPage/route'
import { Route as organizationNetworkingPageRelayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/RelayDetailsByIDPage/route'
import { Route as organizationNetworkingPageGatewayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/GatewayDetailsByIDPage/route'
+import { Route as agentVaultAgentVaultSessionsPageRouteImport } from './pages/agent-vault/AgentVaultSessionsPage/route'
+import { Route as agentVaultAgentVaultProxiesPageRouteImport } from './pages/agent-vault/AgentVaultProxiesPage/route'
import { Route as secretScanningLayoutImport } from './pages/secret-scanning/layout'
import { Route as secretManagerLayoutImport } from './pages/secret-manager/layout'
import { Route as kmsLayoutImport } from './pages/kms/layout'
@@ -104,16 +110,22 @@ import { Route as projectRoleDetailsBySlugPageRoutePamImport } from './pages/pro
import { Route as projectMemberDetailsByIDPageRoutePamImport } from './pages/project/MemberDetailsByIDPage/route-pam'
import { Route as projectIdentityDetailsByIDPageRoutePamImport } from './pages/project/IdentityDetailsByIDPage/route-pam'
import { Route as projectGroupDetailsByIDPageRoutePamImport } from './pages/project/GroupDetailsByIDPage/route-pam'
+import { Route as projectRoleDetailsBySlugPageRouteAgentVaultImport } from './pages/project/RoleDetailsBySlugPage/route-agent-vault'
+import { Route as projectMemberDetailsByIDPageRouteAgentVaultImport } from './pages/project/MemberDetailsByIDPage/route-agent-vault'
+import { Route as projectIdentityDetailsByIDPageRouteAgentVaultImport } from './pages/project/IdentityDetailsByIDPage/route-agent-vault'
+import { Route as projectGroupDetailsByIDPageRouteAgentVaultImport } from './pages/project/GroupDetailsByIDPage/route-agent-vault'
import { Route as redirectsPamOrgAccessRedirectImport } from './pages/redirects/pam-org-access-redirect'
import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'
import { Route as organizationKmipServersPageKmipServerDetailsByIDPageRouteImport } from './pages/organization/KmipServersPage/KmipServerDetailsByIDPage/route'
import { Route as pamPamAccountsPagePamFolderPageRouteImport } from './pages/pam/PamAccountsPage/PamFolderPage/route'
import { Route as organizationAppConnectionsGitHubManifestCallbackPageRouteImport } from './pages/organization/AppConnections/GitHubManifestCallbackPage/route'
import { Route as organizationAppConnectionsOauthCallbackPageRouteImport } from './pages/organization/AppConnections/OauthCallbackPage/route'
+import { Route as agentVaultAgentVaultAccessBundleDetailPageRouteImport } from './pages/agent-vault/AgentVaultAccessBundleDetailPage/route'
import { Route as organizationSecretSharingPageRouteImport } from './pages/organization/SecretSharingPage/route'
import { Route as organizationProductSettingsPageSecretsManagementRouteImport } from './pages/organization/ProductSettingsPage/SecretsManagement/route'
import { Route as organizationKmipServersPageRouteImport } from './pages/organization/KmipServersPage/route'
import { Route as pamPamAccountsPageRouteImport } from './pages/pam/PamAccountsPage/route'
+import { Route as agentVaultAgentVaultAccessBundlesPageRouteImport } from './pages/agent-vault/AgentVaultAccessBundlesPage/route'
import { Route as projectAuditLogsPageRouteSecretScanningImport } from './pages/project/AuditLogsPage/route-secret-scanning'
import { Route as projectAppConnectionsPageRouteSecretScanningImport } from './pages/project/AppConnectionsPage/route-secret-scanning'
import { Route as projectAccessControlPageRouteSecretScanningImport } from './pages/project/AccessControlPage/route-secret-scanning'
@@ -301,6 +313,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsImpor
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections',
)()
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultImport =
+ createFileRoute(
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault',
+ )()
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdSecretManagerProjectIdImport =
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId',
@@ -341,6 +357,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessI
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access',
)()
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesImport =
+ createFileRoute(
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles',
+ )()
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesImport =
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources',
@@ -754,6 +774,16 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRoute
} as any,
)
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRoute =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultImport.update(
+ {
+ id: '/agent-vault',
+ path: '/agent-vault',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdRoute,
+ } as any,
+ )
+
const adminResourceOverviewPageRouteRoute =
adminResourceOverviewPageRouteImport.update({
id: '/resources/overview',
@@ -846,6 +876,12 @@ const pamLayoutRoute = pamLayoutImport.update({
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamRoute,
} as any)
+const agentVaultLayoutRoute = agentVaultLayoutImport.update({
+ id: '/_agent-vault-layout',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRoute,
+} as any)
+
const secretManagerIntegrationsRouteVercelOauthRedirectRoute =
secretManagerIntegrationsRouteVercelOauthRedirectImport.update({
id: '/vercel/oauth2/callback',
@@ -1086,6 +1122,36 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessR
} as any,
)
+const projectAuditLogsPageRouteAgentVaultRoute =
+ projectAuditLogsPageRouteAgentVaultImport.update({
+ id: '/audit-logs',
+ path: '/audit-logs',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
+const projectAccessControlPageRouteAgentVaultRoute =
+ projectAccessControlPageRouteAgentVaultImport.update({
+ id: '/access-management',
+ path: '/access-management',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesImport.update(
+ {
+ id: '/access-bundles',
+ path: '/access-bundles',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any,
+ )
+
+const redirectsAgentVaultIndexRedirectRoute =
+ redirectsAgentVaultIndexRedirectImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
const organizationSettingsPageOauthCallbackPageRouteRoute =
organizationSettingsPageOauthCallbackPageRouteImport.update({
id: '/oauth/callback',
@@ -1142,6 +1208,20 @@ const organizationNetworkingPageGatewayDetailsByIDPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRoute,
} as any)
+const agentVaultAgentVaultSessionsPageRouteRoute =
+ agentVaultAgentVaultSessionsPageRouteImport.update({
+ id: '/sessions',
+ path: '/sessions',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
+const agentVaultAgentVaultProxiesPageRouteRoute =
+ agentVaultAgentVaultProxiesPageRouteImport.update({
+ id: '/proxies',
+ path: '/proxies',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
const secretScanningLayoutRoute = secretScanningLayoutImport.update({
id: '/_secret-scanning-layout',
getParentRoute: () =>
@@ -1194,6 +1274,34 @@ const projectGroupDetailsByIDPageRoutePamRoute =
getParentRoute: () => pamLayoutRoute,
} as any)
+const projectRoleDetailsBySlugPageRouteAgentVaultRoute =
+ projectRoleDetailsBySlugPageRouteAgentVaultImport.update({
+ id: '/roles/$roleSlug',
+ path: '/roles/$roleSlug',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
+const projectMemberDetailsByIDPageRouteAgentVaultRoute =
+ projectMemberDetailsByIDPageRouteAgentVaultImport.update({
+ id: '/members/$membershipId',
+ path: '/members/$membershipId',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
+const projectIdentityDetailsByIDPageRouteAgentVaultRoute =
+ projectIdentityDetailsByIDPageRouteAgentVaultImport.update({
+ id: '/identities/$identityId',
+ path: '/identities/$identityId',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
+const projectGroupDetailsByIDPageRouteAgentVaultRoute =
+ projectGroupDetailsByIDPageRouteAgentVaultImport.update({
+ id: '/groups/$groupId',
+ path: '/groups/$groupId',
+ getParentRoute: () => agentVaultLayoutRoute,
+ } as any)
+
const redirectsPamOrgAccessRedirectRoute =
redirectsPamOrgAccessRedirectImport.update({
id: '/',
@@ -1241,6 +1349,14 @@ const organizationAppConnectionsOauthCallbackPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRoute,
} as any)
+const agentVaultAgentVaultAccessBundleDetailPageRouteRoute =
+ agentVaultAgentVaultAccessBundleDetailPageRouteImport.update({
+ id: '/$accessBundleId',
+ path: '/$accessBundleId',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute,
+ } as any)
+
const organizationSecretSharingPageRouteRoute =
organizationSecretSharingPageRouteImport.update({
id: '/',
@@ -1272,6 +1388,14 @@ const pamPamAccountsPageRouteRoute = pamPamAccountsPageRouteImport.update({
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccountsRoute,
} as any)
+const agentVaultAgentVaultAccessBundlesPageRouteRoute =
+ agentVaultAgentVaultAccessBundlesPageRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute,
+ } as any)
+
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesImport.update(
{
@@ -2927,6 +3051,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof adminResourceOverviewPageRouteImport
parentRoute: typeof adminLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault'
+ path: '/agent-vault'
+ fullPath: '/organizations/$orgId/agent-vault'
+ preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections'
path: '/app-connections'
@@ -3088,6 +3219,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof secretManagerIntegrationsRouteVercelOauthRedirectImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutIntegrationsImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout'
+ path: ''
+ fullPath: '/organizations/$orgId/agent-vault'
+ preLoaderRoute: typeof agentVaultLayoutImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout'
path: ''
@@ -3116,6 +3254,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof redirectsGithubManifestCallbackRedirectImport
parentRoute: typeof middlewaresInjectOrgDetailsImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies'
+ path: '/proxies'
+ fullPath: '/organizations/$orgId/agent-vault/proxies'
+ preLoaderRoute: typeof agentVaultAgentVaultProxiesPageRouteImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions'
+ path: '/sessions'
+ fullPath: '/organizations/$orgId/agent-vault/sessions'
+ preLoaderRoute: typeof agentVaultAgentVaultSessionsPageRouteImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'
path: '/gateways/$gatewayId'
@@ -3172,6 +3324,34 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof organizationSettingsPageOauthCallbackPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdSettingsImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/'
+ path: '/'
+ fullPath: '/organizations/$orgId/agent-vault/'
+ preLoaderRoute: typeof redirectsAgentVaultIndexRedirectImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles'
+ path: '/access-bundles'
+ fullPath: '/organizations/$orgId/agent-vault/access-bundles'
+ preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management'
+ path: '/access-management'
+ fullPath: '/organizations/$orgId/agent-vault/access-management'
+ preLoaderRoute: typeof projectAccessControlPageRouteAgentVaultImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs'
+ path: '/audit-logs'
+ fullPath: '/organizations/$orgId/agent-vault/audit-logs'
+ preLoaderRoute: typeof projectAuditLogsPageRouteAgentVaultImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access'
path: '/access'
@@ -3256,6 +3436,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof secretManagerRedirectsRedirectApprovalPageImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdSecretManagerProjectIdImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/'
+ path: '/'
+ fullPath: '/organizations/$orgId/agent-vault/access-bundles/'
+ preLoaderRoute: typeof agentVaultAgentVaultAccessBundlesPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/'
path: '/'
@@ -3284,6 +3471,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof organizationSecretSharingPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementSecretSharingImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId'
+ path: '/$accessBundleId'
+ fullPath: '/organizations/$orgId/agent-vault/access-bundles/$accessBundleId'
+ preLoaderRoute: typeof agentVaultAgentVaultAccessBundleDetailPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback'
path: '/$appConnection/oauth/callback'
@@ -3326,6 +3520,34 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof redirectsPamOrgAccessRedirectImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId'
+ path: '/groups/$groupId'
+ fullPath: '/organizations/$orgId/agent-vault/groups/$groupId'
+ preLoaderRoute: typeof projectGroupDetailsByIDPageRouteAgentVaultImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId'
+ path: '/identities/$identityId'
+ fullPath: '/organizations/$orgId/agent-vault/identities/$identityId'
+ preLoaderRoute: typeof projectIdentityDetailsByIDPageRouteAgentVaultImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId'
+ path: '/members/$membershipId'
+ fullPath: '/organizations/$orgId/agent-vault/members/$membershipId'
+ preLoaderRoute: typeof projectMemberDetailsByIDPageRouteAgentVaultImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug'
+ path: '/roles/$roleSlug'
+ fullPath: '/organizations/$orgId/agent-vault/roles/$roleSlug'
+ preLoaderRoute: typeof projectRoleDetailsBySlugPageRouteAgentVaultImport
+ parentRoute: typeof agentVaultLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId'
path: '/groups/$groupId'
@@ -5342,6 +5564,76 @@ const organizationProjectsPageRouteRouteWithChildren =
organizationProjectsPageRouteRouteChildren,
)
+interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteChildren {
+ agentVaultAgentVaultAccessBundlesPageRouteRoute: typeof agentVaultAgentVaultAccessBundlesPageRouteRoute
+ agentVaultAgentVaultAccessBundleDetailPageRouteRoute: typeof agentVaultAgentVaultAccessBundleDetailPageRouteRoute
+}
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteChildren =
+ {
+ agentVaultAgentVaultAccessBundlesPageRouteRoute:
+ agentVaultAgentVaultAccessBundlesPageRouteRoute,
+ agentVaultAgentVaultAccessBundleDetailPageRouteRoute:
+ agentVaultAgentVaultAccessBundleDetailPageRouteRoute,
+ }
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute._addFileChildren(
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteChildren,
+ )
+
+interface agentVaultLayoutRouteChildren {
+ agentVaultAgentVaultProxiesPageRouteRoute: typeof agentVaultAgentVaultProxiesPageRouteRoute
+ agentVaultAgentVaultSessionsPageRouteRoute: typeof agentVaultAgentVaultSessionsPageRouteRoute
+ redirectsAgentVaultIndexRedirectRoute: typeof redirectsAgentVaultIndexRedirectRoute
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren
+ projectAccessControlPageRouteAgentVaultRoute: typeof projectAccessControlPageRouteAgentVaultRoute
+ projectAuditLogsPageRouteAgentVaultRoute: typeof projectAuditLogsPageRouteAgentVaultRoute
+ projectGroupDetailsByIDPageRouteAgentVaultRoute: typeof projectGroupDetailsByIDPageRouteAgentVaultRoute
+ projectIdentityDetailsByIDPageRouteAgentVaultRoute: typeof projectIdentityDetailsByIDPageRouteAgentVaultRoute
+ projectMemberDetailsByIDPageRouteAgentVaultRoute: typeof projectMemberDetailsByIDPageRouteAgentVaultRoute
+ projectRoleDetailsBySlugPageRouteAgentVaultRoute: typeof projectRoleDetailsBySlugPageRouteAgentVaultRoute
+}
+
+const agentVaultLayoutRouteChildren: agentVaultLayoutRouteChildren = {
+ agentVaultAgentVaultProxiesPageRouteRoute:
+ agentVaultAgentVaultProxiesPageRouteRoute,
+ agentVaultAgentVaultSessionsPageRouteRoute:
+ agentVaultAgentVaultSessionsPageRouteRoute,
+ redirectsAgentVaultIndexRedirectRoute: redirectsAgentVaultIndexRedirectRoute,
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute:
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren,
+ projectAccessControlPageRouteAgentVaultRoute:
+ projectAccessControlPageRouteAgentVaultRoute,
+ projectAuditLogsPageRouteAgentVaultRoute:
+ projectAuditLogsPageRouteAgentVaultRoute,
+ projectGroupDetailsByIDPageRouteAgentVaultRoute:
+ projectGroupDetailsByIDPageRouteAgentVaultRoute,
+ projectIdentityDetailsByIDPageRouteAgentVaultRoute:
+ projectIdentityDetailsByIDPageRouteAgentVaultRoute,
+ projectMemberDetailsByIDPageRouteAgentVaultRoute:
+ projectMemberDetailsByIDPageRouteAgentVaultRoute,
+ projectRoleDetailsBySlugPageRouteAgentVaultRoute:
+ projectRoleDetailsBySlugPageRouteAgentVaultRoute,
+}
+
+const agentVaultLayoutRouteWithChildren =
+ agentVaultLayoutRoute._addFileChildren(agentVaultLayoutRouteChildren)
+
+interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteChildren {
+ agentVaultLayoutRoute: typeof agentVaultLayoutRouteWithChildren
+}
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteChildren =
+ {
+ agentVaultLayoutRoute: agentVaultLayoutRouteWithChildren,
+ }
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteWithChildren =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRoute._addFileChildren(
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteChildren,
+ )
+
interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRouteChildren {
organizationAppConnectionsAppConnectionsPageRouteRoute: typeof organizationAppConnectionsAppConnectionsPageRouteRoute
organizationAppConnectionsOauthCallbackPageRouteRoute: typeof organizationAppConnectionsOauthCallbackPageRouteRoute
@@ -5508,6 +5800,7 @@ interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdRouteChildren {
organizationOauthApplicationsPageRouteRoute: typeof organizationOauthApplicationsPageRouteRoute
organizationProjectsPageRouteRoute: typeof organizationProjectsPageRouteRouteWithChildren
organizationSsoPageRouteRoute: typeof organizationSsoPageRouteRoute
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamRouteWithChildren
@@ -5533,6 +5826,8 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdRouteChildren: Auth
organizationProjectsPageRouteRoute:
organizationProjectsPageRouteRouteWithChildren,
organizationSsoPageRouteRoute: organizationSsoPageRouteRoute,
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRoute:
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRoute:
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRoute:
@@ -5827,6 +6122,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects': typeof organizationProjectsPageRouteRouteWithChildren
'/organizations/$orgId/sso': typeof organizationSsoPageRouteRoute
'/admin/resources/overview': typeof adminResourceOverviewPageRouteRoute
+ '/organizations/$orgId/agent-vault': typeof agentVaultLayoutRouteWithChildren
'/organizations/$orgId/app-connections': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRouteWithChildren
'/organizations/$orgId/networking': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRouteWithChildren
'/organizations/$orgId/pam': typeof pamLayoutRouteWithChildren
@@ -5853,6 +6149,8 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdSecretManagerProjectIdRouteWithChildren
'/organization/app-connections/$appConnection/oauth/callback': typeof redirectsOauthCallbackRedirectRoute
'/organization/app-connections/github/manifest/callback': typeof redirectsGithubManifestCallbackRedirectRoute
+ '/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute
+ '/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute
'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute
'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute
'/organizations/$orgId/pam/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute
@@ -5861,6 +6159,10 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/pam/templates': typeof pamPamTemplatesPageRouteRoute
'/organizations/$orgId/projects/secret-management/insights': typeof organizationSecretInsightsPageRouteRoute
'/organizations/$orgId/settings/oauth/callback': typeof organizationSettingsPageOauthCallbackPageRouteRoute
+ '/organizations/$orgId/agent-vault/': typeof redirectsAgentVaultIndexRedirectRoute
+ '/organizations/$orgId/agent-vault/access-bundles': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren
+ '/organizations/$orgId/agent-vault/access-management': typeof projectAccessControlPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/audit-logs': typeof projectAuditLogsPageRouteAgentVaultRoute
'/organizations/$orgId/pam/access': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildren
'/organizations/$orgId/pam/access-management': typeof projectAccessControlPageRoutePamRoute
'/organizations/$orgId/pam/accounts': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccountsRouteWithChildren
@@ -5873,16 +6175,22 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/secret-management/secret-sharing': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementSecretSharingRouteWithChildren
'/organizations/$orgId/projects/secret-scanning/$projectId': typeof secretScanningLayoutRouteWithChildren
'/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute
+ '/organizations/$orgId/agent-vault/access-bundles/': typeof agentVaultAgentVaultAccessBundlesPageRouteRoute
'/organizations/$orgId/pam/accounts/': typeof pamPamAccountsPageRouteRoute
'/organizations/$orgId/projects/kms/kmip-servers/': typeof organizationKmipServersPageRouteRoute
'/organizations/$orgId/projects/secret-management/product-settings/': typeof organizationProductSettingsPageSecretsManagementRouteRoute
'/organizations/$orgId/projects/secret-management/secret-sharing/': typeof organizationSecretSharingPageRouteRoute
+ '/organizations/$orgId/agent-vault/access-bundles/$accessBundleId': typeof agentVaultAgentVaultAccessBundleDetailPageRouteRoute
'/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute
'/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute
'/organizations/$orgId/pam/accounts/$folderId': typeof pamPamAccountsPagePamFolderPageRouteRoute
'/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': typeof organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute
'/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute
'/organizations/$orgId/pam/access/': typeof redirectsPamOrgAccessRedirectRoute
+ '/organizations/$orgId/agent-vault/groups/$groupId': typeof projectGroupDetailsByIDPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/identities/$identityId': typeof projectIdentityDetailsByIDPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/members/$membershipId': typeof projectMemberDetailsByIDPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/roles/$roleSlug': typeof projectRoleDetailsBySlugPageRouteAgentVaultRoute
'/organizations/$orgId/pam/groups/$groupId': typeof projectGroupDetailsByIDPageRoutePamRoute
'/organizations/$orgId/pam/identities/$identityId': typeof projectIdentityDetailsByIDPageRoutePamRoute
'/organizations/$orgId/pam/members/$membershipId': typeof projectMemberDetailsByIDPageRoutePamRoute
@@ -6098,6 +6406,7 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects': typeof organizationProjectsPageRouteRouteWithChildren
'/organizations/$orgId/sso': typeof organizationSsoPageRouteRoute
'/admin/resources/overview': typeof adminResourceOverviewPageRouteRoute
+ '/organizations/$orgId/agent-vault': typeof redirectsAgentVaultIndexRedirectRoute
'/organizations/$orgId/pam': typeof pamLayoutRouteWithChildren
'/organizations/$orgId/secret-sharing': typeof organizationSecretSharingPageSecretSharingRedirectRouteRoute
'/organization/settings/oauth/callback': typeof redirectsSettingsOauthCallbackRedirectRoute
@@ -6121,6 +6430,8 @@ export interface FileRoutesByTo {
'/organizations/$orgId/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdSecretManagerProjectIdRouteWithChildren
'/organization/app-connections/$appConnection/oauth/callback': typeof redirectsOauthCallbackRedirectRoute
'/organization/app-connections/github/manifest/callback': typeof redirectsGithubManifestCallbackRedirectRoute
+ '/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute
+ '/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute
'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute
'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute
'/organizations/$orgId/pam/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute
@@ -6129,6 +6440,8 @@ export interface FileRoutesByTo {
'/organizations/$orgId/pam/templates': typeof pamPamTemplatesPageRouteRoute
'/organizations/$orgId/projects/secret-management/insights': typeof organizationSecretInsightsPageRouteRoute
'/organizations/$orgId/settings/oauth/callback': typeof organizationSettingsPageOauthCallbackPageRouteRoute
+ '/organizations/$orgId/agent-vault/access-management': typeof projectAccessControlPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/audit-logs': typeof projectAuditLogsPageRouteAgentVaultRoute
'/organizations/$orgId/pam/access-management': typeof projectAccessControlPageRoutePamRoute
'/organizations/$orgId/pam/audit-logs': typeof projectAuditLogsPageRoutePamRoute
'/organizations/$orgId/projects/cert-manager/$projectId': typeof certManagerDashboardPageRouteIndexRoute
@@ -6136,16 +6449,22 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/secret-management/$projectId': typeof secretManagerLayoutRouteWithChildren
'/organizations/$orgId/projects/secret-scanning/$projectId': typeof secretScanningLayoutRouteWithChildren
'/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute
+ '/organizations/$orgId/agent-vault/access-bundles': typeof agentVaultAgentVaultAccessBundlesPageRouteRoute
'/organizations/$orgId/pam/accounts': typeof pamPamAccountsPageRouteRoute
'/organizations/$orgId/projects/kms/kmip-servers': typeof organizationKmipServersPageRouteRoute
'/organizations/$orgId/projects/secret-management/product-settings': typeof organizationProductSettingsPageSecretsManagementRouteRoute
'/organizations/$orgId/projects/secret-management/secret-sharing': typeof organizationSecretSharingPageRouteRoute
+ '/organizations/$orgId/agent-vault/access-bundles/$accessBundleId': typeof agentVaultAgentVaultAccessBundleDetailPageRouteRoute
'/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute
'/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute
'/organizations/$orgId/pam/accounts/$folderId': typeof pamPamAccountsPagePamFolderPageRouteRoute
'/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': typeof organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute
'/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute
'/organizations/$orgId/pam/access': typeof redirectsPamOrgAccessRedirectRoute
+ '/organizations/$orgId/agent-vault/groups/$groupId': typeof projectGroupDetailsByIDPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/identities/$identityId': typeof projectIdentityDetailsByIDPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/members/$membershipId': typeof projectMemberDetailsByIDPageRouteAgentVaultRoute
+ '/organizations/$orgId/agent-vault/roles/$roleSlug': typeof projectRoleDetailsBySlugPageRouteAgentVaultRoute
'/organizations/$orgId/pam/groups/$groupId': typeof projectGroupDetailsByIDPageRoutePamRoute
'/organizations/$orgId/pam/identities/$identityId': typeof projectIdentityDetailsByIDPageRoutePamRoute
'/organizations/$orgId/pam/members/$membershipId': typeof projectMemberDetailsByIDPageRoutePamRoute
@@ -6358,6 +6677,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects': typeof organizationProjectsPageRouteRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/sso': typeof organizationSsoPageRouteRoute
'/_authenticate/_inject-org-details/admin/_admin-layout/resources/overview': typeof adminResourceOverviewPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamRouteWithChildren
@@ -6381,10 +6701,13 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/integrations/heroku/oauth2/callback': typeof secretManagerIntegrationsRouteHerokuOauthRedirectRoute
'/_authenticate/_inject-org-details/_org-layout/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsRouteNetlifyOauthRedirectRoute
'/_authenticate/_inject-org-details/_org-layout/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsRouteVercelOauthRedirectRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout': typeof agentVaultLayoutRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout': typeof pamLayoutRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdSecretManagerProjectIdRouteWithChildren
'/_authenticate/_inject-org-details/organization/app-connections/$appConnection/oauth/callback': typeof redirectsOauthCallbackRedirectRoute
'/_authenticate/_inject-org-details/organization/app-connections/github/manifest/callback': typeof redirectsGithubManifestCallbackRedirectRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute
@@ -6393,6 +6716,10 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/templates': typeof pamPamTemplatesPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/insights': typeof organizationSecretInsightsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/settings/oauth/callback': typeof organizationSettingsPageOauthCallbackPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/': typeof redirectsAgentVaultIndexRedirectRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management': typeof projectAccessControlPageRouteAgentVaultRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs': typeof projectAuditLogsPageRouteAgentVaultRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access-management': typeof projectAccessControlPageRoutePamRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccountsRouteWithChildren
@@ -6405,16 +6732,22 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/secret-sharing': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementSecretSharingRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretScanningProjectIdRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/': typeof agentVaultAgentVaultAccessBundlesPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/': typeof pamPamAccountsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/': typeof organizationKmipServersPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/product-settings/': typeof organizationProductSettingsPageSecretsManagementRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/secret-sharing/': typeof organizationSecretSharingPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId': typeof agentVaultAgentVaultAccessBundleDetailPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/$folderId': typeof pamPamAccountsPagePamFolderPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': typeof organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access/': typeof redirectsPamOrgAccessRedirectRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId': typeof projectGroupDetailsByIDPageRouteAgentVaultRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId': typeof projectIdentityDetailsByIDPageRouteAgentVaultRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId': typeof projectMemberDetailsByIDPageRouteAgentVaultRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug': typeof projectRoleDetailsBySlugPageRouteAgentVaultRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId': typeof projectGroupDetailsByIDPageRoutePamRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/identities/$identityId': typeof projectIdentityDetailsByIDPageRoutePamRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/members/$membershipId': typeof projectMemberDetailsByIDPageRoutePamRoute
@@ -6640,6 +6973,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects'
| '/organizations/$orgId/sso'
| '/admin/resources/overview'
+ | '/organizations/$orgId/agent-vault'
| '/organizations/$orgId/app-connections'
| '/organizations/$orgId/networking'
| '/organizations/$orgId/pam'
@@ -6666,6 +7000,8 @@ export interface FileRouteTypes {
| '/organizations/$orgId/secret-manager/$projectId'
| '/organization/app-connections/$appConnection/oauth/callback'
| '/organization/app-connections/github/manifest/callback'
+ | '/organizations/$orgId/agent-vault/proxies'
+ | '/organizations/$orgId/agent-vault/sessions'
| '/organizations/$orgId/networking/gateways/$gatewayId'
| '/organizations/$orgId/networking/relays/$relayId'
| '/organizations/$orgId/pam/approval-requests'
@@ -6674,6 +7010,10 @@ export interface FileRouteTypes {
| '/organizations/$orgId/pam/templates'
| '/organizations/$orgId/projects/secret-management/insights'
| '/organizations/$orgId/settings/oauth/callback'
+ | '/organizations/$orgId/agent-vault/'
+ | '/organizations/$orgId/agent-vault/access-bundles'
+ | '/organizations/$orgId/agent-vault/access-management'
+ | '/organizations/$orgId/agent-vault/audit-logs'
| '/organizations/$orgId/pam/access'
| '/organizations/$orgId/pam/access-management'
| '/organizations/$orgId/pam/accounts'
@@ -6686,16 +7026,22 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-management/secret-sharing'
| '/organizations/$orgId/projects/secret-scanning/$projectId'
| '/organizations/$orgId/secret-manager/$projectId/approval'
+ | '/organizations/$orgId/agent-vault/access-bundles/'
| '/organizations/$orgId/pam/accounts/'
| '/organizations/$orgId/projects/kms/kmip-servers/'
| '/organizations/$orgId/projects/secret-management/product-settings/'
| '/organizations/$orgId/projects/secret-management/secret-sharing/'
+ | '/organizations/$orgId/agent-vault/access-bundles/$accessBundleId'
| '/organizations/$orgId/app-connections/$appConnection/oauth/callback'
| '/organizations/$orgId/app-connections/github/manifest/callback'
| '/organizations/$orgId/pam/accounts/$folderId'
| '/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'
| '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'
| '/organizations/$orgId/pam/access/'
+ | '/organizations/$orgId/agent-vault/groups/$groupId'
+ | '/organizations/$orgId/agent-vault/identities/$identityId'
+ | '/organizations/$orgId/agent-vault/members/$membershipId'
+ | '/organizations/$orgId/agent-vault/roles/$roleSlug'
| '/organizations/$orgId/pam/groups/$groupId'
| '/organizations/$orgId/pam/identities/$identityId'
| '/organizations/$orgId/pam/members/$membershipId'
@@ -6910,6 +7256,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects'
| '/organizations/$orgId/sso'
| '/admin/resources/overview'
+ | '/organizations/$orgId/agent-vault'
| '/organizations/$orgId/pam'
| '/organizations/$orgId/secret-sharing'
| '/organization/settings/oauth/callback'
@@ -6933,6 +7280,8 @@ export interface FileRouteTypes {
| '/organizations/$orgId/secret-manager/$projectId'
| '/organization/app-connections/$appConnection/oauth/callback'
| '/organization/app-connections/github/manifest/callback'
+ | '/organizations/$orgId/agent-vault/proxies'
+ | '/organizations/$orgId/agent-vault/sessions'
| '/organizations/$orgId/networking/gateways/$gatewayId'
| '/organizations/$orgId/networking/relays/$relayId'
| '/organizations/$orgId/pam/approval-requests'
@@ -6941,6 +7290,8 @@ export interface FileRouteTypes {
| '/organizations/$orgId/pam/templates'
| '/organizations/$orgId/projects/secret-management/insights'
| '/organizations/$orgId/settings/oauth/callback'
+ | '/organizations/$orgId/agent-vault/access-management'
+ | '/organizations/$orgId/agent-vault/audit-logs'
| '/organizations/$orgId/pam/access-management'
| '/organizations/$orgId/pam/audit-logs'
| '/organizations/$orgId/projects/cert-manager/$projectId'
@@ -6948,16 +7299,22 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-management/$projectId'
| '/organizations/$orgId/projects/secret-scanning/$projectId'
| '/organizations/$orgId/secret-manager/$projectId/approval'
+ | '/organizations/$orgId/agent-vault/access-bundles'
| '/organizations/$orgId/pam/accounts'
| '/organizations/$orgId/projects/kms/kmip-servers'
| '/organizations/$orgId/projects/secret-management/product-settings'
| '/organizations/$orgId/projects/secret-management/secret-sharing'
+ | '/organizations/$orgId/agent-vault/access-bundles/$accessBundleId'
| '/organizations/$orgId/app-connections/$appConnection/oauth/callback'
| '/organizations/$orgId/app-connections/github/manifest/callback'
| '/organizations/$orgId/pam/accounts/$folderId'
| '/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'
| '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'
| '/organizations/$orgId/pam/access'
+ | '/organizations/$orgId/agent-vault/groups/$groupId'
+ | '/organizations/$orgId/agent-vault/identities/$identityId'
+ | '/organizations/$orgId/agent-vault/members/$membershipId'
+ | '/organizations/$orgId/agent-vault/roles/$roleSlug'
| '/organizations/$orgId/pam/groups/$groupId'
| '/organizations/$orgId/pam/identities/$identityId'
| '/organizations/$orgId/pam/members/$membershipId'
@@ -7168,6 +7525,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/sso'
| '/_authenticate/_inject-org-details/admin/_admin-layout/resources/overview'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam'
@@ -7191,10 +7549,13 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/integrations/heroku/oauth2/callback'
| '/_authenticate/_inject-org-details/_org-layout/integrations/netlify/oauth2/callback'
| '/_authenticate/_inject-org-details/_org-layout/integrations/vercel/oauth2/callback'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId'
| '/_authenticate/_inject-org-details/organization/app-connections/$appConnection/oauth/callback'
| '/_authenticate/_inject-org-details/organization/app-connections/github/manifest/callback'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/approval-requests'
@@ -7203,6 +7564,10 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/templates'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/insights'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/settings/oauth/callback'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access-management'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts'
@@ -7215,16 +7580,22 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/secret-sharing'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId/approval'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/product-settings/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/secret-sharing/'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/$folderId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'
| '/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access/'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/identities/$identityId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/members/$membershipId'
@@ -7708,6 +8079,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/oauth-applications",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/sso",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam",
@@ -7763,6 +8135,13 @@ export const routeTree = rootRoute
"filePath": "admin/ResourceOverviewPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/admin/_admin-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault": {
+ "filePath": "",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ ]
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections": {
"filePath": "",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId",
@@ -7872,6 +8251,22 @@ export const routeTree = rootRoute
"filePath": "secret-manager/integrations/route-vercel-oauth-redirect.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/integrations"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout": {
+ "filePath": "agent-vault/layout.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug"
+ ]
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout": {
"filePath": "pam/layout.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam",
@@ -7905,6 +8300,14 @@ export const routeTree = rootRoute
"filePath": "redirects/github-manifest-callback-redirect.tsx",
"parent": "/_authenticate/_inject-org-details"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies": {
+ "filePath": "agent-vault/AgentVaultProxiesPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions": {
+ "filePath": "agent-vault/AgentVaultSessionsPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId": {
"filePath": "organization/NetworkingPage/GatewayDetailsByIDPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking"
@@ -7937,6 +8340,26 @@ export const routeTree = rootRoute
"filePath": "organization/SettingsPage/OauthCallbackPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/settings"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/": {
+ "filePath": "redirects/agent-vault-index-redirect.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles": {
+ "filePath": "",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId"
+ ]
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management": {
+ "filePath": "project/AccessControlPage/route-agent-vault.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/audit-logs": {
+ "filePath": "project/AuditLogsPage/route-agent-vault.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access": {
"filePath": "",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout",
@@ -8015,6 +8438,10 @@ export const routeTree = rootRoute
"filePath": "secret-manager/redirects/redirect-approval-page.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/": {
+ "filePath": "agent-vault/AgentVaultAccessBundlesPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts/": {
"filePath": "pam/PamAccountsPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts"
@@ -8031,6 +8458,10 @@ export const routeTree = rootRoute
"filePath": "organization/SecretSharingPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/secret-sharing"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId": {
+ "filePath": "agent-vault/AgentVaultAccessBundleDetailPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback": {
"filePath": "organization/AppConnections/OauthCallbackPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections"
@@ -8055,6 +8486,22 @@ export const routeTree = rootRoute
"filePath": "redirects/pam-org-access-redirect.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/groups/$groupId": {
+ "filePath": "project/GroupDetailsByIDPage/route-agent-vault.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/identities/$identityId": {
+ "filePath": "project/IdentityDetailsByIDPage/route-agent-vault.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/members/$membershipId": {
+ "filePath": "project/MemberDetailsByIDPage/route-agent-vault.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/roles/$roleSlug": {
+ "filePath": "project/RoleDetailsBySlugPage/route-agent-vault.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId": {
"filePath": "project/GroupDetailsByIDPage/route-pam.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout"
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 676434be1d..62f173dc4c 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -369,7 +369,6 @@ const pamRoutes = route("/organizations/$orgId/pam", [
route("/approval-requests", "pam/PamApprovalRequestsPage/route.tsx"),
route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),
- // Access Management
route("/access-management", "project/AccessControlPage/route-pam.tsx"),
route("/roles/$roleSlug", "project/RoleDetailsBySlugPage/route-pam.tsx"),
route("/identities/$identityId", "project/IdentityDetailsByIDPage/route-pam.tsx"),
@@ -378,6 +377,25 @@ const pamRoutes = route("/organizations/$orgId/pam", [
])
]);
+const agentVaultRoutes = route("/organizations/$orgId/agent-vault", [
+ layout("agent-vault-layout", "agent-vault/layout.tsx", [
+ index("redirects/agent-vault-index-redirect.tsx"),
+ route("/sessions", "agent-vault/AgentVaultSessionsPage/route.tsx"),
+ route("/access-bundles", [
+ index("agent-vault/AgentVaultAccessBundlesPage/route.tsx"),
+ route("/$accessBundleId", "agent-vault/AgentVaultAccessBundleDetailPage/route.tsx")
+ ]),
+ route("/proxies", "agent-vault/AgentVaultProxiesPage/route.tsx"),
+ route("/audit-logs", "project/AuditLogsPage/route-agent-vault.tsx"),
+
+ route("/access-management", "project/AccessControlPage/route-agent-vault.tsx"),
+ route("/roles/$roleSlug", "project/RoleDetailsBySlugPage/route-agent-vault.tsx"),
+ route("/identities/$identityId", "project/IdentityDetailsByIDPage/route-agent-vault.tsx"),
+ route("/members/$membershipId", "project/MemberDetailsByIDPage/route-agent-vault.tsx"),
+ route("/groups/$groupId", "project/GroupDetailsByIDPage/route-agent-vault.tsx")
+ ])
+]);
+
const pamAccessRoute = route(
"/organizations/$orgId/pam/accounts/$accountType/$accountId/access",
"pam/PamAccountAccessPage/route.tsx"
@@ -496,7 +514,8 @@ export const routes = rootRoute("root.tsx", [
certManagerRoutes,
kmsRoutes,
secretScanningRoutes,
- pamRoutes
+ pamRoutes,
+ agentVaultRoutes
])
])
])
diff --git a/frontend/src/views/Alerts/AlertForm.tsx b/frontend/src/views/Alerts/AlertForm.tsx
index a1e19a1287..2a6a961349 100644
--- a/frontend/src/views/Alerts/AlertForm.tsx
+++ b/frontend/src/views/Alerts/AlertForm.tsx
@@ -55,6 +55,7 @@ type Props = {
const DEFAULT_ALERT_BEFORE_DAYS = 7;
const DEFAULT_ALERT_NAME = "Secret expiration alert";
+const ALERT_NAME_PLACEHOLDER = "Client secret expiration alert";
const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({
id: channel.id,
@@ -71,10 +72,10 @@ const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({
hasIntegrationKey: Boolean(channel.config.hasIntegrationKey)
});
-const buildFormDefaults = (alert?: TAlert): TAlertForm => {
+const buildFormDefaults = (alert: TAlert | undefined, defaultName: string): TAlertForm => {
if (!alert) {
return {
- name: DEFAULT_ALERT_NAME,
+ name: defaultName,
description: "",
resourceType: AlertResourceType.IdentityAuthentication,
eventType: AlertEventType.IdentityAuthenticationExpiry,
@@ -110,12 +111,13 @@ export const AlertForm = ({
}: Props) => {
const isEditing = Boolean(alert);
const scopeVariant = useScopeVariant();
+ const isAgentVault = scopeVariant === "av";
const createAlert = useCreateAlert();
const updateAlert = useUpdateAlert();
const formMethods = useForm<TAlertForm>({
resolver: zodResolver(alertFormSchema),
- defaultValues: buildFormDefaults(alert)
+ defaultValues: buildFormDefaults(alert, isAgentVault ? "" : DEFAULT_ALERT_NAME)
});
const {
@@ -186,7 +188,7 @@ export const AlertForm = ({
<Input
id="alert-name"
autoFocus
- placeholder={DEFAULT_ALERT_NAME}
+ placeholder={isAgentVault ? ALERT_NAME_PLACEHOLDER : DEFAULT_ALERT_NAME}
isError={Boolean(errors.name)}
{...register("name")}
autoComplete="off"