Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(agent-vault): start proxies from a proxy token (#8822)
Saif Ur Rahman4c5095c63992
diff --git a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.tsindex e8e4784ed2..93a411edf0 100644--- a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@ -1,6 +1,5 @@import crypto from "node:crypto";-import * as x509 from "@peculiar/x509";import { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";import { fakeS3Bucket } from "e2e-test/fakes/s3";import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";@@ -89,33 +88,13 @@ const createMemberIdentity = async (name: string) => {};};-const generateRootCaPem = async () => {- const alg = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" } as const;- const keys = await x509.cryptoProvider.get().subtle.generateKey(alg, false, ["sign", "verify"]);- const cert = await x509.X509CertificateGenerator.createSelfSigned({- serialNumber: "01",- name: "CN=agent-vault-test-ca",- notBefore: new Date(Date.now() - 60_000),- notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),- signingAlgorithm: alg,- keys,- extensions: [new x509.BasicConstraintsExtension(true, 1, true)]- });- return cert.toString("pem");-};-const createProxy = async (name: string) => {const res = await inject("POST", "/api/v1/agent-vault/proxies", { name });expect(res.statusCode).toBe(200);- const { proxy, token } = JSON.parse(res.payload) as { proxy: { id: string; name: string }; token: string };-- const enrolled = await testServer.inject({- method: "POST",- url: "/api/v1/agent-vault/proxy/login",- body: { method: "token", token, rootCaCertificate: await generateRootCaPem() }- });- expect(enrolled.statusCode, enrolled.payload).toBe(200);- const { accessToken } = JSON.parse(enrolled.payload) as { accessToken: string };+ const { proxy, proxyToken: accessToken } = JSON.parse(res.payload) as {+ proxy: { id: string; name: string };+ proxyToken: string;+ };return {...proxy,diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex f9f140dff5..ca98f90fa9 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -21,7 +21,6 @@ import { groupDALFactory } from "@app/ee/services/group/group-dal";import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";-import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig, initEnvConfig } from "@app/lib/config/env";import { UnauthorizedError } from "@app/lib/errors";@@ -812,26 +811,6 @@ describe("Agent Vault V1 Router", async () => {const referencesByField = (references: TReference[]) =>references.map((reference) => `${reference.field}:${reference.key}`).sort();- // Enrollment only checks that it is a live CA. ECDSA P-256, because the FIPS image refuses Ed25519.- const createProxyCaPem = async () => {- const algorithm = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };- const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);- const certificate = await x509.X509CertificateGenerator.createSelfSigned({- name: "CN=Agent Vault Variables Test CA",- serialNumber: "01",- notBefore: new Date(Date.now() - 60_000),- notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),- signingAlgorithm: algorithm,- keys,- extensions: [- new x509.BasicConstraintsExtension(true, undefined, true),- // eslint-disable-next-line no-bitwise- new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)- ]- });- return certificate.toString("pem");- };-type TResolved = {services: {name: string;@@ -852,14 +831,7 @@ describe("Agent Vault V1 Router", async () => {const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: proxyName });expect(created.statusCode).toBe(200);- const { token } = JSON.parse(created.payload) as { token: string };- const login = await testServer.inject({- method: "POST",- url: "/api/v1/agent-vault/proxy/login",- body: { method: ResourceAuthMethodType.Token, token, rootCaCertificate: await createProxyCaPem() }- });- expect(login.statusCode).toBe(200);- const { accessToken } = JSON.parse(login.payload) as { accessToken: string };+ const { proxyToken: accessToken } = JSON.parse(created.payload) as { proxyToken: string };return async () => {const resolved = await testServer.inject({@@ -3275,42 +3247,30 @@ describe("Agent Vault V1 Router", async () => {expect(proxy.pollInterval).toBe(60);});- test("create and reissue both hand back the enrollment token at the top level", async () => {+ test("create and rotate both hand back the proxy 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/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();+ const body = JSON.parse(created.payload) as { proxy: { id: string }; proxyToken: string };+ expect(body.proxyToken).toBeTruthy();++ const rotated = await inject("POST", `/api/v1/agent-vault/proxies/${body.proxy.id}/token-auth/proxy-token`);+ expect(rotated.statusCode).toBe(200);+ const again = JSON.parse(rotated.payload) as { proxyToken: string };+ expect(again.proxyToken).toBeTruthy();+ expect(again.proxyToken).not.toBe(body.proxyToken);});- 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" });+ test("revoking access bumps the token version and clears the heartbeat", async () => {+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: "revoke-bumps-version" });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);+ expect((await testDb("agent_vault_proxies").where({ id: proxy.id }).first()).tokenVersion).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.tokenVersion).toBe(2);expect(row.heartbeat).toBeNull();expect(row.heartbeatTTL).toBeNull();});@@ -3351,6 +3311,236 @@ describe("Agent Vault V1 Router", async () => {});});+ describe("proxy tokens and Infisical-held CAs", async () => {+ type TRootCa = { certificate: string; privateKey: string };++ const fingerprintOf = (pem: string) => {+ const digest = crypto+ .createHash("sha256")+ .update(Buffer.from(new x509.X509Certificate(pem).rawData))+ .digest("hex")+ .toUpperCase();+ return `SHA256:${digest.match(/.{2}/g)!.join(":")}`;+ };++ const caPem = async ({+ isCa = true,+ rsa = false,+ notBefore = new Date(Date.now() - 60_000)+ }: { isCa?: boolean; rsa?: boolean; notBefore?: Date } = {}) => {+ const algorithm = rsa+ ? { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }+ : { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };+ const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);+ const certificate = await x509.X509CertificateGenerator.createSelfSigned({+ name: "CN=Agent Vault Test CA",+ serialNumber: "01",+ notBefore,+ notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),+ signingAlgorithm: algorithm,+ keys,+ extensions: [+ new x509.BasicConstraintsExtension(isCa, undefined, true),+ // eslint-disable-next-line no-bitwise+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)+ ]+ });+ return certificate.toString("pem");+ };++ const asProxy = (accessToken: string, url: string, body?: Record<string, unknown>) =>+ testServer.inject({+ method: "POST",+ url: `/api/v1/agent-vault/proxy/${url}`,+ headers: { authorization: `Bearer ${accessToken}` },+ body+ });++ const createProxy = async (name: string) => {+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name });+ expect(created.statusCode).toBe(200);+ return JSON.parse(created.payload) as {+ proxy: { id: string; rootCaFingerprint: string | null };+ proxyToken: string;+ };+ };++ const rotate = async (proxyId: string) => {+ const rotated = await inject("POST", `/api/v1/agent-vault/proxies/${proxyId}/token-auth/proxy-token`);+ expect(rotated.statusCode).toBe(200);+ return JSON.parse(rotated.payload) as { proxy: { rootCaFingerprint: string | null }; proxyToken: string };+ };++ test("create returns a proxy token and the fingerprint of the CA bootstrap returns", async () => {+ const created = await createProxy("token-create");+ expect(created.proxyToken).toBeTruthy();+ // Shown before anything starts, so it can be pinned without running a proxy first.+ expect(created.proxy.rootCaFingerprint).toMatch(/^SHA256:/);++ const boot = await asProxy(created.proxyToken, "bootstrap", {});+ expect(boot.statusCode).toBe(200);+ const body = JSON.parse(boot.payload) as { proxyId: string; rootCa: TRootCa; config: { pollInterval: number } };+ expect(body.proxyId).toBe(created.proxy.id);+ expect(body.config.pollInterval).toBe(60);+ expect(body.rootCa.privateKey).toContain("BEGIN PRIVATE KEY");+ expect(fingerprintOf(body.rootCa.certificate)).toBe(created.proxy.rootCaFingerprint);++ const again = JSON.parse((await asProxy(created.proxyToken, "bootstrap", {})).payload) as { rootCa: TRootCa };+ expect(again.rootCa.certificate).toBe(body.rootCa.certificate);++ expect((await asProxy(created.proxyToken, "heartbeat")).statusCode).toBe(200);+ });++ test("the generated CA is a P-256 CA valid for about ten years", async () => {+ const created = await createProxy("token-ca-shape");+ const { rootCa } = JSON.parse((await asProxy(created.proxyToken, "bootstrap", {})).payload) as {+ rootCa: TRootCa;+ };+ const cert = new x509.X509Certificate(rootCa.certificate);+ expect(cert.getExtension(x509.BasicConstraintsExtension)?.ca).toBe(true);+ expect((cert.publicKey.algorithm as { namedCurve?: string }).namedCurve).toBe("P-256");+ const years = (cert.notAfter.getTime() - Date.now()) / (365 * 24 * 60 * 60 * 1000);+ expect(years).toBeGreaterThan(9.9);+ expect(years).toBeLessThan(10.1);++ // The CLI sends a CA it serves itself through the same parser, so Infisical's own CA must pass it too.+ expect(+ (await asProxy(created.proxyToken, "bootstrap", { servedCaCertificate: rootCa.certificate })).statusCode+ ).toBe(200);+ });++ test("rotating stops the old token, replaces the CA, and shows the new CA's fingerprint", async () => {+ const created = await createProxy("token-rotate");+ const first = JSON.parse((await asProxy(created.proxyToken, "bootstrap", {})).payload) as { rootCa: TRootCa };+ const next = await rotate(created.proxy.id);+ expect(next.proxy.rootCaFingerprint).toMatch(/^SHA256:/);+ expect(next.proxy.rootCaFingerprint).not.toBe(created.proxy.rootCaFingerprint);++ expect((await asProxy(created.proxyToken, "heartbeat")).statusCode).toBe(401);+ const boot = JSON.parse((await asProxy(next.proxyToken, "bootstrap", {})).payload) as { rootCa: TRootCa };+ expect(boot.rootCa.certificate).not.toBe(first.rootCa.certificate);+ expect(fingerprintOf(boot.rootCa.certificate)).toBe(next.proxy.rootCaFingerprint);+ });++ test("two rotations at once each return a token and CA that belong together, and the last one wins", async () => {+ const created = await createProxy("token-rotate-race");+ const [first, second] = await Promise.all([rotate(created.proxy.id), rotate(created.proxy.id)]);++ const results = await Promise.all(+ [first, second].map(async (r) => ({+ r,+ boot: await asProxy(r.proxyToken, "bootstrap", {})+ }))+ );+ const live = results.filter(({ boot }) => boot.statusCode === 200);+ expect(live).toHaveLength(1);+ const { rootCa } = JSON.parse(live[0].boot.payload) as { rootCa: TRootCa };++ const row = await testDb("agent_vault_proxies").where({ id: created.proxy.id }).first();+ expect(row.tokenVersion).toBe(3);+ expect(row.rootCaCertificate).toBe(rootCa.certificate);+ expect(row.rootCaFingerprint).toBe(fingerprintOf(rootCa.certificate));+ });++ test("revoking access stops the token, and rotating brings the proxy back", async () => {+ const created = await createProxy("token-revoke");+ expect((await inject("POST", `/api/v1/agent-vault/proxies/${created.proxy.id}/revoke`)).statusCode).toBe(200);+ expect((await asProxy(created.proxyToken, "bootstrap", {})).statusCode).toBe(401);++ const next = await rotate(created.proxy.id);+ expect((await asProxy(next.proxyToken, "bootstrap", {})).statusCode).toBe(200);+ });++ test("a member can't rotate a proxy's token", async () => {+ const created = await createProxy("token-member-rotate");+ const member = await createUaIdentity(`av-proxy-member-${Date.now()}`);+ try {+ expect(+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [member.id], role: "member" }))+ .statusCode+ ).toBe(200);+ const rotated = await member.asIdentity(+ "POST",+ `/api/v1/agent-vault/proxies/${created.proxy.id}/token-auth/proxy-token`+ );+ expect(rotated.statusCode).toBe(403);+ } finally {+ await deleteUaIdentity(member.id);+ }+ });++ test("a proxy serving its own CA reports it and gets no CA back", async () => {+ const created = await createProxy("token-own-ca");+ const own = await caPem();+ const boot = await asProxy(created.proxyToken, "bootstrap", { servedCaCertificate: own });+ expect(boot.statusCode).toBe(200);+ expect((JSON.parse(boot.payload) as { rootCa?: TRootCa }).rootCa).toBeUndefined();++ const row = await testDb("agent_vault_proxies").where({ id: created.proxy.id }).first();+ expect(row.rootCaFingerprint).toBe(fingerprintOf(own));+ expect(row.encryptedRootCaPrivateKey).not.toBeNull();+ });++ test("a served CA that isn't a CA, or isn't a certificate, is refused and changes nothing", async () => {+ const created = await createProxy("token-bad-served-ca");+ const before = await testDb("agent_vault_proxies").where({ id: created.proxy.id }).first();++ const leaf = await asProxy(created.proxyToken, "bootstrap", {+ servedCaCertificate: await caPem({ isCa: false })+ });+ expect(leaf.statusCode).toBe(400);+ const garbage = await asProxy(created.proxyToken, "bootstrap", { servedCaCertificate: "not a certificate" });+ expect(garbage.statusCode).toBe(400);+ const rsa = await asProxy(created.proxyToken, "bootstrap", { servedCaCertificate: await caPem({ rsa: true }) });+ expect(rsa.statusCode).toBe(400);+ expect((JSON.parse(rsa.payload) as { message: string }).message).toContain("P-256");+ const future = await asProxy(created.proxyToken, "bootstrap", {+ servedCaCertificate: await caPem({ notBefore: new Date(Date.now() + 60 * 60 * 1000) })+ });+ expect(future.statusCode).toBe(400);+ expect((JSON.parse(future.payload) as { message: string }).message).toContain("valid from");++ const after = await testDb("agent_vault_proxies").where({ id: created.proxy.id }).first();+ expect(after.rootCaFingerprint).toBe(before.rootCaFingerprint);+ });++ test("a CA that starts a little in the future is accepted, for a CLI whose clock is ahead", async () => {+ const created = await createProxy("token-clock-ahead");+ const own = await caPem({ notBefore: new Date(Date.now() + 2 * 60 * 1000) });+ expect((await asProxy(created.proxyToken, "bootstrap", { servedCaCertificate: own })).statusCode).toBe(200);+ });++ test("a proxy enrolled before tokens had no stored CA gets one at bootstrap, the same for every start", async () => {+ const created = await createProxy("token-legacy-ca");+ await testDb("agent_vault_proxies")+ .where({ id: created.proxy.id })+ .update({ rootCaCertificate: null, encryptedRootCaPrivateKey: null });++ const boots = await Promise.all([1, 2, 3].map(() => asProxy(created.proxyToken, "bootstrap", {})));+ boots.forEach((boot) => expect(boot.statusCode).toBe(200));+ const certificates = new Set(+ boots.map((boot) => (JSON.parse(boot.payload) as { rootCa: TRootCa }).rootCa.certificate)+ );+ expect(certificates.size).toBe(1);++ const row = await testDb("agent_vault_proxies").where({ id: created.proxy.id }).first();+ expect(row.rootCaFingerprint).toBe(fingerprintOf([...certificates][0]));+ });++ test("the enrollment routes are gone", async () => {+ const created = await createProxy("token-no-enrollment");+ expect(+ (await inject("POST", `/api/v1/agent-vault/proxies/${created.proxy.id}/token-auth/enrollment-token`)).statusCode+ ).toBe(404);+ const login = await testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/login",+ body: { method: "token", token: "avp_x" }+ });+ expect(login.statusCode).toBe(404);+ });+ });+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 {diff --git a/backend/src/db/migrations/20261022093358_agent-vault-proxy-stored-ca.ts b/backend/src/db/migrations/20261022093358_agent-vault-proxy-stored-ca.tsnew file mode 100644index 0000000000..1beb4a506e--- /dev/null+++ b/backend/src/db/migrations/20261022093358_agent-vault-proxy-stored-ca.ts@@ -0,0 +1,23 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasCertificate = await knex.schema.hasColumn(TableName.AgentVaultProxy, "rootCaCertificate");+ const hasPrivateKey = await knex.schema.hasColumn(TableName.AgentVaultProxy, "encryptedRootCaPrivateKey");++ await knex.schema.alterTable(TableName.AgentVaultProxy, (t) => {+ if (!hasCertificate) t.text("rootCaCertificate").nullable();+ if (!hasPrivateKey) t.binary("encryptedRootCaPrivateKey").nullable();+ });+}++export async function down(knex: Knex): Promise<void> {+ const hasCertificate = await knex.schema.hasColumn(TableName.AgentVaultProxy, "rootCaCertificate");+ const hasPrivateKey = await knex.schema.hasColumn(TableName.AgentVaultProxy, "encryptedRootCaPrivateKey");++ await knex.schema.alterTable(TableName.AgentVaultProxy, (t) => {+ if (hasCertificate) t.dropColumn("rootCaCertificate");+ if (hasPrivateKey) t.dropColumn("encryptedRootCaPrivateKey");+ });+}diff --git a/backend/src/db/schemas/agent-vault-proxies.ts b/backend/src/db/schemas/agent-vault-proxies.tsindex 66cfdcf526..dc8790caa3 100644--- a/backend/src/db/schemas/agent-vault-proxies.ts+++ b/backend/src/db/schemas/agent-vault-proxies.ts@@ -5,6 +5,8 @@import { z } from "zod";+import { zodBuffer } from "@app/lib/zod";+import { TImmutableDBKeys } from "./models";export const AgentVaultProxiesSchema = z.object({@@ -20,7 +22,9 @@ export const AgentVaultProxiesSchema = z.object({allowedHosts: z.string().nullable().optional(),pollInterval: z.number().default(60),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ rootCaCertificate: z.string().nullable().optional(),+ encryptedRootCaPrivateKey: zodBuffer.nullable().optional()});export type TAgentVaultProxies = z.infer<typeof AgentVaultProxiesSchema>;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.tsindex 80c17f6e36..7d87a82bc2 100644--- 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@@ -6,20 +6,17 @@ import {AgentVaultSessionLogChunkCreateResponseSchema,AgentVaultSessionLogChunkCreateSchema} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-schemas";-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 { UnauthorizedError } from "@app/lib/errors";import {+ agentVaultBootstrapLimit,agentVaultHeartbeatLimit,agentVaultResolveLimit,- agentVaultSessionLogChunkLimit,- writeLimit+ agentVaultSessionLogChunkLimit} 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";+import { AuthMode } from "@app/services/auth/auth-type";const ProxyConfigSchema = z.object({trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),@@ -27,87 +24,55 @@ const ProxyConfigSchema = z.object({pollInterval: z.number().describe(AGENT_VAULT.PROXY.pollInterval)});+const RootCaSchema = z+ .object({+ certificate: z.string().describe(AGENT_VAULT.PROXY.rootCaCertificatePem),+ privateKey: z.string().describe(AGENT_VAULT.PROXY.rootCaPrivateKey)+ })+ .describe(AGENT_VAULT.PROXY.rootCa);+const SESSION_HEADER = "x-infisical-agent-session";export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvider) => {+ // POST, not GET: a proxy serving its own certificate authority reports it here, and that is recorded.server.route({method: "POST",- url: "/login",- config: { rateLimit: writeLimit },+ url: "/bootstrap",+ config: { rateLimit: agentVaultBootstrapLimit },schema: {hide: true,- operationId: "loginAgentVaultProxy",+ operationId: "bootstrapAgentVaultProxy",description:- "Proxy login. Body discriminates on `method`; token exchanges a one-time enrollment token for the proxy's access token.",+ "Start a proxy: returns its identity, settings and, unless it serves its own, the certificate authority",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)- })- ]),+ body: z.object({+ servedCaCertificate: z+ .string()+ .trim()+ .min(1)+ .max(16384)+ .optional()+ .describe(AGENT_VAULT.PROXY.servedCaCertificate)+ }),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+ config: ProxyConfigSchema,+ rootCa: RootCaSchema.optional()})}},+ onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),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}]`- );+ if (req.auth.authMode !== AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN) {+ throw new UnauthorizedError({ message: "A proxy token is required" });}-- 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- };+ return server.services.agentVaultProxy.bootstrap({+ proxyId: req.permission.id,+ tokenVersion: req.auth.token.tokenVersion,+ servedCaCertificate: req.body.servedCaCertificate+ });}});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.tsindex 50784c88a8..7978ee087e 100644--- 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@@ -5,6 +5,7 @@ import { buildHostPatternSchema, parseHostPatterns } from "@app/ee/services/agenimport { 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 { logger } from "@app/lib/logger";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { slugSchema } from "@app/server/lib/schemas";import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";@@ -31,9 +32,9 @@ const ProxyAdminViewSchema = ProxyMemberViewSchema.extend({createdAt: z.date().describe(AGENT_VAULT.PROXY.createdAt)}).describe(JSON.stringify({ title: "Admin view" }));-const EnrollmentSchema = z.object({- token: z.string().describe(AGENT_VAULT.PROXY.enrollmentToken),- expiresAt: z.date()+const ProxyWithTokenSchema = z.object({+ proxy: ProxyAdminViewSchema,+ proxyToken: z.string().describe(AGENT_VAULT.PROXY.proxyToken)});const ProxySettingsSchema = {@@ -82,7 +83,7 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)schema: {hide: false,operationId: "createAgentVaultProxy",- description: "Register an Agent Vault proxy and issue its one-time enrollment token",+ description: "Register an Agent Vault proxy and issue its proxy token",tags: [ApiDocsTags.AgentVaultProxies],body: z.object({name: slugSchema({ max: 64, field: "Name" }).describe(AGENT_VAULT.PROXY.name),@@ -90,25 +91,30 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)allowedHosts: ProxySettingsSchema.allowedHosts.default(null),pollInterval: ProxySettingsSchema.pollInterval.default(60)}),- response: { 200: z.object({ proxy: ProxyAdminViewSchema, ...EnrollmentSchema.shape }) }+ response: { 200: ProxyWithTokenSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { proxy, enrollment } = await server.services.agentVaultProxy.createProxy({+ const { proxy, proxyToken } = 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 }- }- });+ // The proxy exists and this response is the only copy of its token, so an audit failure must not fail it.+ try {+ 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 }+ }+ });+ } catch (error) {+ logger.error(error, `agentVaultProxyCreate: failed to write the audit log [proxyId=${proxy.id}]`);+ }emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultProxyRegistered,@@ -121,7 +127,7 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)}});- return { proxy, ...enrollment };+ return { proxy, proxyToken };}});@@ -224,40 +230,47 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)server.route({method: "POST",- url: "/:proxyId/token-auth/enrollment-token",+ url: "/:proxyId/token-auth/proxy-token",config: { rateLimit: writeLimit },schema: {hide: false,- operationId: "reissueAgentVaultProxyEnrollmentToken",- description: "Issue a replacement enrollment token for an Agent Vault proxy",+ operationId: "rotateAgentVaultProxyToken",+ description:+ "Issue a new proxy token. The proxy's earlier tokens stop working and it gets a new certificate authority.",tags: [ApiDocsTags.AgentVaultProxies],params: z.object({ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId) }),- response: { 200: EnrollmentSchema }+ response: { 200: ProxyWithTokenSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { proxy, enrollment } = await server.services.agentVaultProxy.reissueEnrollmentToken({+ const { proxy, proxyToken } = await server.services.agentVaultProxy.rotateProxyToken({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 }- }- });+ // The old token is already dead and this response is the only copy of the new one, so an audit failure+ // must not fail it.+ try {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_PROXY_TOKEN_ROTATE,+ metadata: { proxyId: proxy.id, name: proxy.name }+ }+ });+ } catch (error) {+ logger.error(error, `agentVaultProxyTokenRotate: failed to write the audit log [proxyId=${proxy.id}]`);+ }emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProxyEnrollmentTokenReissued,+ event: PostHogEventTypes.AgentVaultProxyTokenRotated,properties: { proxyId: proxy.id }});- return enrollment;+ return { proxy, proxyToken };}});@@ -268,7 +281,7 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)schema: {hide: false,operationId: "revokeAgentVaultProxyAccess",- description: "Revoke an Agent Vault proxy's access token",+ description: "Revoke an Agent Vault proxy's token. Rotate its token to bring it back.",tags: [ApiDocsTags.AgentVaultProxies],params: z.object({ proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId) }),response: { 200: z.object({ proxy: ProxyAdminViewSchema }) }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.tsindex 350bd2de6d..90a0d74d5a 100644--- 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@@ -2,15 +2,28 @@ import * as x509 from "@peculiar/x509";import { crypto } from "@app/lib/crypto";import { BadRequestError } from "@app/lib/errors";+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import {+ createSerialNumber,+ getNotAfterWithClockSkew,+ getNotBeforeWithClockSkew,+ keyAlgorithmToAlgCfg+} from "@app/services/certificate-authority/certificate-authority-fns";export type TParsedRootCa = {fingerprint: string;expiresAt: Date;};-const MAX_ROOT_CA_PEM_LENGTH = 16384;+export type TGeneratedRootCa = TParsedRootCa & {+ certificate: string;+ privateKey: string;+};-/** Derives the fingerprint and expiry once, at enrollment; the certificate itself is never stored. */+const MAX_ROOT_CA_PEM_LENGTH = 16384;+// A CA made moments before the proxy started can read as not yet valid when this server's clock is behind.+const NOT_BEFORE_CLOCK_TOLERANCE_MS = 5 * 60 * 1000;+const GENERATED_ROOT_CA_VALIDITY_YEARS = 10;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" });@@ -28,20 +41,20 @@ export const parseRootCaCertificate = (pem: string): TParsedRootCa => {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."+ message: "The certificate is not a certificate authority. A proxy serves a 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.`- });+ // The same rule the CLI applies before it serves a CA.+ const { name: keyAlgorithm, namedCurve } = certificate.publicKey.algorithm as { name?: string; namedCurve?: string };+ if (keyAlgorithm !== "ECDSA" || namedCurve !== "P-256") {+ throw new BadRequestError({ message: "The proxy's certificate authority must use a P-256 ECDSA key." });}- if (certificate.notBefore > new Date()) {+ const now = Date.now();+ if (certificate.notAfter.getTime() <= now || certificate.notBefore.getTime() > now + NOT_BEFORE_CLOCK_TOLERANCE_MS) {throw new BadRequestError({- message: `The certificate authority is not valid until ${certificate.notBefore.toISOString()}. Nothing will accept the certificates it signs before then.`+ message: `The proxy's certificate authority isn't valid yet or has expired (valid from ${certificate.notBefore.toISOString()} to ${certificate.notAfter.toISOString()}).`});}@@ -54,3 +67,36 @@ export const parseRootCaCertificate = (pem: string): TParsedRootCa => {return { fingerprint, expiresAt: certificate.notAfter };};++// The same key type and subject the CLI uses for a CA it makes itself, so agents see no difference.+export const generateProxyRootCa = async (): Promise<TGeneratedRootCa> => {+ const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.ECDSA_P256);+ const keys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);++ const issuedAt = new Date();+ const expiresAt = new Date(new Date(issuedAt).setFullYear(issuedAt.getFullYear() + GENERATED_ROOT_CA_VALIDITY_YEARS));++ const certificate = await x509.X509CertificateGenerator.createSelfSigned({+ name: "CN=Infisical Agent Vault Proxy",+ serialNumber: createSerialNumber(),+ notBefore: getNotBeforeWithClockSkew(issuedAt),+ notAfter: getNotAfterWithClockSkew(expiresAt),+ signingAlgorithm: alg,+ keys,+ extensions: [+ // eslint-disable-next-line no-bitwise+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true),+ new x509.BasicConstraintsExtension(true, 0, true),+ await x509.SubjectKeyIdentifierExtension.create(keys.publicKey)+ ]+ });++ const certificatePem = certificate.toString("pem");+ const privateKey = crypto.nativeCrypto.KeyObject.from(keys.privateKey).export({ type: "pkcs8", format: "pem" });++ return {+ ...parseRootCaCertificate(certificatePem),+ certificate: certificatePem,+ privateKey: privateKey.toString()+ };+};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.tsindex df67c4518f..518391a6e3 100644--- 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@@ -98,6 +98,29 @@ export const agentVaultProxyDALFactory = (db: TDbClient) => {}};+ // Only fills an empty CA, and only at the token version the caller was checked against, so neither a racing+ // start nor a rotation that landed in between can be overwritten.+ const storeRootCaIfMissing = async (+ id: string,+ tokenVersion: number,+ ca: Pick<+ TAgentVaultProxies,+ "rootCaCertificate" | "encryptedRootCaPrivateKey" | "rootCaFingerprint" | "rootCaExpiresAt"+ >,+ tx?: Knex+ ): Promise<TAgentVaultProxies | undefined> => {+ try {+ const [updated] = (await (tx || db)(TableName.AgentVaultProxy)+ .where({ id, tokenVersion })+ .whereNull("rootCaCertificate")+ .update(ca)+ .returning("*")) as TAgentVaultProxies[];+ return updated;+ } catch (error) {+ throw new DatabaseError({ error, name: "Store agent vault proxy root CA" });+ }+ };+const countByProjectId = async (projectId: string, tx?: Knex) => {try {const result = await (tx || db.replicaNode())(TableName.AgentVaultProxy).where({ projectId }).count("id").first();@@ -107,5 +130,13 @@ export const agentVaultProxyDALFactory = (db: TDbClient) => {}};- return { ...orm, findByIdWithOrg, findByIdInProject, findForList, recordHeartbeat, countByProjectId };+ return {+ ...orm,+ findByIdWithOrg,+ findByIdInProject,+ findForList,+ recordHeartbeat,+ storeRootCaIfMissing,+ countByProjectId+ };};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.tsindex 367fe1ca56..0eca1f7bce 100644--- 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@@ -38,18 +38,22 @@ import {} from "../agent-vault-session-log/agent-vault-session-log-fns";import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";-import { RESOURCE_TYPE_AGENT_VAULT_PROXY } from "../resource-auth-method/resource-auth-method-fns";+import {+ mintAgentVaultProxyJwt,+ 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 { generateProxyRootCa, parseRootCaCertificate } from "./agent-vault-ca-fns";import { TAgentVaultProxyDALFactory } from "./agent-vault-proxy-dal";import {TAgentVaultProxyConfig,TAgentVaultProxyScoped,+ TBootstrapProxyDTO,TCreateProxyDTO,- TEnrollProxyDTO,THeartbeatDTO,TListProxiesDTO,TProxyByIdDTO,+ TProxyRootCa,TResolvedService,TResolveSessionDTO,TUpdateProxyDTO@@ -74,10 +78,7 @@ type TAgentVaultProxyServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;licenseService: TSessionLogLicenseService;- resourceAuthMethodService: Pick<- TResourceAuthMethodServiceFactory,- "initAtCreate" | "mintToken" | "loginWithToken" | "revokeAccess"- >;+ resourceAuthMethodService: Pick<TResourceAuthMethodServiceFactory, "initAtCreate" | "revokeAccess">;};export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;@@ -151,6 +152,71 @@ export const agentVaultProxyServiceFactory = ({const getProxyForAuth = (proxyId: string) => agentVaultProxyDAL.findByIdWithOrg(proxyId);+ const $sealRootCaKey = async (projectId: string, privateKey: string) => {+ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ return encryptor({ plainText: Buffer.from(privateKey) }).cipherTextBlob;+ };++ const $openRootCa = async (proxy: TAgentVaultProxies): Promise<TProxyRootCa | null> => {+ if (!proxy.rootCaCertificate || !proxy.encryptedRootCaPrivateKey) return null;+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: proxy.projectId+ });+ return {+ certificate: proxy.rootCaCertificate,+ privateKey: decryptor({ cipherTextBlob: proxy.encryptedRootCaPrivateKey }).toString()+ };+ };++ // Key generation is CPU-bound and the KMS may be remote, so a CA is always made before any write. Create and+ // rotate record its fingerprint too, so it can be pinned before any start; a start serving another CA replaces it.+ const $newRootCa = async (projectId: string) => {+ const generated = await generateProxyRootCa();+ return {+ privateKey: generated.privateKey,+ stored: {+ rootCaCertificate: generated.certificate,+ encryptedRootCaPrivateKey: await $sealRootCaKey(projectId, generated.privateKey)+ },+ reported: {+ rootCaFingerprint: generated.fingerprint,+ rootCaExpiresAt: generated.expiresAt+ }+ };+ };++ // Every proxy created or rotated gets a CA. Only proxies enrolled before that reach the fill-in path, and+ // several of their starts can race: storeRootCaIfMissing lets one win and the rest read its CA back. A+ // rotation can also land while the CA is being made, and its CA must never reach the old token.+ // recorded: this call already wrote the fingerprint, so the caller has nothing left to record.+ const $getOrCreateRootCa = async (+ proxy: TAgentVaultProxies+ ): Promise<{ rootCa: TProxyRootCa; recorded: boolean }> => {+ const existing = await $openRootCa(proxy);+ if (existing) return { rootCa: existing, recorded: false };++ const { stored, reported, privateKey } = await $newRootCa(proxy.projectId);+ const filled = await agentVaultProxyDAL.storeRootCaIfMissing(proxy.id, proxy.tokenVersion, {+ ...stored,+ ...reported+ });+ if (filled) return { rootCa: { certificate: stored.rootCaCertificate, privateKey }, recorded: true };++ // Read on the primary, inside a transaction: the replica may not have the winner's CA yet.+ const winner = await agentVaultProxyDAL.transaction((tx) => agentVaultProxyDAL.findById(proxy.id, tx));+ if (!winner) throw new UnauthorizedError({ message: "This proxy no longer exists" });+ if (winner.tokenVersion !== proxy.tokenVersion) {+ throw new UnauthorizedError({ name: "ProxyTokenRejected", message: "Agent Vault proxy token has been revoked" });+ }+ const opened = await $openRootCa(winner);+ if (!opened) throw new InternalServerError({ message: "Failed to load this proxy's certificate authority" });+ return { rootCa: opened, recorded: false };+ };+const listProxies = async ({ search, orderBy, orderDirection, limit, offset, ...dto }: TListProxiesDTO) => {const { isAdmin } = await $authorize(dto, ProjectPermissionAgentVaultProxyActions.Read);const { proxies, totalCount } = await agentVaultProxyDAL.findForList({@@ -173,16 +239,8 @@ export const agentVaultProxyServiceFactory = ({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 $signProxyToken = (proxyId: string, orgId: string, tokenVersion: number) =>+ mintAgentVaultProxyJwt({ agentVaultProxyId: proxyId, orgId, tokenVersion, accessTokenTTL: 0 });const createProxy = async ({ projectId, ctx, name, ...settings }: TCreateProxyDTO) => {await $authorize({ projectId, ctx }, ProjectPermissionAgentVaultProxyActions.Create);@@ -190,6 +248,9 @@ export const agentVaultProxyServiceFactory = ({const existing = await agentVaultProxyDAL.findOne({ projectId, name });if (existing) throw new BadRequestError({ message: `A proxy named '${name}' already exists` });+ const { stored, reported } = await $newRootCa(projectId);+ const rootCa = { ...stored, ...reported };+const create = () =>agentVaultProxyDAL.transaction(async (tx) => {// Serialised per project so two creates at once can't both slip under the cap.@@ -201,13 +262,16 @@ export const agentVaultProxyServiceFactory = ({});}+ // tokenVersion starts at 1: Revoke Access only counts a resource as revocable once it is above 0.const created = await agentVaultProxyDAL.create({projectId,name,trafficPolicy: settings.trafficPolicy ?? AgentVaultTrafficPolicy.AnyHost,allowedHosts: settings.allowedHosts ?? null,- pollInterval: settings.pollInterval ?? 60+ pollInterval: settings.pollInterval ?? 60,+ tokenVersion: 1,+ ...rootCa},tx);@@ -217,7 +281,9 @@ export const agentVaultProxyServiceFactory = ({tx);- return created;+ const withOrg = await agentVaultProxyDAL.findByIdWithOrg(created.id, tx);+ if (!withOrg) throw new InternalServerError({ message: "Failed to create the proxy" });+ return withOrg;});let proxy;@@ -228,17 +294,39 @@ export const agentVaultProxyServiceFactory = ({throw err;}- // Outside the transaction: minting hits KMS.- const enrollment = await $issueEnrollmentToken(proxy.id, ctx, "create");- return { proxy: toAdminView(proxy), enrollment };+ return { proxy: toAdminView(proxy), proxyToken: $signProxyToken(proxy.id, proxy.orgId, proxy.tokenVersion) };};- // Does NOT bump tokenVersion, so a running proxy keeps serving until the replacement enrolls.- const reissueEnrollmentToken = async ({ projectId, ctx, proxyId }: TProxyByIdDTO) => {+ // One UPDATE bumps tokenVersion and swaps the CA, so no token ever pairs with the wrong CA. Two rotations at+ // once queue on the row lock, and each response carries the version and CA its own UPDATE returned.+ const rotateProxyToken = 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 { stored, reported } = await $newRootCa(proxy.projectId);++ const rotated = await agentVaultProxyDAL.transaction(async (tx) => {+ const updated = await agentVaultProxyDAL.updateById(+ proxy.id,+ {+ $incr: { tokenVersion: 1 },+ heartbeat: null,+ heartbeatTTL: null,+ ...stored,+ ...reported+ },+ tx+ );+ if (!updated) throw new NotFoundError({ message: `Proxy with ID '${proxyId}' not found` });+ const withOrg = await agentVaultProxyDAL.findByIdWithOrg(proxy.id, tx);+ if (!withOrg) throw new NotFoundError({ message: `Proxy with ID '${proxyId}' not found` });+ return withOrg;+ });++ return {+ proxy: toAdminView(rotated),+ proxyToken: $signProxyToken(rotated.id, rotated.orgId, rotated.tokenVersion)+ };};const updateProxy = async ({ projectId, ctx, proxyId, name, ...settings }: TUpdateProxyDTO) => {@@ -266,8 +354,6 @@ export const agentVaultProxyServiceFactory = ({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 });@@ -278,34 +364,35 @@ export const agentVaultProxyServiceFactory = ({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);+ // Every proxy calls this on start. One serving its own CA reports it and gets none back; either way the row+ // ends up showing the CA the most recent start serves.+ const bootstrap = async ({ proxyId, tokenVersion, servedCaCertificate }: TBootstrapProxyDTO) => {+ const proxy = await agentVaultProxyDAL.findByIdWithOrg(proxyId);+ if (!proxy) throw new UnauthorizedError({ message: "This proxy no longer exists" });+ // The auth check ran on an earlier read; a rotation landing in between must not hand the old token the new CA.+ if (proxy.tokenVersion !== tokenVersion) {+ throw new UnauthorizedError({ name: "ProxyTokenRejected", message: "Agent Vault proxy token has been revoked" });+ }- const login = await resourceAuthMethodService.loginWithToken({- token: enrollmentToken,- expectedResourceType: RESOURCE_TYPE_AGENT_VAULT_PROXY- });+ const servedCa = servedCaCertificate ? parseRootCaCertificate(servedCaCertificate) : null;+ const infisicalCa = servedCa ? null : await $getOrCreateRootCa(proxy);+ const reported = servedCa ?? parseRootCaCertificate((infisicalCa as { rootCa: TProxyRootCa }).rootCa.certificate);- 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" });+ // Tied to the checked version, so a start whose token was rotated in between can't overwrite the rotation.+ if (!infisicalCa?.recorded && proxy.rootCaFingerprint !== reported.fingerprint) {+ const [recorded] = await agentVaultProxyDAL.update(+ { id: proxy.id, tokenVersion },+ { rootCaFingerprint: reported.fingerprint, rootCaExpiresAt: reported.expiresAt }+ );+ if (!recorded) {+ throw new UnauthorizedError({+ name: "ProxyTokenRejected",+ message: "Agent Vault proxy token has been revoked"+ });+ }+ }- 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)- };+ return { proxyId: proxy.id, name: proxy.name, config: toConfig(proxy), rootCa: infisicalCa?.rootCa };};const heartbeat = async ({ proxyId }: THeartbeatDTO) => {@@ -607,11 +694,11 @@ export const agentVaultProxyServiceFactory = ({getProxyForAuth,listProxies,createProxy,- reissueEnrollmentToken,+ rotateProxyToken,updateProxy,deleteProxy,revokeProxyAccess,- enroll,+ bootstrap,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.tsindex ed74325f31..8c4a2a4073 100644--- 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@@ -35,9 +35,15 @@ export type TUpdateProxyDTO = TAgentVaultProxyScoped & {export type TProxyByIdDTO = TAgentVaultProxyScoped & { proxyId: string };-export type TEnrollProxyDTO = {- enrollmentToken: string;- rootCaCertificate: string;+export type TBootstrapProxyDTO = {+ proxyId: string;+ tokenVersion: number;+ servedCaCertificate?: string;+};++export type TProxyRootCa = {+ certificate: string;+ privateKey: string;};export type THeartbeatDTO = {diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 1dcce497af..bc6d5847cb 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -13,7 +13,7 @@ never in anything the agent holds.| **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 |+| **Proxy** | One egress identity and its CA. Any number of processes can run it from its proxy token |```agent-vault/ shared: enums, host grammar, conflict detection, reachability@@ -22,7 +22,7 @@ agent-vault-variable/ product-wide variables and the reads behind Used Byagent-vault-member/ product membership (list, add, role, remove)agent-vault-session/ mint, revoke, list, getagent-vault-project/ the per-org project's lazy bootstrap and resolver-agent-vault-proxy/ login (enrollment), heartbeat, resolve+agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolveagent-vault-session-log/ storage settings, chunk ingest, playback```@@ -110,18 +110,27 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-## 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`.+- There is no enrollment. Create and rotate return a proxy token (the non-expiring access JWT) and every proxy+ process starts from it, loading its settings and CA from `POST /proxy/bootstrap`. Create and rotate each write+ `tokenVersion` and the new CA in one statement, so no response ever pairs a token with the wrong CA. Proxies+ enrolled before enrollment was removed keep running from their saved state on disk; the CLI's read-only+ support for that is due to be removed after 2026-12-21.+- Infisical generates and keeps each proxy's CA (cert in plain text, key sealed with the project data key) at+ create and on every rotation, and fills one in at bootstrap for a proxy enrolled before that, with+ `storeRootCaIfMissing` deciding races. A proxy serving its own CA (`--ca-cert`) reports it at bootstrap and is+ sent none; the stored CA is kept for processes that don't bring one, and the row shows whichever CA the latest+ start reported. Create and rotate record the new CA's fingerprint so it can be pinned before+ anything starts, and bootstrap's fingerprint write is tied to the token version it checked, so a start on a+ rotated token can't overwrite it.+- Agents still fetch the CA from the proxy's own unauthenticated `/_agent-vault/ca`, so the agent's trust path+ has no dependency on Infisical. There is deliberately no admin download endpoint for the CA.- Health is judged against `heartbeatTTL`, the interval the proxy was running when it last checked in, notthe row's current `pollInterval`. A proxy learns a new interval on its next poll, so comparing against thesaved 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.+- The proxy 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; rotating brings a revoked proxy back.+- Resolve is not audited: once per poll per session would swamp the audit table. Bootstrap is not audited+ either, since a proxy run as a sidecar starts once per agent run.## Host and path grammardiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 06b50206d7..e2698c99a6 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -830,6 +830,7 @@ export enum EventType {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_TOKEN_ROTATE = "agent-vault-proxy-token-rotate",AGENT_VAULT_PROXY_ENROLL = "agent-vault-proxy-enroll",AGENT_VAULT_PROXY_UPDATE = "agent-vault-proxy-update",AGENT_VAULT_PROXY_REVOKE = "agent-vault-proxy-revoke",@@ -6444,6 +6445,14 @@ interface AgentVaultProxyTokenReissueEvent {};}+interface AgentVaultProxyTokenRotateEvent {+ type: EventType.AGENT_VAULT_PROXY_TOKEN_ROTATE;+ metadata: {+ proxyId: string;+ name: string;+ };+}+interface AgentVaultProxyEnrollEvent {type: EventType.AGENT_VAULT_PROXY_ENROLL;metadata: {@@ -8620,6 +8629,7 @@ export type Event =| AgentVaultSessionRevokeEvent| AgentVaultProxyRegisterEvent| AgentVaultProxyTokenReissueEvent+ | AgentVaultProxyTokenRotateEvent| AgentVaultProxyEnrollEvent| AgentVaultProxyUpdateEvent| AgentVaultProxyRevokeEventdiff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex b6f691916a..e737af736f 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4621,9 +4621,14 @@ export const AGENT_VAULT = {offset: "How many proxies to skip.",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.",+ proxyToken:+ "The token the proxy starts with, on as many machines as you need. Shown once, and works until it is rotated or the proxy's access is revoked.",+ rootCa:+ "The certificate authority Infisical keeps for this proxy: a PEM certificate and its PKCS#8 PEM private key.",+ rootCaCertificatePem: "The certificate authority's certificate, in PEM form.",+ rootCaPrivateKey: "The certificate authority's private key, in PKCS#8 PEM form.",+ servedCaCertificate:+ "The certificate authority the proxy serves, in PEM form, when it uses its own instead of Infisical's. Infisical records its fingerprint and returns no `rootCa`.",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.",diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.tsindex c52daf13d8..e3222f206e 100644--- a/backend/src/server/config/rateLimiter.ts+++ b/backend/src/server/config/rateLimiter.ts@@ -117,6 +117,18 @@ export const agentVaultSessionLogChunkLimit: RateLimitOptions = {}};+// Called once per proxy start, and per-sandbox sidecars start often from egress addresses shared with other+// tenants, so this keys on the proxy like the other proxy routes rather than on the IP writeLimit uses.+export const agentVaultBootstrapLimit: RateLimitOptions = {+ timeWindow: 60 * 1000,+ hook: "preValidation",+ max: (req) => req.rateLimits.writeLimit,+ keyGenerator: (req) => {+ const actorId = (req as { permission?: { id?: string } }).permission?.id;+ return actorId ? `agent-vault-bootstrap:${actorId}` : req.realIp;+ }+};+export const agentVaultHeartbeatLimit: RateLimitOptions = {timeWindow: 60 * 1000,hook: "preValidation",diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex ebaed789f4..3fb5ab6357 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -336,8 +336,7 @@ export enum PostHogEventTypes {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",+ AgentVaultProxyTokenRotated = "Agent Vault Proxy Token Rotated",AgentVaultProductMemberAdded = "Agent Vault Product Member Added",AgentVaultProductMemberUpdated = "Agent Vault Product Member Updated",AgentVaultProductMemberRemoved = "Agent Vault Product Member Removed",@@ -2574,21 +2573,11 @@ export type TAgentVaultProxyAccessRevokedEvent = {properties: TAgentVaultEventBase & { proxyId: string };};-export type TAgentVaultProxyEnrollmentTokenReissuedEvent = {- event: PostHogEventTypes.AgentVaultProxyEnrollmentTokenReissued;+export type TAgentVaultProxyTokenRotatedEvent = {+ event: PostHogEventTypes.AgentVaultProxyTokenRotated;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: AgentVaultMemberType; role: string };@@ -2623,13 +2612,12 @@ export type TAgentVaultPostHogEvent =| TAgentVaultProxyUpdatedEvent| TAgentVaultProxyDeletedEvent| TAgentVaultProxyAccessRevokedEvent- | TAgentVaultProxyEnrollmentTokenReissuedEvent- | TAgentVaultProxyEnrolledEvent+ | TAgentVaultProxyTokenRotatedEvent| TAgentVaultProductMemberAddedEvent| TAgentVaultProductMemberUpdatedEvent| TAgentVaultProductMemberRemovedEvent;-export type TAgentVaultActorPostHogEvent = Exclude<TAgentVaultPostHogEvent, TAgentVaultProxyEnrolledEvent>;+export type TAgentVaultActorPostHogEvent = TAgentVaultPostHogEvent;// A trial is burned per PRODUCT, not per (product, plan): the trial-history gate discards plan_key// (see licenseV2Service.getOverview), and the license server 409s a repeat. So TrialStarted fires atdiff --git a/docs/api-reference/endpoints/agent-vault-proxies/enrollment-token.mdx b/docs/api-reference/endpoints/agent-vault-proxies/rotate-token.mdxsimilarity index 58%rename from docs/api-reference/endpoints/agent-vault-proxies/enrollment-token.mdxrename to docs/api-reference/endpoints/agent-vault-proxies/rotate-token.mdxindex 3adf747645..11655b1931 100644--- a/docs/api-reference/endpoints/agent-vault-proxies/enrollment-token.mdx+++ b/docs/api-reference/endpoints/agent-vault-proxies/rotate-token.mdx@@ -1,4 +1,4 @@----title: "Reissue enrollment token"-openapi: "POST /api/v1/agent-vault/proxies/{proxyId}/token-auth/enrollment-token"+title: "Rotate proxy token"+openapi: "POST /api/v1/agent-vault/proxies/{proxyId}/token-auth/proxy-token"---diff --git a/docs/cli/reference.mdx b/docs/cli/reference.mdxindex eed5381d2c..e3fc686441 100644--- a/docs/cli/reference.mdx+++ b/docs/cli/reference.mdx@@ -184,22 +184,24 @@ Run [Agent Vault](/documentation/platform/agent-vault/overview), which lets AI acommand="agent-vault proxy"usage="[flags]"flags={[- { name: "--data-dir", value: "<string>", type: "string", description: "The directory that holds the proxy's certificate authority, access token, and last settings. It must persist across restarts. Defaults to `~/.infisical/agent-vault`, or `/etc/infisical/agent-vault` when run as root. Can also be set with `INFISICAL_AGENT_VAULT_DATA_DIR`." },- { name: "--enrollment-token", value: "<string>", type: "string", description: "The one-time token shown when the proxy was created in Infisical. Needed on the first run and to re-enroll. Can also be set with `INFISICAL_AGENT_VAULT_ENROLLMENT_TOKEN`, which keeps it off the command line." },+ { name: "--ca-cert", value: "<string>", type: "string", description: "Your own certificate authority to serve instead of the one Infisical generates, as PEM text, PEM encoded as base64, or the path to a PEM file. Pass it with `--ca-key`. Can also be set with `INFISICAL_AGENT_VAULT_CA_CERT`." },+ { name: "--ca-key", value: "<string>", type: "string", description: "The ECDSA P-256 private key for `--ca-cert`, in the same formats. Can also be set with `INFISICAL_AGENT_VAULT_CA_KEY`, which keeps the key off the command line." },+ { name: "--data-dir", value: "<string>", type: "string", description: "The directory where the proxy keeps a cache of its settings and certificate authority, if the directory is writable. The proxy starts from the cache if it can't reach Infisical. Defaults to `~/.infisical/agent-vault`, or `/etc/infisical/agent-vault` when run as root. Can also be set with `INFISICAL_AGENT_VAULT_DATA_DIR`." },{ name: "--log-file", value: "<string>", type: "string", description: "A file to also write logs to, as JSON lines. The file is appended to." },{ name: "--log-format", value: "<string>", type: "string", default: "console", description: "The format of the logs written to stderr: `console` or `json`." },- { name: "--port", value: "<int>", type: "int", default: "17323", description: "The port to listen on, on all interfaces. `0` picks any free port, which the startup line reports." },+ { name: "--port", value: "<int>", type: "int", default: "17323", description: "The port to listen on, on all interfaces. `0` picks any free port, which the startup line reports. Can also be set with `INFISICAL_AGENT_VAULT_PORT`." },+ { name: "--proxy-token", value: "<string>", type: "string", description: "The proxy token, which Infisical shows once when you create the proxy or rotate its token. Can also be set with `INFISICAL_AGENT_VAULT_PROXY_TOKEN`, which keeps it off the command line." },]}examples={[- { title: "Enroll a new proxy", code: "infisical agent-vault proxy --enrollment-token=<enrollment-token>" },- { title: "Start an enrolled proxy", code: "infisical agent-vault proxy" },- { title: "Log JSON to a file on a custom port", code: "infisical agent-vault proxy --port=18000 --log-format=json --log-file=/var/log/infisical/agent-vault.log" },+ { title: "Start a proxy", code: "INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> infisical agent-vault proxy" },+ { title: "Serve your own certificate authority", code: "INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> infisical agent-vault proxy --ca-cert=./ca.crt --ca-key=./ca.key" },+ { title: "Log JSON to a file on a custom port", code: "INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> infisical agent-vault proxy --port=18000 --log-format=json --log-file=/var/log/infisical/agent-vault.log" },]}>Run an Agent Vault [proxy](/documentation/platform/agent-vault/proxies) in the foreground. For each request, the proxy decides whether the agent's session allows the host and attaches the real credential on the way out, so the agent never holds a secret.-Enroll once with `--enrollment-token`. The proxy saves its certificate authority and access token to `--data-dir`, so later starts need no token. Passing the same token again resumes the existing enrollment. A different token enrolls the proxy again and replaces its certificate authority, so agents that trusted the old one stop trusting the proxy.+Start the proxy with its proxy token. You can run the proxy on as many machines as you need with the same token. Each time the proxy starts, it loads its settings and certificate authority from Infisical. If it can't reach Infisical, it retries for 60 seconds, then starts from the cache in `--data-dir` if there is one, or exits.You set the proxy's traffic policy, exceptions, and poll interval in Infisical, not with flags.diff --git a/docs/docs.json b/docs/docs.jsonindex bc0ac75d2d..65b701af60 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -4535,7 +4535,7 @@"api-reference/endpoints/agent-vault-proxies/create","api-reference/endpoints/agent-vault-proxies/update","api-reference/endpoints/agent-vault-proxies/delete",- "api-reference/endpoints/agent-vault-proxies/enrollment-token",+ "api-reference/endpoints/agent-vault-proxies/rotate-token","api-reference/endpoints/agent-vault-proxies/revoke"]},@@ -4934,6 +4934,10 @@}},"redirects": [+ {+ "source": "/api-reference/endpoints/agent-vault-proxies/enrollment-token",+ "destination": "/api-reference/endpoints/agent-vault-proxies/rotate-token"+ },{"source": "/documentation/platform/secret-scanning/usage","destination": "/documentation/platform/secret-scanning/scan-repositories"diff --git a/docs/documentation/platform/agent-vault/guides/custom-agent.mdx b/docs/documentation/platform/agent-vault/guides/custom-agent.mdxindex c41730807b..a42928c5bd 100644--- a/docs/documentation/platform/agent-vault/guides/custom-agent.mdx+++ b/docs/documentation/platform/agent-vault/guides/custom-agent.mdx@@ -47,9 +47,9 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bund</Step></Steps>-### Enroll a proxy+### Create a proxy-Next, enroll a proxy. Every request your agent makes goes through the proxy, which attaches the real credential from the access bundle before forwarding the request to the API.+Next, create a proxy. Every request your agent makes goes through the proxy, which attaches the real credential from the access bundle before forwarding the request to the API.<Steps><Step>@@ -59,7 +59,7 @@ Next, enroll a proxy. Every request your agent makes goes through the proxy, whiGive the proxy a **Name**, then select **Create**.</Step><Step>- In the **Enrollment Token** dialog, copy the command from the **CLI** tab, or from the **Docker** or **systemd** tab to keep the proxy running after you close the terminal. The enrollment token expires in an hour.+ In the **Proxy Token** dialog, copy the command from the **CLI** tab, or from the **Docker** or **Kubernetes** tab to keep the proxy running after you close the terminal. The dialog shows the proxy token only once.</Step><Step>Run the command on the machine that will run the proxy.@@ -104,7 +104,7 @@ openssl x509 -in ca.pem -noout -fingerprint -sha256Compare the colon-separated value with the proxy's fingerprint on the **Proxies** page in Agent Vault. The **Certificate Authority** column shows the start of the fingerprint, and hovering over it shows the full value. If the values don't match, don't use the file.-Store `ca.pem` where the agent can read it. The certificate isn't secret, so you can add it to the agent's container image. If you [re-enroll the proxy](/documentation/platform/agent-vault/proxies#re-enroll-a-proxy), download the certificate again.+Store `ca.pem` where the agent can read it. The certificate isn't secret, so you can add it to the agent's container image. If you [rotate the proxy's token](/documentation/platform/agent-vault/proxies#rotate-a-proxys-token), download the certificate again.## Step 3: Replace the API keys with placeholders@@ -253,7 +253,7 @@ To replace sessions automatically, such as for a process that runs for days, [crThe request reached the API without the real credential. Check that a service in the session's access bundle covers the host, and that the service's credential is correct. If the service uses a substitution, check that the agent sends the exact placeholder in **Replace**.</Accordion><Accordion title="Requests fail with a certificate error">- The agent doesn't trust the proxy's certificate. Check that the client loads `ca.pem`, and download the certificate again if you re-enrolled the proxy.+ The agent doesn't trust the proxy's certificate. Check that the client loads `ca.pem`, and download the certificate again if you rotated the proxy's token.</Accordion><Accordion title="Requests reach the API without the proxy">If the API rejects the placeholder key and the request doesn't appear in the session logs, the agent's requests skip the proxy. Check that the host isn't in `NO_PROXY`, and that the HTTP client reads the proxy setting:diff --git a/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx b/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdxindex 6ad997ac36..2484c9de4d 100644--- a/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx+++ b/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx@@ -126,9 +126,9 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bund</Step></Steps>-### Enroll a proxy+### Create a proxy-Next, enroll a [proxy](/documentation/platform/agent-vault/proxies) on the Agent Vault machine. Every request Hermes makes will go through this proxy first. The proxy gets the real credential from the access bundle you just created. It attaches the credential to the request, then forwards the request to the API.+Next, create a [proxy](/documentation/platform/agent-vault/proxies) on the Agent Vault machine. Every request Hermes makes will go through this proxy first. The proxy gets the real credential from the access bundle you just created. It attaches the credential to the request, then forwards the request to the API.<Steps><Step>@@ -145,7 +145,7 @@ Next, enroll a [proxy](/documentation/platform/agent-vault/proxies) on the AgentSelect **Create**.</Step><Step>- In the **Enrollment Token** dialog, open the **systemd** or **Docker** tab and copy what it shows. The enrollment token expires in an hour.+ Store the proxy token from the **Proxy Token** dialog somewhere safe. The dialog shows the token only once.</Step></Steps>@@ -153,7 +153,30 @@ The gateway runs all the time, so run the proxy as a service that starts again w<Tabs><Tab title="systemd">- Save the unit from the dialog as `/etc/systemd/system/agent-vault-proxy.service`, then enable and start the proxy:+ Save the proxy token in `/etc/infisical/agent-vault-proxy.env`:++ ```bash+ INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token>+ ```++ Run `sudo chmod 600 /etc/infisical/agent-vault-proxy.env` so that only root can read the file. Then save this unit as `/etc/systemd/system/agent-vault-proxy.service`, replacing `<your-instance-url>` with your Infisical instance URL:++ ```ini+ [Unit]+ Description=Infisical Agent Vault proxy+ After=network-online.target+ Wants=network-online.target++ [Service]+ EnvironmentFile=/etc/infisical/agent-vault-proxy.env+ ExecStart=/usr/local/bin/infisical agent-vault proxy --domain <your-instance-url>+ Restart=always++ [Install]+ WantedBy=multi-user.target+ ```++ Enable and start the proxy:```bashsudo systemctl daemon-reload@@ -163,18 +186,18 @@ The gateway runs all the time, so run the proxy as a service that starts again w`enable` starts the proxy every time the machine boots, and `--now` also starts it right away.</Tab><Tab title="Docker">- Add `--restart unless-stopped` after `docker run -d` in the command from the dialog, then run the command. For example:+ Run the following command, replacing `<proxy-token>` with the proxy token and `<your-instance-url>` with your Infisical instance URL:```bashdocker run -d --restart unless-stopped --name agent-vault-proxy \-p 17323:17323 \-v agent-vault-proxy:/etc/infisical/agent-vault \+ -e INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \infisical/cli agent-vault proxy \- --enrollment-token <enrollment-token> \--domain <your-instance-url>```- With `--restart unless-stopped`, Docker starts the proxy again whenever Docker itself starts, unless you stopped the container yourself. Docker must also start at boot, which you can turn on with `sudo systemctl enable docker` on most Linux machines.+ With `--restart unless-stopped`, Docker starts the proxy again whenever Docker itself starts, unless you stopped the container yourself. Docker must also start at boot, which you can turn on with `sudo systemctl enable docker` on most Linux machines. The volume keeps the proxy's [cache](/documentation/platform/agent-vault/proxies#command-flags), so the proxy can start after a reboot even if Infisical is unreachable.</Tab></Tabs>@@ -186,7 +209,7 @@ The proxy listens on port `17323`. Make sure the Hermes machine can reach that p### Create a session-Finally, create a [session](/documentation/platform/agent-vault/sessions) for the gateway. This will generate a token that Hermes can use to make authenticated requests via the proxy you enrolled.+Finally, create a [session](/documentation/platform/agent-vault/sessions) for the gateway. This will generate a token that Hermes can use to make authenticated requests through the proxy you created.<Steps><Step>@@ -329,7 +352,7 @@ Hermes writes the gateway's logs to `~/.hermes/logs/gateway.log`. On Linux, you<AccordionGroup><Accordion title="The proxy's systemd service fails to start">- If `sudo systemctl status agent-vault-proxy` shows `status=203/EXEC`, systemd couldn't find the Infisical CLI. The unit from the enrollment dialog starts the proxy with `/usr/local/bin/infisical`, but your CLI may be installed somewhere else.+ If `sudo systemctl status agent-vault-proxy` shows `status=203/EXEC`, systemd couldn't find the Infisical CLI. The [unit](#create-a-proxy) starts the proxy with `/usr/local/bin/infisical`, but your CLI may be installed somewhere else.Run `which infisical` to find your CLI's path. In `/etc/systemd/system/agent-vault-proxy.service`, replace `/usr/local/bin/infisical` at the start of the `ExecStart=` line with that path, then reload and restart the proxy:diff --git a/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx b/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdxindex f7f7c42062..72df89b8f4 100644--- a/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx+++ b/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx@@ -120,9 +120,9 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bund</Step></Steps>-### Enroll a proxy+### Create a proxy-Next, enroll a [proxy](/documentation/platform/agent-vault/proxies) on the Agent Vault machine. Every request OpenClaw makes will go through this proxy first. The proxy gets the real credential from the access bundle you just created. It attaches the credential to the request, then forwards the request to the API.+Next, create a [proxy](/documentation/platform/agent-vault/proxies) on the Agent Vault machine. Every request OpenClaw makes will go through this proxy first. The proxy gets the real credential from the access bundle you just created. It attaches the credential to the request, then forwards the request to the API.<Steps><Step>@@ -139,7 +139,7 @@ Next, enroll a [proxy](/documentation/platform/agent-vault/proxies) on the AgentSelect **Create**.</Step><Step>- In the **Enrollment Token** dialog, open the **systemd** or **Docker** tab and copy what it shows. The enrollment token expires in an hour.+ Store the proxy token from the **Proxy Token** dialog somewhere safe. The dialog shows the token only once.</Step></Steps>@@ -147,7 +147,30 @@ The gateway runs all the time, so run the proxy as a service that starts again w<Tabs><Tab title="systemd">- Save the unit from the dialog as `/etc/systemd/system/agent-vault-proxy.service`, then enable and start the proxy:+ Save the proxy token in `/etc/infisical/agent-vault-proxy.env`:++ ```bash+ INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token>+ ```++ Run `sudo chmod 600 /etc/infisical/agent-vault-proxy.env` so that only root can read the file. Then save this unit as `/etc/systemd/system/agent-vault-proxy.service`, replacing `<your-instance-url>` with your Infisical instance URL:++ ```ini+ [Unit]+ Description=Infisical Agent Vault proxy+ After=network-online.target+ Wants=network-online.target++ [Service]+ EnvironmentFile=/etc/infisical/agent-vault-proxy.env+ ExecStart=/usr/local/bin/infisical agent-vault proxy --domain <your-instance-url>+ Restart=always++ [Install]+ WantedBy=multi-user.target+ ```++ Enable and start the proxy:```bashsudo systemctl daemon-reload@@ -157,18 +180,18 @@ The gateway runs all the time, so run the proxy as a service that starts again w`enable` starts the proxy every time the machine boots, and `--now` also starts it right away.</Tab><Tab title="Docker">- In the command from the dialog, add `--restart unless-stopped` after `docker run -d`, and change `-p 17323:17323` to `-p <private-ip>:17323:17323`, replacing `<private-ip>` with the Agent Vault machine's private address. Then run the command. For example:+ Run the following command, replacing `<private-ip>` with the Agent Vault machine's private address, `<proxy-token>` with the proxy token, and `<your-instance-url>` with your Infisical instance URL:```bashdocker run -d --restart unless-stopped --name agent-vault-proxy \-p <private-ip>:17323:17323 \-v agent-vault-proxy:/etc/infisical/agent-vault \+ -e INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \infisical/cli agent-vault proxy \- --enrollment-token <enrollment-token> \--domain <your-instance-url>```- With `--restart unless-stopped`, Docker starts the proxy again whenever Docker itself starts, unless you stopped the container yourself. Docker must also start at boot, which you can turn on with `sudo systemctl enable docker` on most Linux machines. Publishing the port on the private address keeps the proxy off any public network interface the machine has.+ With `--restart unless-stopped`, Docker starts the proxy again whenever Docker itself starts, unless you stopped the container yourself. Docker must also start at boot, which you can turn on with `sudo systemctl enable docker` on most Linux machines. The volume keeps the proxy's [cache](/documentation/platform/agent-vault/proxies#command-flags), so the proxy can start after a reboot even if Infisical is unreachable. Publishing the port on the private address keeps the proxy off any public network interface the machine has.</Tab></Tabs>@@ -180,7 +203,7 @@ The proxy listens on port `17323`. Make sure the OpenClaw machine can reach that### Create a session-Finally, create a [session](/documentation/platform/agent-vault/sessions) for the gateway. This will generate a token that OpenClaw can use to make authenticated requests via the proxy you enrolled.+Finally, create a [session](/documentation/platform/agent-vault/sessions) for the gateway. This will generate a token that OpenClaw can use to make authenticated requests through the proxy you created.<Steps><Step>@@ -345,7 +368,7 @@ To follow the gateway's logs, run `openclaw logs --follow`. To check the gateway<AccordionGroup><Accordion title="The proxy's systemd service fails to start">- If `sudo systemctl status agent-vault-proxy` shows `status=203/EXEC`, systemd couldn't find the Infisical CLI. The unit from the enrollment dialog starts the proxy with `/usr/local/bin/infisical`, but your CLI may be installed somewhere else.+ If `sudo systemctl status agent-vault-proxy` shows `status=203/EXEC`, systemd couldn't find the Infisical CLI. The [unit](#create-a-proxy) starts the proxy with `/usr/local/bin/infisical`, but your CLI may be installed somewhere else.Run `which infisical` to find your CLI's path. In `/etc/systemd/system/agent-vault-proxy.service`, replace `/usr/local/bin/infisical` at the start of the `ExecStart=` line with that path, then reload and restart the proxy:diff --git a/docs/documentation/platform/agent-vault/plan-your-setup.mdx b/docs/documentation/platform/agent-vault/plan-your-setup.mdxindex 48afd1d436..c2f0174d91 100644--- a/docs/documentation/platform/agent-vault/plan-your-setup.mdx+++ b/docs/documentation/platform/agent-vault/plan-your-setup.mdx@@ -144,7 +144,7 @@ Configure the following options to get custom guidance and best practices tailor<li>If you don't have a second machine, a small VM on your network can run the proxy</li></AgentVaultSetupBranch><AgentVaultSetupBranch runs="container">- <li>The agents' containers don't have access to the proxy's state directory</li>+ <li>The agents' containers can't read the proxy token</li></AgentVaultSetupBranch><AgentVaultSetupBranch runs="ci"><li>The CI runner has to reach the proxy, so if the proxy is on a private network, the job runs on a [self-hosted runner](https://docs.github.com/en/actions/hosting-your-own-runners) in that network</li>@@ -152,7 +152,7 @@ Configure the following options to get custom guidance and best practices tailor</ul><Note>- The proxy [runs on a different machine](/documentation/platform/agent-vault/proxies#choose-where-to-run-the-proxy) from the agent, on the same private network. If the proxy ran on the agent's machine, the agent could read the proxy's [state directory](/documentation/platform/agent-vault/proxies#state-directory), which holds the proxy's access token.+ The proxy [runs on a different machine](/documentation/platform/agent-vault/proxies#choose-where-to-run-the-proxy) from the agent, on the same private network. If the proxy ran on the agent's machine, the agent could read the proxy token.</Note></AgentVaultSetupStep>@@ -186,22 +186,22 @@ Follow these pages in order:<ol><AgentVaultSetupBranch building="personal,assistant" agent="none">- <li>[Quickstart](/documentation/platform/agent-vault/quickstart): create an access bundle, enroll a proxy, create a session, and start your agent with the session token</li>+ <li>[Quickstart](/documentation/platform/agent-vault/quickstart): create an access bundle, create a proxy, create a session, and start your agent with the session token</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="personal,assistant" agent="claude-code">- <li>[Agent Vault with Claude Code](/documentation/platform/agent-vault/guides/claude-code): create an access bundle, enroll a proxy, create a session, and start Claude Code with the session token</li>+ <li>[Agent Vault with Claude Code](/documentation/platform/agent-vault/guides/claude-code): create an access bundle, create a proxy, create a session, and start Claude Code with the session token</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="personal,assistant" agent="codex">- <li>[Agent Vault with Codex](/documentation/platform/agent-vault/guides/codex): create an access bundle, enroll a proxy, create a session, and start Codex with the session token</li>+ <li>[Agent Vault with Codex](/documentation/platform/agent-vault/guides/codex): create an access bundle, create a proxy, create a session, and start Codex with the session token</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="personal,assistant" agent="opencode">- <li>[Agent Vault with OpenCode](/documentation/platform/agent-vault/guides/opencode): create an access bundle, enroll a proxy, create a session, and start OpenCode with the session token</li>+ <li>[Agent Vault with OpenCode](/documentation/platform/agent-vault/guides/opencode): create an access bundle, create a proxy, create a session, and start OpenCode with the session token</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="personal" agent="hermes">- <li>[Agent Vault with Hermes Agent](/documentation/platform/agent-vault/guides/hermes): create an access bundle, enroll a proxy, create a session, and start Hermes in your terminal with the session token</li>+ <li>[Agent Vault with Hermes Agent](/documentation/platform/agent-vault/guides/hermes): create an access bundle, create a proxy, create a session, and start Hermes in your terminal with the session token</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="personal" agent="openclaw">- <li>[Agent Vault with OpenClaw](/documentation/platform/agent-vault/guides/openclaw): create an access bundle, enroll a proxy, create a session, and start OpenClaw in your terminal with the session token</li>+ <li>[Agent Vault with OpenClaw](/documentation/platform/agent-vault/guides/openclaw): create an access bundle, create a proxy, create a session, and start OpenClaw in your terminal with the session token</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="assistant" agent="hermes"><li>[Agent Vault with the Hermes gateway](/documentation/platform/agent-vault/guides/hermes-gateway): create a session that never expires, then send the Hermes gateway's requests through the proxy</li>@@ -210,12 +210,12 @@ Follow these pages in order:<li>[Agent Vault with the OpenClaw gateway](/documentation/platform/agent-vault/guides/openclaw-gateway): create a session that never expires, then send the OpenClaw gateway's requests through the proxy</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="personal,assistant" agent="custom">- <li>[Connect your own agent](/documentation/platform/agent-vault/guides/custom-agent): create an access bundle, enroll a proxy, create a session, and send your agent's requests through the proxy</li>+ <li>[Connect your own agent](/documentation/platform/agent-vault/guides/custom-agent): create an access bundle, create a proxy, create a session, and send your agent's requests through the proxy</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="scheduled,platform"><li>[Create an access bundle](/documentation/platform/agent-vault/access-bundles#create-an-access-bundle), with a service for each API the agent calls</li>- <li>[Enroll a proxy](/documentation/platform/agent-vault/proxies#create-and-enroll-a-proxy), and run it with Docker or systemd so that it keeps running between jobs</li>+ <li>[Create a proxy](/documentation/platform/agent-vault/proxies#create-a-proxy-and-start-it), and run it with Docker, Kubernetes, or systemd so that it keeps running between jobs</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="scheduled" runs="none,computer,server"><li>[Create sessions with the CLI](/documentation/platform/agent-vault/sessions-cli): set up a machine identity, then run the agent from cron or systemd</li>diff --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdxindex f57616b99a..cf20f42b8f 100644--- a/docs/documentation/platform/agent-vault/proxies.mdx+++ b/docs/documentation/platform/agent-vault/proxies.mdx@@ -3,13 +3,13 @@ title: "Proxies"description: "Run the proxy that attaches credentials, set its traffic policy, and understand how agents trust it."----A proxy intercepts your agents' requests to the APIs they call, then attaches the necessary API credential to each request that matches a [service](/documentation/platform/agent-vault/services). Run the proxy where agent traffic leaves your network, either on its own host that several agents share, or on the same machine as one agent.+A proxy intercepts your agents' requests to the APIs they call, then attaches the necessary API credential to each request that matches a [service](/documentation/platform/agent-vault/services). Run the proxy where agent traffic leaves your network, either on its own host that several agents share, or next to each agent, such as in a sidecar container.-You create a proxy in Infisical, enroll it once from the CLI, and change its settings in Infisical afterwards.+You create a proxy in Infisical, start it with the proxy token that Infisical shows you, and change its settings in Infisical afterwards. You can run the same proxy on as many machines as you need with one token, such as several machines behind a [load balancer](#high-availability).## Choose where to run the proxy-While you can technically run the agent and the proxy on a single machine, we recommend running the proxy on a different machine from the agent. If the agent and the proxy run on the same machine, the agent could read the proxy's [state directory](#state-directory), which contains sensitive values like the proxy's access token and the private key of its certificate authority.+While you can technically run the agent and the proxy on a single machine, we recommend running the proxy on a different machine from the agent. If the agent and the proxy run on the same machine, the agent could read the proxy token and the private key of the proxy's certificate authority.<Tip>We also recommend keeping both machines on the same private network. This is because every request the agent makes goes through the proxy, and a round trip between networks adds latency to every request.@@ -24,28 +24,24 @@ The proxy attaches credentials to HTTP/1.1 requests, over both HTTPS and plain HIf an API offers both, configure the agent to use its plain HTTPS requests. Many SDKs fall back to HTTPS when a WebSocket connection fails.-## Create and enroll a proxy+## Create a proxy and start it<Steps><Step>In Agent Vault, go to **Proxies** and select **Create Proxy**.</Step><Step>- Enter a **Name**. To set the [traffic policy](#traffic-policy), [exceptions](#exceptions), or [poll interval](#poll-interval) now, expand **Advanced Options**. You can change them later.+ Enter a **Name**. To set the [traffic policy](#traffic-policy), [exceptions](#exceptions), or [poll interval](#poll-interval) now, expand **Advanced Options**. You can change these settings later.<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></Step><Step>- Select **Create**. The **Enrollment Token** dialog shows a one-time token that expires in an hour, and commands for the CLI, Docker, and systemd with your token and instance filled in.-- <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>+ Select **Create**. The **Proxy Token** dialog shows the proxy token, and commands for the CLI, systemd, Docker, and Kubernetes with your token and instance filled in.</Step><Step>- Run one of the commands on the machine where the proxy will run.+ Run one of the commands on each machine where the proxy will run.</Step></Steps>@@ -54,8 +50,8 @@ The commands look like this:<Tabs><Tab title="CLI">```bash+ INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \infisical agent-vault proxy \- --enrollment-token <enrollment-token> \--domain <your-instance-url>```</Tab>@@ -64,58 +60,102 @@ The commands look like this:docker run -d --name agent-vault-proxy \-p 17323:17323 \-v agent-vault-proxy:/etc/infisical/agent-vault \+ -e INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \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.+ The volume keeps the proxy's [cache](#command-flags), so the proxy can start even if Infisical is unreachable.+ </Tab>+ <Tab title="Kubernetes">+ ```yaml expandable+ apiVersion: v1+ kind: Secret+ metadata:+ name: agent-vault-proxy+ type: Opaque+ stringData:+ INFISICAL_AGENT_VAULT_PROXY_TOKEN: <proxy-token>+ ---+ apiVersion: apps/v1+ kind: Deployment+ metadata:+ name: agent-vault-proxy+ spec:+ replicas: 2+ selector:+ matchLabels:+ app: agent-vault-proxy+ template:+ metadata:+ labels:+ app: agent-vault-proxy+ spec:+ containers:+ - name: agent-vault-proxy+ image: infisical/cli+ args: ["agent-vault", "proxy", "--domain", "<your-instance-url>"]+ envFrom:+ - secretRef:+ name: agent-vault-proxy+ ports:+ - containerPort: 17323+ ---+ apiVersion: v1+ kind: Service+ metadata:+ name: agent-vault-proxy+ spec:+ selector:+ app: agent-vault-proxy+ ports:+ - port: 17323+ targetPort: 17323+ ```++ The manifest in the dialog has no Service. Add the Service from the end of this example so that agents in the cluster can reach the proxy at `agent-vault-proxy:17323`.</Tab><Tab title="systemd">+ Save the token in `/etc/infisical/agent-vault-proxy.env`:++ ```bash+ INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token>+ ```++ Run `sudo chmod 600 /etc/infisical/agent-vault-proxy.env` so that only root can read the file. Then save this unit as `/etc/systemd/system/agent-vault-proxy.service`:+```ini[Unit]Description=Infisical Agent Vault proxyAfter=network-online.target+ Wants=network-online.target[Service]- ExecStart=/usr/local/bin/infisical agent-vault proxy --enrollment-token <enrollment-token> --domain <your-instance-url>+ EnvironmentFile=/etc/infisical/agent-vault-proxy.env+ ExecStart=/usr/local/bin/infisical agent-vault proxy --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`.+ Run `sudo systemctl enable --now agent-vault-proxy` to start the proxy now and every time the machine boots.</Tab></Tabs>### Command flags-The enrollment command uses these flags:+The commands use these settings:-- `--enrollment-token` is the one-time token from the **Enrollment Token** dialog. Instead of passing the flag, you can set the token in the `INFISICAL_AGENT_VAULT_ENROLLMENT_TOKEN` environment variable.-- `--domain` is your Infisical instance URL. It defaults to Infisical Cloud (US), so you need it for EU Cloud or a self-hosted instance. If you prefer, you can set the URL in the `INFISICAL_DOMAIN` environment variable instead of passing the flag+- `INFISICAL_AGENT_VAULT_PROXY_TOKEN` or `--proxy-token`: the proxy token (prefer the environment variable, because other users on the machine can read anything on a command line)+- `--domain` or `INFISICAL_DOMAIN`: your Infisical instance URL (required for EU Cloud and self-hosted instances, because the default is Infisical Cloud in the US)-<Note>- Other users on the machine can read anything on a command line. To keep the enrollment token off it, put `INFISICAL_AGENT_VAULT_ENROLLMENT_TOKEN=<enrollment-token>` in a file with mode `0600`, and pass the file with `--env-file` for Docker or `EnvironmentFile=` for systemd. You can delete the file once the proxy has enrolled.-</Note>+Each time the proxy starts, it loads its settings and certificate authority from Infisical and, if it can, saves a copy in its data directory (`~/.infisical/agent-vault`, or `/etc/infisical/agent-vault` as root, or `--data-dir`). If it can't reach Infisical for 60 seconds, it starts from that copy, or exits if there isn't one.<Info>- For the proxy's other flags, such as the port and the state directory, check out the [`agent-vault proxy` CLI reference](/cli/reference#agent-vault-proxy).+ For the proxy's other flags, such as the port and the data directory, check out the [`agent-vault proxy` CLI reference](/cli/reference#agent-vault-proxy).</Info>-### State directory--When the proxy enrolls, it generates its own certificate authority and saves it with its enrollment in a state directory at `~/.infisical/agent-vault` (or `/etc/infisical/agent-vault` if you run the proxy as the root user on the machine).--The enrollment token only works once. After the first run, the proxy reads its enrollment from the state directory, so you can restart the proxy without `--enrollment-token`:--```bash-infisical agent-vault proxy --domain <your-instance-url>-```--If the state directory is empty, the proxy can't start without a new token. Select **New Enrollment Token** on the proxy's menu and [enroll again](#re-enroll-a-proxy).-## SettingsTo change a setting, select **Edit Settings** on the proxy's menu. If the proxy is running, it applies the change within one [poll interval](#poll-interval) (60 seconds by default).@@ -175,7 +215,7 @@ If the proxy can't reach Infisical:## Certificate trust-The proxy decrypts HTTPS traffic to attach the credential, so each agent has to trust the proxy's certificate authority (CA). Each proxy generates its own self-signed CA when it enrolls.+The proxy decrypts HTTPS traffic to attach the credential, so each agent has to trust the proxy's certificate authority (CA). Infisical generates a self-signed CA for each proxy when you create the proxy, and a new one each time you rotate the proxy's token.<Tabs><Tab title="With the CLI">@@ -231,28 +271,67 @@ If the proxy's certificate doesn't match, the CLI stops before starting the agen<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>+### Use your own certificate authority++To serve your own CA instead of the one Infisical generates, pass it to the proxy with `--ca-cert` and `--ca-key`, or with the `INFISICAL_AGENT_VAULT_CA_CERT` and `INFISICAL_AGENT_VAULT_CA_KEY` environment variables. Each value can be the PEM text, the PEM encoded as base64, or the path to a PEM file. The key has to be an ECDSA P-256 key.++```bash+INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \+infisical agent-vault proxy --ca-cert ./ca.crt --ca-key ./ca.key+```++The **Proxies** page shows the fingerprint of the CA that the proxy reported the last time it started. Pass the same CA to every machine that runs this proxy, for example in a [high availability](#high-availability) setup.++Your own CA stays the same when you rotate the proxy's token. To use the CA Infisical generates again, leave out these flags.+### APIs with a private certificate authorityThe proxy checks the certificate of each API it connects to, the way any HTTPS client does. If an API uses a private certificate authority, the machine running the proxy has to trust that authority. The agent's machine doesn't need to trust it.-### Re-enroll a proxy+## Rotate a proxy's token-To re-enroll a proxy, select **New Enrollment Token** on the proxy's menu and run the new command. The proxy keeps its name, settings, and history, but gets a new certificate authority.+Rotate the token if it leaked, or to bring back a proxy whose access you revoked:++<Steps>+ <Step>+ On the **Proxies** page, select **Rotate Proxy Token** on the proxy's menu, then select **Rotate**.+ </Step>+ <Step>+ Store the new token from the **Proxy Token** dialog somewhere safe.+ </Step>+ <Step>+ Restart the proxy with the new token on every machine where it runs.+ </Step>+</Steps>-After you re-enroll a proxy:+The current token will stop working, and the proxy gets a new certificate authority. After you rotate the token:- Restart every agent that uses the proxy, because those agents still trust the old certificate- Update any `--ca-fingerprint` pin-- Replace any mounted copy of the certificate+- Replace any `ca.pem` file you mounted for an agent- On macOS, replace the certificate in your login keychain+If you [use your own certificate authority](#use-your-own-certificate-authority), only the token changes, so your agents don't need these updates.+## Revoke or delete a proxyBoth actions are on the proxy's menu:| Action | What happens ||--------|--------------|-| **Revoke Access** | The proxy's token stops working right away. Every agent using the proxy loses its credentials, and the proxy answers requests with a 503. The proxy process exits after two failed check-ins in a row (one to two [poll intervals](#poll-interval)) |-| **Delete** | Infisical removes the proxy. If the proxy is running, it stops working and exits the same way as a revoked proxy |+| **Revoke Access** | The proxy will stop adding credentials to requests. To bring it back, [rotate its token](#rotate-a-proxys-token) |+| **Delete** | Infisical removes the proxy, and the proxy will stop adding credentials to requests. You can't undo this |++Revoke access if you think a machine running the proxy is compromised.++## High availability++To keep the proxy available when one machine goes down, run it on several machines with the same proxy token and put a load balancer in front of them. Every machine serves the same certificate authority, so agents trust whichever machine they reach.++- **Load balancer type:** use a TCP (layer 4) load balancer, because agents send `CONNECT` requests that most HTTP load balancers don't forward. You don't need sticky sessions+- **Health checks:** send an HTTP `GET` to `/_agent-vault/ca` on each machine, which returns `200` while the proxy is serving+- **Your own certificate authority (optional):** if you want to [use your own](#use-your-own-certificate-authority), pass the same `--ca-cert` and `--ca-key` to every machine++Point agents at the load balancer's address instead of a single machine.-Revoke access if you think the proxy's host is compromised. To bring a revoked proxy back, [re-enroll it](#re-enroll-a-proxy).+On Infisical Cloud, every machine running a proxy shares that proxy's [rate limits](/api-reference/overview/rate-limits).diff --git a/docs/documentation/platform/agent-vault/sessions-cli.mdx b/docs/documentation/platform/agent-vault/sessions-cli.mdxindex a2051b3ab0..4f05426cca 100644--- a/docs/documentation/platform/agent-vault/sessions-cli.mdx+++ b/docs/documentation/platform/agent-vault/sessions-cli.mdx@@ -65,7 +65,7 @@ The CLI downloads the proxy's certificate at the start of each run. If the agentinfisical agent-vault run --access-bundle <access-bundle-name> --ttl 2h --ca-fingerprint <fingerprint> -- <agent-command>```-Copy the fingerprint from the **Certificate Authority** column on the **Proxies** page. If you [re-enroll the proxy](/documentation/platform/agent-vault/proxies#re-enroll-a-proxy), update the fingerprint.+Copy the fingerprint from the **Certificate Authority** column on the **Proxies** page. If you [rotate the proxy's token](/documentation/platform/agent-vault/proxies#rotate-a-proxys-token), update the fingerprint.## Step 3: Run the agent automaticallydiff --git a/docs/documentation/platform/audit-logs.mdx b/docs/documentation/platform/audit-logs.mdxindex 50aa8fae74..a6a9c6e415 100644--- a/docs/documentation/platform/audit-logs.mdx+++ b/docs/documentation/platform/audit-logs.mdx@@ -888,7 +888,7 @@ Here are a few common patterns for filtering audit logs, grouped by product.</Tabs></Accordion><Accordion title="Proxy lifecycle events">- Find every proxy registration, enrollment, and revocation.+ Find every proxy registration, token rotation, and revocation.<Tabs><Tab title="Infisical UI">@@ -898,7 +898,7 @@ Here are a few common patterns for filtering audit logs, grouped by product.</Step><Step>Select **Search audit logs** and add:- - `event`: `agent-vault-proxy-register`, `agent-vault-proxy-enroll`, `agent-vault-proxy-revoke`, `agent-vault-proxy-delete`+ - `event`: `agent-vault-proxy-register`, `agent-vault-proxy-token-rotate`, `agent-vault-proxy-revoke`, `agent-vault-proxy-delete`</Step></Steps></Tab>@@ -906,7 +906,7 @@ Here are a few common patterns for filtering audit logs, grouped by product.```bashcurl -G "https://app.infisical.com/api/v1/organization/audit-logs" \-H "Authorization: Bearer <your-access-token>" \- --data-urlencode "eventType=agent-vault-proxy-register,agent-vault-proxy-enroll,agent-vault-proxy-revoke,agent-vault-proxy-delete"+ --data-urlencode "eventType=agent-vault-proxy-register,agent-vault-proxy-token-rotate,agent-vault-proxy-revoke,agent-vault-proxy-delete"```</Tab></Tabs>diff --git a/docs/snippets/agent-vault/QuickstartBody.mdx b/docs/snippets/agent-vault/QuickstartBody.mdxindex 1e1d725102..55b7908e08 100644--- a/docs/snippets/agent-vault/QuickstartBody.mdx+++ b/docs/snippets/agent-vault/QuickstartBody.mdx@@ -66,34 +66,32 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bundYou can repeat these steps to add as many more services as you like to the access bundle.</Tip>-### Enroll a proxy+### Create a proxy-Next, enroll a [proxy](/documentation/platform/agent-vault/proxies) to intercept API calls from your agent.+Next, create a [proxy](/documentation/platform/agent-vault/proxies) to intercept API calls from your agent.<Steps><Step>Go to **Proxies** and select **Create Proxy**.</Step><Step>- Give the proxy a **Name**, then select **Create**. This creates a one-time enrollment token. Copy the command shown—you'll need it in the next step.-- <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>+ Give the proxy a **Name**, then select **Create**. The **Proxy Token** dialog shows the proxy token once, with a command to start the proxy. Copy the command from the **CLI** tab for the next step.</Step><Step>On the host that will act as the proxy, run the command from the previous step.```bash- infisical agent-vault proxy --enrollment-token <enrollment-token>+ INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \+ infisical agent-vault proxy \+ --domain <your-instance-url>```- This enrolls the proxy, which starts listening on port `17323`. Leave it running and note this host's address—you'll need it when launching your agent.+ The proxy starts listening on port `17323`. Leave it running and note this host's address. You'll need the address when you launch your agent.</Step></Steps><Note>- This runs the proxy in your current terminal, so the proxy stops when the terminal closes. For a persistent setup, use the **Docker** or **systemd** snippet from the enrollment dialog.+ This runs the proxy in your current terminal, so the proxy stops when the terminal closes. For a persistent setup, use the **Docker** command or the **Kubernetes** manifest from the **Proxy Token** dialog, or [run the proxy with systemd](/documentation/platform/agent-vault/proxies#create-a-proxy-and-start-it).Check out the [proxies documentation](/documentation/platform/agent-vault/proxies) for more information.</Note>@@ -114,7 +112,7 @@ Next, create a [session](/documentation/platform/agent-vault/sessions) with your</Frame></Step><Step>- This creates the session and gives you a command to run your agent with it. Copy the command—you'll need it in the next step.+ This creates the session and gives you a command to run your agent with it. Copy the command for the next step.<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" />diff --git a/docs/snippets/agent-vault/SeparateMachinesNote.mdx b/docs/snippets/agent-vault/SeparateMachinesNote.mdxindex 669b21bdba..4cf6e0586e 100644--- a/docs/snippets/agent-vault/SeparateMachinesNote.mdx+++ b/docs/snippets/agent-vault/SeparateMachinesNote.mdx@@ -1,6 +1,5 @@<Note>- We recommend running the proxy on a different machine than the agent. If they run on the same machine, the agent could read the proxy's [state directory](/documentation/platform/agent-vault/proxies#state-directory). That directory contains sensitive values,- like the proxy's access token and the private key of its certificate authority.+ We recommend running the proxy on a different machine than the agent. If they run on the same machine, the agent could read the proxy token and the private key of the proxy's certificate authority.We also recommend keeping both machines on the same private network. This is because every request the agent makes goes through the proxy, and a round trip between networks adds latency to every request.</Note>diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex e9febb7bc4..71f11582cc 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -11,12 +11,12 @@ import {TAgentVaultAccessBundle,TAgentVaultActorIdsDTO,TAgentVaultActorRef,- TAgentVaultEnrollment,TAgentVaultGrantedMember,TAgentVaultMemberWriteResult,TAgentVaultMintedSession,TAgentVaultProxy,TAgentVaultProxySettingsDTO,+ TAgentVaultProxyWithToken,TAgentVaultService,TAgentVaultSessionLogSettings,TAgentVaultVariable,@@ -240,11 +240,10 @@ export const useCreateAgentVaultProxy = () => {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);+ const { data } = await apiRequest.post<TAgentVaultProxyWithToken>(+ "/api/v1/agent-vault/proxies",+ params+ );return data;},onSuccess: () => {@@ -289,15 +288,21 @@ export const useDeleteAgentVaultProxy = () => {});};-export const useReissueAgentVaultProxyEnrollmentToken = () =>- useMutation({+export const useRotateAgentVaultProxyToken = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({mutationFn: async (proxyId: string) => {- const { data } = await apiRequest.post<TAgentVaultEnrollment>(- `/api/v1/agent-vault/proxies/${proxyId}/token-auth/enrollment-token`+ const { data } = await apiRequest.post<TAgentVaultProxyWithToken>(+ `/api/v1/agent-vault/proxies/${proxyId}/token-auth/proxy-token`);return data;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.proxies(currentOrg.id) });}});+};export const useRevokeAgentVaultProxyAccess = () => {const { currentOrg } = useOrganization();diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 3b3dd5e736..eb315ee841 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -240,9 +240,12 @@ export type TAgentVaultProxy = {createdAt?: string;};-export type TAgentVaultEnrollment = {- token: string;- expiresAt: string;+export type TAgentVaultProxyToken = {+ proxyToken: string;+};++export type TAgentVaultProxyWithToken = TAgentVaultProxyToken & {+ proxy: TAgentVaultProxy;};export type TListAgentVaultSessionsDTO = {diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 55ef8a81e8..e2801c44a7 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -494,6 +494,7 @@ export const eventToNameMap: { [K in EventType]: string } = {[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_TOKEN_ROTATE]: "Rotate proxy token",[EventType.AGENT_VAULT_PROXY_UPDATE]: "Update proxy",[EventType.AGENT_VAULT_PROXY_REVOKE]: "Revoke proxy access",[EventType.AGENT_VAULT_PROXY_DELETE]: "Delete proxy",@@ -575,6 +576,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.AGENT_VAULT_PROXY_REGISTER,EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE,EventType.AGENT_VAULT_PROXY_ENROLL,+ EventType.AGENT_VAULT_PROXY_TOKEN_ROTATE,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.tsxindex 14486c3bd5..1560942c82 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -492,6 +492,7 @@ export enum EventType {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_TOKEN_ROTATE = "agent-vault-proxy-token-rotate",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/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsxindex afe6894c8f..b14c9c9c12 100644--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx@@ -69,17 +69,17 @@ import {AgentVaultTrafficPolicy,useDeleteAgentVaultProxy,useListAgentVaultProxies,- useReissueAgentVaultProxyEnrollmentToken,- useRevokeAgentVaultProxyAccess+ useRevokeAgentVaultProxyAccess,+ useRotateAgentVaultProxyToken} from "@app/hooks/api/agentVault";-import { TAgentVaultEnrollment, TAgentVaultProxy } from "@app/hooks/api/agentVault/types";+import { TAgentVaultProxy, TAgentVaultProxyToken } 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";+import { ProxyTokenDialog } from "./components/ProxyTokenDialog";const allowedHostsOf = (proxy: TAgentVaultProxy) =>proxy.allowedHosts@@ -160,14 +160,14 @@ export const AgentVaultProxiesPage = () => {useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });const deleteProxy = useDeleteAgentVaultProxy();const revokeProxy = useRevokeAgentVaultProxyAccess();- const reissueToken = useReissueAgentVaultProxyEnrollmentToken();+ const rotateProxyToken = useRotateAgentVaultProxyToken();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 [proxyToRotate, setProxyToRotate] = useState<TAgentVaultProxy | null>(null);+ const [proxyToken, setProxyToken] = useState<TAgentVaultProxyToken | null>(null);const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {setPage(1);@@ -210,13 +210,13 @@ export const AgentVaultProxiesPage = () => {}};- const handleReissue = async () => {- if (!proxyToReissue) return;+ const handleRotate = async () => {+ if (!proxyToRotate) return;try {- const result = await reissueToken.mutateAsync(proxyToReissue.id);- setProxyToReissue(null);- setEnrollment(result);+ const result = await rotateProxyToken.mutateAsync(proxyToRotate.id);+ setProxyToRotate(null);+ setProxyToken(result);} catch {// A failed request returns a 4xx that the global request handler surfaces as a toast}@@ -257,7 +257,7 @@ export const AgentVaultProxiesPage = () => {<EmptyHeader><EmptyTitle>No proxies yet</EmptyTitle><EmptyDescription>- Create a proxy and enroll it where agent traffic leaves your network.+ Create a proxy and start it where agent traffic leaves your network.</EmptyDescription></EmptyHeader></Empty>@@ -376,9 +376,9 @@ export const AgentVaultProxiesPage = () => {<PencilIcon />Edit Settings</DropdownMenuItem>- <DropdownMenuItem onClick={() => setProxyToReissue(proxy)}>+ <DropdownMenuItem onClick={() => setProxyToRotate(proxy)}><RefreshCwIcon />- New Enrollment Token+ Rotate Proxy Token</DropdownMenuItem><DropdownMenuItemvariant="danger"@@ -424,7 +424,7 @@ export const AgentVaultProxiesPage = () => {<ProxyFormDialogisOpen={isCreateOpen}onOpenChange={setIsCreateOpen}- onCreated={setEnrollment}+ onCreated={setProxyToken}/><ProxyFormDialog@@ -435,17 +435,17 @@ export const AgentVaultProxiesPage = () => {proxy={proxyToEdit ?? undefined}/>- <ProxyEnrollmentDialog- enrollment={enrollment}+ <ProxyTokenDialog+ proxyToken={proxyToken}onOpenChange={(isOpen) => {- if (!isOpen) setEnrollment(null);+ if (!isOpen) setProxyToken(null);}}/><AlertDialog- open={Boolean(proxyToReissue)}+ open={Boolean(proxyToRotate)}onOpenChange={(isOpen) => {- if (!isOpen) setProxyToReissue(null);+ if (!isOpen) setProxyToRotate(null);}}><AlertDialogContent>@@ -453,26 +453,24 @@ export const AgentVaultProxiesPage = () => {<AlertDialogMedia><TriangleAlertIcon /></AlertDialogMedia>- <AlertDialogTitle>- New enrollment token for "{proxyToReissue?.name}"- </AlertDialogTitle>+ <AlertDialogTitle>Rotate Token for "{proxyToRotate?.name}"</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.+ The current token will stop working, and the proxy gets a new certificate authority.+ Restart the proxy with the new token. Agents that pin the proxy's fingerprint+ need the new one.</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction- variant="av"- isPending={reissueToken.isPending}+ variant="danger"+ isPending={rotateProxyToken.isPending}onClick={async (event) => {event.preventDefault();- await handleReissue();+ await handleRotate();}}>- Generate Token+ Rotate</AlertDialogAction></AlertDialogFooter></AlertDialogContent>@@ -484,7 +482,7 @@ export const AgentVaultProxiesPage = () => {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."+ description="The proxy will stop adding credentials to requests. To bring it back, rotate its token."confirmKey={proxyToRevoke?.name ?? ""}confirmLabel="Revoke Access"isPending={revokeProxy.isPending}@@ -497,7 +495,7 @@ export const AgentVaultProxiesPage = () => {if (!isOpen) setProxyToDelete(null);}}title={`Delete "${proxyToDelete?.name}"`}- description="Agents routed through it lose their credentials. This cannot be undone."+ description="The proxy will stop adding credentials to requests. This cannot be undone."confirmKey={proxyToDelete?.name ?? ""}isPending={deleteProxy.isPending}onConfirm={handleDelete}diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyEnrollmentDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyEnrollmentDialog.tsxdeleted file mode 100644index 5b99de898d..0000000000--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyEnrollmentDialog.tsx+++ /dev/null@@ -1,128 +0,0 @@-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 wherever agents' requests leave your network. The proxy enrolls once, then- keeps its own certificate.- </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, since 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.tsxindex f83e704fd2..b59bbcc10a 100644--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx@@ -38,7 +38,7 @@ import {useCreateAgentVaultProxy,useUpdateAgentVaultProxy} from "@app/hooks/api/agentVault";-import { TAgentVaultEnrollment, TAgentVaultProxy } from "@app/hooks/api/agentVault/types";+import { TAgentVaultProxy, TAgentVaultProxyToken } from "@app/hooks/api/agentVault/types";import { slugSchema } from "@app/lib/schemas";const TRAFFIC_POLICY_CHOICES = [@@ -120,7 +120,7 @@ type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;proxy?: TAgentVaultProxy;- onCreated?: (enrollment: TAgentVaultEnrollment) => void;+ onCreated?: (proxyToken: TAgentVaultProxyToken) => void;};export const ProxyFormDialog = ({ isOpen, onOpenChange, proxy, onCreated }: Props) => {@@ -178,7 +178,7 @@ export const ProxyFormDialog = ({ isOpen, onOpenChange, proxy, onCreated }: Prop} else {const result = await createProxy.mutateAsync(payload);createNotification({ text: `Proxy "${data.name}" created`, type: "success" });- onCreated?.({ token: result.token, expiresAt: result.expiresAt });+ onCreated?.({ proxyToken: result.proxyToken });}onOpenChange(false);diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsxindex e694cc88c9..e1a2080f70 100644--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyStatusBadge.tsx@@ -9,7 +9,7 @@ export const ProxyStatusBadge = ({ proxy }: { proxy: TAgentVaultProxy }) => {return (<Badge variant="neutral"><CircleDashedIcon />- {proxy.rootCaFingerprint ? "Not connected" : "Never enrolled"}+ Not connected</Badge>);}diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyTokenDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyTokenDialog.tsxnew file mode 100644index 0000000000..4dc997a443--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyTokenDialog.tsx@@ -0,0 +1,151 @@+import { TriangleAlertIcon } from "lucide-react";++import {+ Alert,+ AlertDescription,+ Button,+ CodeBlock,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger+} from "@app/components/v3";+import { TAgentVaultProxyToken } from "@app/hooks/api/agentVault/types";++const cliCommand = (token: string, siteUrl: string) =>+ `INFISICAL_AGENT_VAULT_PROXY_TOKEN=${token} \\+infisical agent-vault proxy \\+ --domain ${siteUrl}`;++const systemdEnvFile = (token: string) => `INFISICAL_AGENT_VAULT_PROXY_TOKEN=${token}`;++const systemdUnit = (siteUrl: string) =>+ `[Unit]+Description=Infisical Agent Vault proxy+After=network-online.target+Wants=network-online.target++[Service]+EnvironmentFile=/etc/infisical/agent-vault-proxy.env+ExecStart=/usr/local/bin/infisical agent-vault proxy --domain ${siteUrl}+Restart=always++[Install]+WantedBy=multi-user.target`;++const dockerCommand = (token: string, siteUrl: string) =>+ `docker run -d --name agent-vault-proxy \\+ -p 17323:17323 \\+ -v agent-vault-proxy:/etc/infisical/agent-vault \\+ -e INFISICAL_AGENT_VAULT_PROXY_TOKEN=${token} \\+ infisical/cli agent-vault proxy \\+ --domain ${siteUrl}`;++const kubernetesManifest = (token: string, siteUrl: string) =>+ `apiVersion: v1+kind: Secret+metadata:+ name: agent-vault-proxy+type: Opaque+stringData:+ INFISICAL_AGENT_VAULT_PROXY_TOKEN: ${token}+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: agent-vault-proxy+spec:+ replicas: 2+ selector:+ matchLabels:+ app: agent-vault-proxy+ template:+ metadata:+ labels:+ app: agent-vault-proxy+ spec:+ containers:+ - name: agent-vault-proxy+ image: infisical/cli+ args: ["agent-vault", "proxy", "--domain", "${siteUrl}"]+ envFrom:+ - secretRef:+ name: agent-vault-proxy+ ports:+ - containerPort: 17323`;++type Props = {+ proxyToken: TAgentVaultProxyToken | null;+ onOpenChange: (isOpen: boolean) => void;+};++export const ProxyTokenDialog = ({ proxyToken, onOpenChange }: Props) => {+ const token = proxyToken?.proxyToken ?? "";+ const { protocol, hostname, port } = window.location;+ const siteUrl = `${protocol}//${hostname}${port && port !== "80" ? `:${port}` : ""}`;++ return (+ <Dialog open={Boolean(proxyToken)} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-2xl" onInteractOutside={(event) => event.preventDefault()}>+ <DialogHeader>+ <DialogTitle>Proxy Token</DialogTitle>+ <DialogDescription>+ Start the proxy with this token. You can run it on as many machines as you need.+ </DialogDescription>+ </DialogHeader>++ <div className="flex flex-col gap-4">+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ This token is shown only once. It works until you rotate it or revoke the proxy's+ access.+ </AlertDescription>+ </Alert>++ <CodeBlock value={token} label="Proxy token" />++ <Tabs defaultValue="cli">+ <TabsList variant="av" aria-label="Deployment target">+ <TabsTrigger value="cli">CLI</TabsTrigger>+ <TabsTrigger value="systemd">systemd</TabsTrigger>+ <TabsTrigger value="docker">Docker</TabsTrigger>+ <TabsTrigger value="kubernetes">Kubernetes</TabsTrigger>+ </TabsList>+ <TabsContent value="cli">+ <CodeBlock value={cliCommand(token, siteUrl)} label="Command" />+ </TabsContent>+ <TabsContent value="systemd" className="flex flex-col gap-4">+ <CodeBlock+ value={systemdEnvFile(token)}+ label="/etc/infisical/agent-vault-proxy.env (chmod 600)"+ />+ <CodeBlock+ value={systemdUnit(siteUrl)}+ label="/etc/systemd/system/agent-vault-proxy.service"+ />+ </TabsContent>+ <TabsContent value="docker">+ <CodeBlock value={dockerCommand(token, siteUrl)} label="Command" />+ </TabsContent>+ <TabsContent value="kubernetes">+ <CodeBlock value={kubernetesManifest(token, siteUrl)} label="Manifest" />+ </TabsContent>+ </Tabs>+ </div>++ <DialogFooter>+ <Button variant="av" onClick={() => onOpenChange(false)}>+ Done+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsxindex 32d43a20d7..d7c9dcecee 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx@@ -88,7 +88,7 @@ const PRODUCT_FILTER_KEYS: Partial<Record<ProjectType, string[]>> = {// 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.AgentVault]: "agent-vault-session-mint, agent-vault-proxy-enroll, ..."+ [ProjectType.AgentVault]: "agent-vault-session-mint, agent-vault-proxy-token-rotate, ..."};const getProductFilterProperties = (projectType?: ProjectType) => {