Skip to content

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

Merge main into AGE2-137 for inline services

Scott Wilson259fdd48c65c
diff --cc .infisicalignore
index 08865909a8,4b40bf798f..526f2ed490
--- a/.infisicalignore
+++ b/.infisicalignore
@@@ -85,3 -85,10 +85,11 @@@ tests/clients/api/api.gen.go:generic-ap
tests/clients/api/api.gen.go:generic-api-key:15744
tests/clients/api/api.gen.go:generic-api-key:15770
tests/clients/api/api.gen.go:generic-api-key:15771
+ tests/clients/api/api.gen.go:generic-api-key:15644
+ tests/clients/api/api.gen.go:generic-api-key:15645
+ tests/clients/api/api.gen.go:generic-api-key:15671
+ tests/clients/api/api.gen.go:generic-api-key:15672
+ backend/src/ee/services/dynamic-secret/providers/sap-ase.test.ts:generic-password:18
+ backend/src/services/app-connection/servicenow/servicenow-connection-fns.test.ts:generic-password:29
+ tests/fakes/oauth/google_signon.go:private-key:18
++backend/src/ee/services/dynamic-secret/providers/sql-database.test.ts:generic-password:44
diff --cc backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
index 266289bf7a,3ec1fed161..d58aa073dd
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
@@@ -28,8 -27,8 +28,9 @@@ import
import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";
import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix-schemas";
import { agentVaultMcpServerUrlSchema } from "@app/ee/services/agent-vault/agent-vault-service-type-fns";
+ import { agentVaultAllowedToolsSchema } from "@app/ee/services/agent-vault/agent-vault-tool-name-schemas";
import {
+ acceptsNoVariableReferences,
acceptsVariableReferences,
addDuplicateCustomHeaderNameIssues,
addDuplicatePlaceholderIssues,
@@@ -391,164 -402,16 +406,177 @@@ export const AgentVaultUpdateServiceBod
"Provide at least one field besides 'type' to update"
);
+// A service sent with a session takes no member-provided field and no OAuth: whoever starts the session sends every
+// value, and an OAuth service is connected by signing in from the UI. Both are still accepted, hidden, so the session
+// service refuses them by name rather than zod dropping a field silently.
+const inlineMemberProvidedFieldsSchema = z.string().max(64).array().max(2).optional().describe(openApiHidden());
+
+const inlineCredentialInputSchema = ({ mcp }: { mcp: boolean }) =>
+ z
+ .discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal(AgentVaultCredentialType.Bearer),
+ headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),
+ headerPrefix: agentVaultHeaderPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.headerPrefix),
+ value: acceptsNoVariableReferences(
+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ ).describe(AGENT_VAULT.SESSION.inlineServiceValue),
+ memberProvidedFields: inlineMemberProvidedFieldsSchema
+ })
+ .describe(docsTitle("Bearer")),
+ z
+ .object({
+ type: z.literal(AgentVaultCredentialType.Basic),
+ username: acceptsNoVariableReferences(
+ z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SESSION.inlineServiceUsername),
+ password: acceptsNoVariableReferences(
+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SESSION.inlineServicePassword),
+ memberProvidedFields: inlineMemberProvidedFieldsSchema
+ })
+ .describe(docsTitle("Basic Auth", mcp)),
+ passthroughCredentialInput.describe(docsTitle("Pass-through", mcp)),
+ z
+ .object({
+ type: z.literal(AgentVaultCredentialType.OAuth),
+ authorizationId: z.string().uuid().optional()
+ })
+ .describe(docsTitle("OAuth", true))
+ ])
+ .superRefine((data, ctx) => {
+ if (data.type === AgentVaultCredentialType.Basic && !data.username && !data.password) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["username"],
+ message: "A basic credential needs a username, a password, or both"
+ });
+ }
+ });
+
+const AgentVaultInlineCustomHeadersInputSchema = AgentVaultInlineCustomHeaderInputSchema.array()
+ .max(AGENT_VAULT_MAX_CUSTOM_HEADERS)
+ .superRefine(addDuplicateCustomHeaderNameIssues)
+ .describe(AGENT_VAULT.SESSION.inlineCustomHeaders);
+
+const AgentVaultInlineSubstitutionsInputSchema = AgentVaultInlineSubstitutionInputSchema.array()
+ .max(AGENT_VAULT_MAX_SUBSTITUTIONS)
+ .superRefine(addDuplicatePlaceholderIssues)
+ .describe(AGENT_VAULT.SESSION.inlineSubstitutions);
+
+const inlineServiceNameSchema = AgentVaultNameSchema.optional().describe(AGENT_VAULT.SESSION.inlineServiceName);
+
+// Each option also takes the other type's fields, hidden from the docs, so the session service can refuse them with a
+// message naming the field, as a bundle service's create does.
+const AgentVaultInlineServiceInputSchema = z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal(AgentVaultServiceType.Http).describe(AGENT_VAULT.SERVICE.type),
+ name: inlineServiceNameSchema,
+ hostPattern: AgentVaultHostPatternSchema,
+ allowedMethods: AgentVaultAllowedMethodsSchema.optional(),
+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),
+ credential: inlineCredentialInputSchema({ mcp: false }),
+ customHeaders: AgentVaultInlineCustomHeadersInputSchema.optional(),
+ substitutions: AgentVaultInlineSubstitutionsInputSchema.optional(),
+ serverUrl: AgentVaultServerUrlSchema.optional().describe(openApiHidden()),
- transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden())
++ transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden()),
++ allowedTools: AgentVaultAllowedToolsSchema.optional().describe(openApiHidden())
+ })
+ .describe(JSON.stringify({ title: "HTTP service" })),
+ z
+ .object({
+ type: z.literal(AgentVaultServiceType.Mcp).describe(AGENT_VAULT.SERVICE.type),
+ name: inlineServiceNameSchema,
+ serverUrl: AgentVaultServerUrlSchema,
+ transport: AgentVaultMcpTransportSchema,
+ credential: inlineCredentialInputSchema({ mcp: true }).describe(AGENT_VAULT.SESSION.inlineMcpCredential),
+ customHeaders: AgentVaultInlineCustomHeadersInputSchema.optional(),
+ hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),
+ allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),
+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional().describe(openApiHidden()),
- substitutions: AgentVaultInlineSubstitutionsInputSchema.optional().describe(openApiHidden())
++ substitutions: AgentVaultInlineSubstitutionsInputSchema.optional().describe(openApiHidden()),
++ // Refused by the session service with a message, rather than dropped, so nobody believes the tools are limited.
++ allowedTools: AgentVaultAllowedToolsSchema.optional().describe(openApiHidden())
+ })
+ .describe(JSON.stringify({ title: "MCP service" }))
+]);
+
+export const AgentVaultInlineServicesInputSchema = AgentVaultInlineServiceInputSchema.array()
+ .max(
+ AGENT_VAULT_MAX_SESSION_INLINE_SERVICES,
+ `A session can have at most ${AGENT_VAULT_MAX_SESSION_INLINE_SERVICES} services. Add the others to an access bundle and name it in accessBundles.`
+ )
+ .superRefine((services, ctx) => {
+ const seen = new Set<string>();
+ services.forEach((service, index) => {
+ if (!service.name) return;
+ if (seen.has(service.name)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [index, "name"],
+ message: `More than one inline service is named "${service.name}". Give each a different name.`
+ });
+ }
+ seen.add(service.name);
+ });
+ })
+ .describe(AGENT_VAULT.SESSION.inlineServices);
+
+// The sealed values are never in here, and the serializer emits only what this schema lists.
+export const AgentVaultInlineServiceSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.SESSION.inlineServiceId),
+ name: z.string().describe(AGENT_VAULT.SESSION.inlineServiceNameRead),
+ type: z.nativeEnum(AgentVaultServiceType).describe(AGENT_VAULT.SERVICE.type),
+ serverUrl: z.string().nullable().describe(AGENT_VAULT.SERVICE.serverUrlRead),
+ transport: z.nativeEnum(AgentVaultMcpTransport).nullable().describe(AGENT_VAULT.SERVICE.transportRead),
+ hostPattern: z.string().describe(AGENT_VAULT.SERVICE.hostPattern),
+ allowedMethods: z.nativeEnum(AgentVaultHttpMethod).array().nullable().describe(AGENT_VAULT.SERVICE.allowedMethods),
+ allowedPathPrefixes: z.string().array().nullable().describe(AGENT_VAULT.SERVICE.allowedPathPrefixes),
+ credential: z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal(AgentVaultCredentialType.Bearer),
+ headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),
+ headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix)
+ })
+ .describe(JSON.stringify({ title: "Bearer" })),
+ z.object({ type: z.literal(AgentVaultCredentialType.Basic) }).describe(JSON.stringify({ title: "Basic Auth" })),
+ z
+ .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
+ .describe(JSON.stringify({ title: "Pass-through" }))
+ ]),
+ customHeaders: z
+ .object({
+ name: z.string().describe(AGENT_VAULT.SERVICE.customHeaderName),
+ prefix: z.string().describe(AGENT_VAULT.SERVICE.customHeaderPrefix)
+ })
+ .array()
+ .describe(AGENT_VAULT.SESSION.inlineCustomHeadersRead),
+ substitutions: z
+ .object({
+ placeholder: z.string().describe(AGENT_VAULT.SERVICE.placeholder),
+ surfaces: z.nativeEnum(AgentVaultSubstitutionSurface).array().describe(AGENT_VAULT.SERVICE.surfaces)
+ })
+ .array()
+ .describe(AGENT_VAULT.SESSION.inlineSubstitutionsRead)
+});
+
+ // The service sheet's unsaved values, so the tools are listed with the credential a save would store. `serviceId`
+ // names the saved service whose stored values fill in what is left out.
+ export const AgentVaultListMcpToolsBodySchema = z.object({
+ serviceId: z.string().uuid().optional().describe(AGENT_VAULT.SERVICE.serviceId),
+ serverUrl: AgentVaultServerUrlSchema,
+ transport: AgentVaultMcpTransportSchema,
+ credential: AgentVaultMcpCredentialUpdateSchema.optional().describe(AGENT_VAULT.SERVICE.mcpCredential),
+ customHeaders: AgentVaultCustomHeadersUpdateSchema.optional()
+ });
+
const variableReferenceBase = {
variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),
key: z.string().describe(AGENT_VAULT.VARIABLE.key)
diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
index b291e4d32c,fda292694b..5fe8d35676
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
@@@ -128,7 -138,7 +138,8 @@@ import
TAgentVaultVariableReferenceWithKey
} from "./agent-vault-service-variable-reference-dal";
import {
+ assertCustomHeadersDoNotShadowCredential,
+ matchTransformationRows,
planTransformationDiff,
TTransformationWrite
} from "./agent-vault-transformation-fns";
diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts
index f5eb97a7fd,61d538f717..d29ef262da
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts
@@@ -434,81 -454,34 +462,111 @@@ describe("resolve for a session on a us
const { resolve } = setupOnBehalfOf({ identity: { isAdmin: true }, isUserDeleted: true });
await expect(resolve()).rejects.toThrow(UnauthorizedError);
});
+
+ test("a user without Read on sessions is a 401", async () => {
+ const { resolve } = setupOnBehalfOf({ user: { grants: ["bundle-a"], canRead: false } });
+ await expect(resolve()).rejects.toThrow(UnauthorizedError);
+ });
+
+ // A 403 reads to the proxy as "Infisical is unreachable", which would keep the agent running through its grace window.
+ test("a user no longer in Agent Vault is a 401, not a 403", async () => {
+ const { resolve } = setupOnBehalfOf({ user: { isMember: false } });
+ await expect(resolve()).rejects.toThrow(UnauthorizedError);
+ });
+
+ test("personal values are looked up for the user, never the identity", async () => {
+ const { resolve, findPersonalValues } = setupOnBehalfOf({
+ user: { isAdmin: true },
+ identity: { isAdmin: true },
+ rows: [
+ serviceRow({
+ type: AgentVaultServiceType.Http,
+ hostPattern: "api.example.com",
+ credentialType: AgentVaultCredentialType.Bearer,
+ credentialConfig: { headerName: "Authorization", headerPrefix: "Bearer" },
+ encryptedCredential: Buffer.from(JSON.stringify({ value: "" })),
+ memberProvidedFields: ["credential-value"]
+ })
+ ]
+ });
+ await resolve();
+ expect(findPersonalValues).toHaveBeenCalledWith({ serviceIds: [SERVICE_ID], owner: { userId: USER_ID } });
+ });
});
+
+describe("resolve with inline services", () => {
+ const resolve = (service: ReturnType<typeof setup>["service"]) =>
+ service.resolveSession({ proxyId: "proxy-1", orgId: "org-1", sessionToken: "token", hasSessionLogKey: false });
+ const noRefresh = async () => {
+ throw new Error("nothing here needs a refresh");
+ };
+
+ const passthroughBundleRow = serviceRow({
+ name: "bundle-api",
+ type: AgentVaultServiceType.Http,
+ hostPattern: "api.example.com",
+ config: {},
+ credentialType: AgentVaultCredentialType.Passthrough,
+ credentialConfig: {},
+ encryptedCredential: null
+ });
+
+ const inlineRow = (overrides: Partial<TAgentVaultSessionInlineServices> = {}): TAgentVaultSessionInlineServices => ({
+ id: "inline-1",
+ sessionId: "session-1",
+ position: 0,
+ name: "inline-api",
+ type: AgentVaultServiceType.Http,
+ config: {},
+ hostPattern: "api.example.com",
+ allowedMethods: null,
+ allowedPathPrefixes: null,
+ credentialType: AgentVaultCredentialType.Bearer,
+ credentialConfig: { type: AgentVaultCredentialType.Bearer, headerName: "Authorization", headerPrefix: "Bearer" },
+ customHeaders: [],
+ substitutions: [],
+ // The test's decryptor hands the blob back as it is.
+ encryptedSecrets: Buffer.from(
+ JSON.stringify({ credential: { value: "inline-token" }, customHeaders: [], substitutions: [] })
+ ),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides
+ });
+
+ // The proxy picks the first of two equally specific matches, so the bundle's service wins a host both cover.
+ test("sends the inline services after the access bundle's", async () => {
+ const { service } = setup(noRefresh, [passthroughBundleRow], [], { inlineRows: [inlineRow()] });
+ const { services } = await resolve(service);
+ expect(services.map((resolved) => resolved.name)).toEqual(["bundle-api", "inline-api"]);
+ expect(services[1]).toMatchObject({ accessBundleName: null, credential: { value: "inline-token" } });
+ });
+
+ test("leaves the inline services out once the session's owner isn't an admin", async () => {
+ const { service, findInlineServices } = setup(noRefresh, [passthroughBundleRow], [], {
+ inlineRows: [inlineRow()],
+ isOwnerAdmin: false
+ });
+ const { services } = await resolve(service);
+ expect(services.map((resolved) => resolved.name)).toEqual(["bundle-api"]);
+ expect(findInlineServices).not.toHaveBeenCalled();
+ });
+
+ test("derives the data key only when an inline service has something sealed", async () => {
+ const unsealed = setup(noRefresh, [passthroughBundleRow], [], {
+ inlineRows: [
+ inlineRow({
+ credentialType: AgentVaultCredentialType.Passthrough,
+ credentialConfig: { type: AgentVaultCredentialType.Passthrough },
+ encryptedSecrets: null
+ })
+ ]
+ });
+ expect((await resolve(unsealed.service)).services).toHaveLength(2);
+ expect(unsealed.createCipherPairWithDataKey).not.toHaveBeenCalled();
+
+ const sealed = setup(noRefresh, [passthroughBundleRow], [], { inlineRows: [inlineRow()] });
+ await resolve(sealed.service);
+ expect(sealed.createCipherPairWithDataKey).toHaveBeenCalledTimes(1);
+ });
+});
diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
index 25671b2ab7,e3975bcc16..96b51e676c
--- 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
@@@ -362,7 -371,8 +384,8 @@@ export const agentVaultProxyServiceFact
{
projectId,
name,
+ description,
- trafficPolicy: settings.trafficPolicy ?? AgentVaultTrafficPolicy.AnyHost,
+ trafficPolicy: toStoredTrafficPolicy(settings.trafficPolicy ?? AgentVaultTrafficPolicy.AnyHost),
allowedHosts: settings.allowedHosts ?? null,
pollInterval: settings.pollInterval ?? 60,
tokenVersion: 1,
diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.test.ts
index 7395aa0d46,0000000000..4e09029631
mode 100644,000000..100644
--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.test.ts
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.test.ts
@@@ -1,346 -1,0 +1,361 @@@
+import { describe, expect, test } from "vitest";
+
+import { TAgentVaultSessionInlineServices } from "@app/db/schemas";
+
+import {
+ AgentVaultCredentialType,
+ AgentVaultMcpTransport,
+ AgentVaultServiceType,
+ AgentVaultSubstitutionSurface
+} from "../agent-vault/agent-vault-enums";
+import {
+ assertNoAccessBundleConflicts,
+ inlineServiceDisplayName,
+ prepareInlineServices,
+ toInlineServiceSummary,
+ toResolvedInlineService
+} from "./agent-vault-session-inline-service-fns";
+import { TAgentVaultInlineServiceInput } from "./agent-vault-session-types";
+
+const httpBearer = (overrides: Partial<TAgentVaultInlineServiceInput> = {}): TAgentVaultInlineServiceInput => ({
+ type: AgentVaultServiceType.Http,
+ hostPattern: "api.example.com",
+ credential: { type: AgentVaultCredentialType.Bearer, value: "sk-live" },
+ ...overrides
+});
+
+const storedRow = (overrides: Partial<TAgentVaultSessionInlineServices> = {}): TAgentVaultSessionInlineServices => ({
+ id: "inline-1",
+ sessionId: "session-1",
+ position: 0,
+ name: null,
+ type: AgentVaultServiceType.Http,
+ config: {},
+ hostPattern: "api.example.com",
+ allowedMethods: null,
+ allowedPathPrefixes: null,
+ credentialType: AgentVaultCredentialType.Bearer,
+ credentialConfig: { type: AgentVaultCredentialType.Bearer, headerName: "Authorization", headerPrefix: "Bearer" },
+ customHeaders: [],
+ substitutions: [],
+ encryptedSecrets: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides
+});
+
+describe("prepareInlineServices", () => {
+ test("settles a bearer credential the way a bundle service does and keeps its value to seal", () => {
+ const [service] = prepareInlineServices([httpBearer()]);
+ expect(service.name).toBeNull();
+ expect(service.credentialConfig).toEqual({
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer"
+ });
+ expect(service.secrets).toEqual({ credential: { value: "sk-live" }, customHeaders: [], substitutions: [] });
+ });
+
+ test("keeps custom header and substitution values out of the stored names and seals them in order", () => {
+ const [service] = prepareInlineServices([
+ httpBearer({
+ customHeaders: [{ name: "X-Team", value: "platform" }],
+ substitutions: [
+ { placeholder: "TEAM_ID", surfaces: [AgentVaultSubstitutionSurface.Path], value: "42" },
+ { placeholder: "REGION", surfaces: [AgentVaultSubstitutionSurface.Query], value: "eu" }
+ ]
+ })
+ ]);
+ expect(service.customHeaders).toEqual([{ name: "X-Team", prefix: "" }]);
+ expect(service.substitutions.map((substitution) => substitution.placeholder)).toEqual(["TEAM_ID", "REGION"]);
+ expect(service.secrets?.customHeaders).toEqual(["platform"]);
+ expect(service.secrets?.substitutions).toEqual(["42", "eu"]);
+ });
+
+ test("seals nothing for a pass-through service with nothing to send", () => {
+ const [service] = prepareInlineServices([
+ httpBearer({ credential: { type: AgentVaultCredentialType.Passthrough } })
+ ]);
+ expect(service.secrets).toBeNull();
+ });
+
+ test("derives an MCP service's host from its server URL", () => {
+ const [service] = prepareInlineServices([
+ {
+ type: AgentVaultServiceType.Mcp,
+ serverUrl: "https://mcp.example.com/mcp",
+ transport: AgentVaultMcpTransport.StreamableHttp,
+ credential: { type: AgentVaultCredentialType.Bearer, value: "token" }
+ }
+ ]);
+ expect(service.hostPattern).toBe("mcp.example.com");
+ expect(service.config).toEqual({ serverUrl: "https://mcp.example.com/mcp", transport: "streamable-http" });
+ });
+
+ test("names the service in a refusal, by name or by index", () => {
+ expect(() =>
+ prepareInlineServices([
+ httpBearer({ name: "github", serverUrl: "https://mcp.example.com/mcp" }),
+ httpBearer({ hostPattern: "other.example.com" })
+ ])
+ ).toThrow(/^Service 'github': An HTTP service doesn't take 'serverUrl'/);
+ expect(() =>
+ prepareInlineServices([
+ httpBearer(),
+ httpBearer({ hostPattern: "other.example.com", credential: { type: AgentVaultCredentialType.OAuth } })
+ ])
+ ).toThrow(/^Service at index 1: Services sent with a session can't use OAuth/);
+ });
+
+ test("refuses fields left to members", () => {
+ expect(() =>
+ prepareInlineServices([
+ httpBearer({
+ credential: {
+ type: AgentVaultCredentialType.Bearer,
+ value: "token",
+ memberProvidedFields: ["credential-value"]
+ }
+ })
+ ])
+ ).toThrow(/can't leave a field to members/);
+ });
+
+ test("offers only a bearer token for an MCP service, since OAuth isn't available inline", () => {
+ expect(() =>
+ prepareInlineServices([
+ {
+ type: AgentVaultServiceType.Mcp,
+ serverUrl: "https://mcp.example.com/mcp",
+ transport: AgentVaultMcpTransport.StreamableHttp,
+ credential: { type: AgentVaultCredentialType.Passthrough }
+ }
+ ])
+ ).toThrow("Service at index 0: An MCP service can't use pass-through as its credential. Use a bearer token.");
+ });
+
+ test("refuses a custom header that would shadow the credential's", () => {
+ expect(() =>
+ prepareInlineServices([httpBearer({ customHeaders: [{ name: "authorization", value: "x" }] })])
+ ).toThrow(/The Authorization header is already set by the credential/);
+ });
+
+ test("refuses two inline services covering the same pattern but allows an exact host beside a wildcard", () => {
+ expect(() =>
+ prepareInlineServices([httpBearer({ name: "first" }), httpBearer({ hostPattern: "API.example.com" })])
+ ).toThrow(
+ "The service 'first' and the service at index 1 both cover api.example.com:443. Remove it from one of them."
+ );
+ expect(() => prepareInlineServices([httpBearer({ hostPattern: "*.example.com" }), httpBearer()])).not.toThrow();
+ });
+
+ test("refuses a service sent without a name whose first host is another service's name", () => {
+ expect(() =>
+ prepareInlineServices([
+ httpBearer({ name: "localhost", hostPattern: "api.example.com" }),
+ httpBearer({ hostPattern: "localhost" })
+ ])
+ ).toThrow(
+ "The service 'localhost' and the service at index 1 would both be called 'localhost', since a service sent without a name goes by its first host. Give one of them a different name."
+ );
+ });
+
++ test("refuses a tool list on an MCP server, rather than dropping it", () => {
++ expect(() =>
++ prepareInlineServices([
++ {
++ type: AgentVaultServiceType.Mcp,
++ serverUrl: "https://mcp.example.com/mcp",
++ transport: AgentVaultMcpTransport.StreamableHttp,
++ credential: { type: AgentVaultCredentialType.Bearer, value: "token" },
++ allowedTools: ["search"]
++ }
++ ])
++ ).toThrow(/^Service at index 0: Services sent with a session can't limit an MCP server's tools/);
++ });
++
+ test("refuses a basic credential with neither half", () => {
+ expect(() => prepareInlineServices([httpBearer({ credential: { type: AgentVaultCredentialType.Basic } })])).toThrow(
+ "Service at index 0: A basic credential needs a username, a password, or both"
+ );
+ });
+});
+
+describe("assertNoAccessBundleConflicts", () => {
+ const bundle = { name: "prod", services: [{ id: "service-1", name: "github", hostPattern: "api.github.com" }] };
+
+ test("refuses an inline service covering a pattern the bundle already covers", () => {
+ const prepared = prepareInlineServices([httpBearer({ hostPattern: "uploads.github.com,api.github.com" })]);
+ expect(() => assertNoAccessBundleConflicts(prepared, bundle)).toThrow(
+ "The service at index 0 covers api.github.com:443, which 'github' in the access bundle 'prod' already covers. Remove it from the service at index 0."
+ );
+ });
+
+ test("refuses an inline service called the same as one of the bundle's", () => {
+ const prepared = prepareInlineServices([httpBearer({ name: "github", hostPattern: "github.example.com" })]);
+ expect(() => assertNoAccessBundleConflicts(prepared, bundle)).toThrow(
+ "The service 'github' has the same name as a service in the access bundle 'prod'. Give it a different name."
+ );
+ // Hosts match regardless of case, so a host typed in capitals still clashes.
+ const unnamed = prepareInlineServices([httpBearer({ hostPattern: "GitHub" })]);
+ expect(() => assertNoAccessBundleConflicts(unnamed, bundle)).toThrow(
+ "The service at index 0 goes by its first host, 'github', which is the name of a service in the access bundle 'prod'. Give it a name."
+ );
+ });
+
+ test("allows a wildcard that contains the bundle's exact host", () => {
+ const prepared = prepareInlineServices([httpBearer({ hostPattern: "*.github.com" })]);
+ expect(() => assertNoAccessBundleConflicts(prepared, bundle)).not.toThrow();
+ });
+});
+
+describe("inline service reads", () => {
+ test("falls back to the first host for a service sent without a name", () => {
+ expect(inlineServiceDisplayName({ name: null, hostPattern: " api.example.com , *.example.org" })).toBe(
+ "api.example.com"
+ );
+ expect(inlineServiceDisplayName({ name: "openai", hostPattern: "api.openai.com" })).toBe("openai");
+ expect(inlineServiceDisplayName({ name: null, hostPattern: "api.example.com:443, b.example.com" })).toBe(
+ "api.example.com"
+ );
+ expect(inlineServiceDisplayName({ name: null, hostPattern: "api.example.com:8443" })).toBe("api.example.com:8443");
+ expect(inlineServiceDisplayName({ name: null, hostPattern: "API.Example.com" })).toBe("api.example.com");
+ });
+
+ test("the summary names a service sent without a name by its first host", () => {
+ expect(toInlineServiceSummary(storedRow()).name).toBe("api.example.com");
+ expect(toInlineServiceSummary(storedRow({ name: "example" })).name).toBe("example");
+ });
+
+ test("the summary carries no secret, nor anything else stored beside the credential", () => {
+ const summary = toInlineServiceSummary(
+ storedRow({
+ encryptedSecrets: Buffer.from("sealed"),
+ credentialConfig: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ source: AgentVaultCredentialType.OAuth
+ }
+ })
+ );
+ expect(summary).not.toHaveProperty("encryptedSecrets");
+ expect(summary.credential).toEqual({
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer"
+ });
+ });
+});
+
+describe("toResolvedInlineService", () => {
+ test("sends the values as they were stored, braces and all, with no bundle", () => {
+ const resolved = toResolvedInlineService(storedRow(), {
+ credential: { value: "{{literal}}" },
+ customHeaders: [],
+ substitutions: []
+ });
+ expect(resolved).toMatchObject({
+ name: "api.example.com",
+ accessBundleName: null,
++ allowedTools: null,
+ personalValuesMissing: false,
+ credential: { type: AgentVaultCredentialType.Bearer, value: "{{literal}}" }
+ });
+ });
+
+ test("leaves out a service whose secrets were deleted when its session ended", () => {
+ expect(toResolvedInlineService(storedRow(), null)).toBeNull();
+ expect(
+ toResolvedInlineService(
+ storedRow({
+ credentialType: AgentVaultCredentialType.Passthrough,
+ credentialConfig: { type: AgentVaultCredentialType.Passthrough },
+ customHeaders: [{ name: "X-Team", prefix: "" }]
+ }),
+ null
+ )
+ ).toBeNull();
+ });
+
+ test("sends a pass-through service that never had anything to seal", () => {
+ expect(
+ toResolvedInlineService(
+ storedRow({
+ credentialType: AgentVaultCredentialType.Passthrough,
+ credentialConfig: { type: AgentVaultCredentialType.Passthrough }
+ }),
+ null
+ )
+ ).toMatchObject({ credential: { type: AgentVaultCredentialType.Passthrough }, customHeaders: [] });
+ });
+
+ test("leaves out a service whose sealed values don't line up with its stored names", () => {
+ expect(
+ toResolvedInlineService(storedRow({ customHeaders: [{ name: "X-Team", prefix: "" }] }), {
+ credential: { value: "token" },
+ customHeaders: [],
+ substitutions: []
+ })
+ ).toBeNull();
+ expect(
+ toResolvedInlineService(
+ storedRow({ substitutions: [{ placeholder: "ACME_KEY", surfaces: [AgentVaultSubstitutionSurface.Header] }] }),
+ { credential: { value: "token" }, customHeaders: [], substitutions: [] }
+ )
+ ).toBeNull();
+ });
+
+ test("leaves out a service whose sealed credential is the wrong kind", () => {
+ expect(
+ toResolvedInlineService(storedRow(), {
+ credential: { username: "user", password: "pass" },
+ customHeaders: [],
+ substitutions: []
+ })
+ ).toBeNull();
+ expect(
+ toResolvedInlineService(
+ storedRow({
+ credentialType: AgentVaultCredentialType.Basic,
+ credentialConfig: { type: AgentVaultCredentialType.Basic }
+ }),
+ { credential: { value: "token" }, customHeaders: [], substitutions: [] }
+ )
+ ).toBeNull();
+ });
+
+ test("sends a basic credential's username and password", () => {
+ expect(
+ toResolvedInlineService(
+ storedRow({
+ credentialType: AgentVaultCredentialType.Basic,
+ credentialConfig: { type: AgentVaultCredentialType.Basic }
+ }),
+ { credential: { username: "user", password: "pass" }, customHeaders: [], substitutions: [] }
+ )?.credential
+ ).toEqual({ type: AgentVaultCredentialType.Basic, username: "user", password: "pass" });
+ });
+
+ // An OAuth source would make the proxy try to refresh a token it was sent as is.
+ test("sends only the bearer fields, whatever else is stored beside them", () => {
+ expect(
+ toResolvedInlineService(
+ storedRow({
+ credentialConfig: {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ source: AgentVaultCredentialType.OAuth
+ }
+ }),
+ { credential: { value: "token" }, customHeaders: [], substitutions: [] }
+ )?.credential
+ ).toEqual({
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ value: "token"
+ });
+ });
+});
diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.ts
index aa81f551ef,0000000000..3f70973247
mode 100644,000000..100644
--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.ts
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.ts
@@@ -1,327 -1,0 +1,336 @@@
+import { z } from "zod";
+
+import { TAgentVaultSessionInlineServices } from "@app/db/schemas";
+import { BadRequestError } from "@app/lib/errors";
+
+import { assertCustomHeadersDoNotShadowCredential } from "../agent-vault-access-bundle/agent-vault-transformation-fns";
+import { TResolvedService } from "../agent-vault-proxy/agent-vault-proxy-types";
+import { findHostPatternConflicts, TConflictCandidate } from "../agent-vault/agent-vault-conflict-fns";
+import { AgentVaultBearerConfigSchema } from "../agent-vault/agent-vault-credential-schemas";
+import {
+ AgentVaultCredentialType,
+ AgentVaultHttpMethod,
+ AgentVaultServiceType
+} from "../agent-vault/agent-vault-enums";
+import {
+ assertCredentialTypeSupported,
+ assertServiceFieldsSupported,
+ buildServiceConfig,
+ getAgentVaultServiceType,
+ resolveServiceHostPattern,
+ TAgentVaultServiceConfig
+} from "../agent-vault/agent-vault-service-type-fns";
+import { TAgentVaultInlineServiceInput, TAgentVaultInlineServiceSummary } from "./agent-vault-session-types";
+
+export const AGENT_VAULT_MAX_SESSION_INLINE_SERVICES = 20;
+
+type TInlineCredentialConfig = TAgentVaultInlineServiceSummary["credential"];
+type TInlineCustomHeader = TAgentVaultInlineServiceSummary["customHeaders"][number];
+type TInlineSubstitution = TAgentVaultInlineServiceSummary["substitutions"][number];
+
+// Values are kept in the order of the names and placeholders stored beside them.
+const InlineServiceSecretsSchema = z.object({
+ credential: z
+ .union([z.object({ value: z.string() }), z.object({ username: z.string(), password: z.string() })])
+ .nullable(),
+ customHeaders: z.string().array(),
+ substitutions: z.string().array()
+});
+
+export type TInlineServiceSecrets = z.infer<typeof InlineServiceSecretsSchema>;
+
+export type TPreparedInlineService = {
+ position: number;
+ name: string | null;
+ type: AgentVaultServiceType;
+ config: TAgentVaultServiceConfig;
+ hostPattern: string;
+ allowedMethods: AgentVaultHttpMethod[] | null;
+ allowedPathPrefixes: string[] | null;
+ credentialConfig: TInlineCredentialConfig;
+ customHeaders: TInlineCustomHeader[];
+ substitutions: TInlineSubstitution[];
+ // Null when there is nothing to seal: a pass-through service with no custom headers or substitutions.
+ secrets: TInlineServiceSecrets | null;
+};
+
+// What an inline service is called wherever a name is shown: its own, or its first host when it was sent without one,
+// lowercased and without the default port, since hosts match regardless of case and every screen shows a host that way.
+export const inlineServiceDisplayName = ({ name, hostPattern }: { name?: string | null; hostPattern: string }) =>
+ name || hostPattern.split(",")[0].trim().toLowerCase().replace(/:443$/, "");
+
+const toInlineCredential = (
+ credential: Exclude<TAgentVaultInlineServiceInput["credential"], { type: AgentVaultCredentialType.OAuth }>
+): { config: TInlineCredentialConfig; secret: TInlineServiceSecrets["credential"] } => {
+ switch (credential.type) {
+ case AgentVaultCredentialType.Bearer: {
+ const { headerName, headerPrefix } = AgentVaultBearerConfigSchema.parse({
+ headerName: credential.headerName,
+ headerPrefix: credential.headerPrefix
+ });
+ return {
+ config: { type: AgentVaultCredentialType.Bearer, headerName, headerPrefix },
+ secret: { value: credential.value }
+ };
+ }
+ case AgentVaultCredentialType.Basic:
+ if (!credential.username && !credential.password) {
+ throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });
+ }
+ return {
+ config: { type: AgentVaultCredentialType.Basic },
+ secret: { username: credential.username ?? "", password: credential.password ?? "" }
+ };
+ default:
+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };
+ }
+};
+
+const prepareInlineService = (input: TAgentVaultInlineServiceInput, position: number): TPreparedInlineService => {
+ const definition = getAgentVaultServiceType(input.type);
+ assertServiceFieldsSupported(definition, {
+ hostPattern: input.hostPattern,
+ allowedMethods: input.allowedMethods,
+ allowedPathPrefixes: input.allowedPathPrefixes,
+ customHeaders: input.customHeaders,
+ substitutions: input.substitutions,
+ serverUrl: input.serverUrl,
- transport: input.transport
++ transport: input.transport,
++ allowedTools: input.allowedTools
+ });
++ if (input.allowedTools?.length) {
++ throw new BadRequestError({
++ message:
++ "Services sent with a session can't limit an MCP server's tools, so leave out allowedTools. Add the MCP server to an access bundle to limit its tools."
++ });
++ }
+
+ const { credential } = input;
+ if (credential.type === AgentVaultCredentialType.OAuth) {
+ throw new BadRequestError({
+ message:
+ "Services sent with a session can't use OAuth, since an OAuth service is connected by signing in from the Infisical UI. Add it to an access bundle instead."
+ });
+ }
+ if ("memberProvidedFields" in credential && credential.memberProvidedFields?.length) {
+ throw new BadRequestError({
+ message:
+ "Services sent with a session can't leave a field to members, so send every value and leave out memberProvidedFields."
+ });
+ }
+ assertCredentialTypeSupported(
+ definition,
+ credential.type,
+ definition.allowedCredentialTypes.filter((type) => type !== AgentVaultCredentialType.OAuth)
+ );
+
+ const config = buildServiceConfig(definition, { serverUrl: input.serverUrl, transport: input.transport });
+ const hostPattern = resolveServiceHostPattern(definition, config, input.hostPattern);
+
+ const { config: credentialConfig, secret } = toInlineCredential(credential);
+ const customHeaders = input.customHeaders ?? [];
+ const substitutions = input.substitutions ?? [];
+ assertCustomHeadersDoNotShadowCredential(credentialConfig, customHeaders);
+
+ return {
+ position,
+ name: input.name ?? null,
+ type: definition.type,
+ config,
+ hostPattern,
+ allowedMethods: input.allowedMethods ?? null,
+ allowedPathPrefixes: input.allowedPathPrefixes ?? null,
+ credentialConfig,
+ customHeaders: customHeaders.map((header) => ({ name: header.name, prefix: header.prefix ?? "" })),
+ substitutions: substitutions.map((substitution) => ({
+ placeholder: substitution.placeholder,
+ surfaces: substitution.surfaces
+ })),
+ secrets:
+ secret || customHeaders.length || substitutions.length
+ ? {
+ credential: secret,
+ customHeaders: customHeaders.map((header) => header.value),
+ substitutions: substitutions.map((substitution) => substitution.value)
+ }
+ : null
+ };
+};
+
+// How mint errors point at a service: by the name it was sent with, or by its place in the list.
+const inlineServiceLabel = (service: Pick<TPreparedInlineService, "name" | "position">) =>
+ service.name ? `'${service.name}'` : `at index ${service.position}`;
+
+const toConflictCandidate = (service: TPreparedInlineService): TConflictCandidate => ({
+ id: String(service.position),
+ name: inlineServiceLabel(service),
+ hostPattern: service.hostPattern
+});
+
+/**
+ * Checks and normalizes the services a mint sends, the way a bundle service's create does, and holds them to the
+ * same host rule as one bundle's services: an exact host may sit beside a wildcard that contains it, but two services
+ * covering the same pattern would leave the proxy's choice to the order they were sent in.
+ */
+export const prepareInlineServices = (inputs: TAgentVaultInlineServiceInput[]): TPreparedInlineService[] => {
+ const prepared = inputs.map((input, position) => {
+ try {
+ return prepareInlineService(input, position);
+ } catch (error) {
+ if (error instanceof BadRequestError) {
+ const label = `Service ${inlineServiceLabel({ name: input.name ?? null, position })}`;
+ throw new BadRequestError({ message: `${label}: ${error.message}` });
+ }
+ throw error;
+ }
+ });
+
+ prepared.forEach((service, index) => {
+ const [conflict] = findHostPatternConflicts(service.hostPattern, prepared.slice(0, index).map(toConflictCandidate));
+ if (conflict) {
+ throw new BadRequestError({
+ message: `The service ${conflict.serviceName} and the service ${inlineServiceLabel(service)} both cover ${conflict.patterns.join(", ")}. Remove it from one of them.`
+ });
+ }
+ });
+
+ // An unnamed service goes by its first host in session logs and proxy errors, so it can't share that name.
+ const byDisplayName = new Map<string, TPreparedInlineService>();
+ prepared.forEach((service) => {
+ const displayName = inlineServiceDisplayName(service);
+ const earlier = byDisplayName.get(displayName);
+ if (earlier) {
+ throw new BadRequestError({
+ message: `The service ${inlineServiceLabel(earlier)} and the service ${inlineServiceLabel(service)} would both be called '${displayName}', since a service sent without a name goes by its first host. Give one of them a different name.`
+ });
+ }
+ byDisplayName.set(displayName, service);
+ });
+
+ return prepared;
+};
+
+/**
+ * A mint that also names an access bundle can't send a service covering a pattern one of the bundle's services covers,
+ * or one called the same as a bundle's service. Only checked at mint: the bundle can change afterwards, and resolve puts
+ * the bundle's services first, so a pattern a later bundle edit shares with an inline service goes to the bundle's.
+ */
+export const assertNoAccessBundleConflicts = (
+ prepared: TPreparedInlineService[],
+ accessBundle: { name: string; services: TConflictCandidate[] }
+) => {
+ prepared.forEach((service) => {
+ const label = inlineServiceLabel(service);
+ const [conflict] = findHostPatternConflicts(service.hostPattern, accessBundle.services);
+ if (conflict) {
+ throw new BadRequestError({
+ message: `The service ${label} covers ${conflict.patterns.join(", ")}, which '${conflict.serviceName}' in the access bundle '${accessBundle.name}' already covers. Remove it from the service ${label}.`
+ });
+ }
+ const displayName = inlineServiceDisplayName(service);
+ if (accessBundle.services.some((bundleService) => bundleService.name === displayName)) {
+ throw new BadRequestError({
+ message: service.name
+ ? `The service ${label} has the same name as a service in the access bundle '${accessBundle.name}'. Give it a different name.`
+ : `The service ${label} goes by its first host, '${displayName}', which is the name of a service in the access bundle '${accessBundle.name}'. Give it a name.`
+ });
+ }
+ });
+};
+
+export type TAgentVaultSessionInlineServiceSummaryRow = Omit<TAgentVaultSessionInlineServices, "encryptedSecrets">;
+
+const toInlineCredentialSummary = (config: TInlineCredentialConfig): TInlineCredentialConfig =>
+ config.type === AgentVaultCredentialType.Bearer
+ ? { type: config.type, headerName: config.headerName, headerPrefix: config.headerPrefix }
+ : { type: config.type };
+
+// Built by hand rather than spread, so the sealed column stays off the wire even if a response schema is loosened.
+export const toInlineServiceSummary = (
+ row: TAgentVaultSessionInlineServiceSummaryRow
+): TAgentVaultInlineServiceSummary => {
+ const config = (row.config ?? {}) as TAgentVaultServiceConfig;
+ return {
+ id: row.id,
+ name: inlineServiceDisplayName(row),
+ type: row.type as AgentVaultServiceType,
+ serverUrl: config.serverUrl ?? null,
+ transport: config.transport ?? null,
+ hostPattern: row.hostPattern,
+ allowedMethods: (row.allowedMethods ?? null) as AgentVaultHttpMethod[] | null,
+ allowedPathPrefixes: row.allowedPathPrefixes ?? null,
+ credential: toInlineCredentialSummary(row.credentialConfig as TInlineCredentialConfig),
+ customHeaders: row.customHeaders as TInlineCustomHeader[],
+ substitutions: row.substitutions as TInlineSubstitution[]
+ };
+};
+
+export const parseInlineServiceSecrets = (decrypted: unknown) => InlineServiceSecretsSchema.parse(decrypted);
+
+/**
+ * Null when the service can't go out: it needs secrets and none are stored, which means its session ended and they
+ * were deleted, or what is stored doesn't line up with the names beside it. Its values were sent as they are, so
+ * nothing in them is expanded.
+ */
+export const toResolvedInlineService = (
+ row: TAgentVaultSessionInlineServices,
+ secrets: TInlineServiceSecrets | null
+): TResolvedService | null => {
+ const credentialConfig = row.credentialConfig as TInlineCredentialConfig;
+ const customHeaders = row.customHeaders as TInlineCustomHeader[];
+ const substitutions = row.substitutions as TInlineSubstitution[];
+
+ let credential: TResolvedService["credential"];
+ if (credentialConfig.type === AgentVaultCredentialType.Passthrough) {
+ credential = { type: AgentVaultCredentialType.Passthrough };
+ } else if (
+ credentialConfig.type === AgentVaultCredentialType.Bearer &&
+ secrets?.credential &&
+ "value" in secrets.credential
+ ) {
+ credential = {
+ type: AgentVaultCredentialType.Bearer,
+ headerName: credentialConfig.headerName,
+ headerPrefix: credentialConfig.headerPrefix,
+ value: secrets.credential.value
+ };
+ } else if (
+ credentialConfig.type === AgentVaultCredentialType.Basic &&
+ secrets?.credential &&
+ "username" in secrets.credential
+ ) {
+ credential = {
+ type: AgentVaultCredentialType.Basic,
+ username: secrets.credential.username,
+ password: secrets.credential.password
+ };
+ } else {
+ return null;
+ }
+
+ if (
+ (customHeaders.length || substitutions.length) &&
+ (secrets?.customHeaders.length !== customHeaders.length || secrets.substitutions.length !== substitutions.length)
+ ) {
+ return null;
+ }
+
+ return {
+ id: row.id,
+ name: inlineServiceDisplayName(row),
+ accessBundleName: null,
+ type: row.type as AgentVaultServiceType,
+ hostPattern: row.hostPattern,
+ allowedMethods: row.allowedMethods ?? null,
+ allowedPathPrefixes: row.allowedPathPrefixes ?? null,
++ // An inline MCP server can't be limited to some of its tools, so the proxy filters none.
++ allowedTools: null,
+ credential,
+ customHeaders: customHeaders.map((header, index) => ({ ...header, value: secrets!.customHeaders[index] })),
+ substitutions: substitutions.map((substitution, index) => ({
+ ...substitution,
+ value: secrets!.substitutions[index]
+ })),
+ personalValuesMissing: false
+ };
+};
diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts
index 73117ef75f,53a272701c..ce0ef820c6
--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts
@@@ -14,55 -9,6 +14,57 @@@ import
/** Exactly one of the two names the user. */
export type TOnBehalfOfUser = { userId?: string; userEmail?: string };
+// Flat like a bundle service's create body, and like it, it also takes what inline services don't (another type's
+// fields, member-provided fields, OAuth) so the session service can refuse each by name.
+export type TAgentVaultInlineServiceInput = {
+ type: AgentVaultServiceType;
+ name?: string;
+ hostPattern?: string;
+ serverUrl?: string;
+ transport?: AgentVaultMcpTransport;
+ allowedMethods?: AgentVaultHttpMethod[] | null;
+ allowedPathPrefixes?: string[] | null;
++ // Accepted only to be refused by name: an inline MCP server can't be limited to some of its tools.
++ allowedTools?: string[] | null;
+ credential:
+ | {
+ type: AgentVaultCredentialType.Bearer;
+ headerName?: string;
+ headerPrefix?: string;
+ value: string;
+ memberProvidedFields?: string[];
+ }
+ | {
+ type: AgentVaultCredentialType.Basic;
+ username?: string;
+ password?: string;
+ memberProvidedFields?: string[];
+ }
+ | { type: AgentVaultCredentialType.Passthrough }
+ | { type: AgentVaultCredentialType.OAuth; authorizationId?: string };
+ customHeaders?: { name: string; prefix?: string; value: string }[];
+ substitutions?: { placeholder: string; surfaces: AgentVaultSubstitutionSurface[]; value: string }[];
+};
+
+/** An inline service as every read returns it: everything but its secrets. */
+export type TAgentVaultInlineServiceSummary = {
+ id: string;
+ // The name it was sent with, or its first host when it was sent without one.
+ name: string;
+ type: AgentVaultServiceType;
+ serverUrl: string | null;
+ transport: AgentVaultMcpTransport | null;
+ hostPattern: string;
+ allowedMethods: AgentVaultHttpMethod[] | null;
+ allowedPathPrefixes: string[] | null;
+ credential:
+ | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }
+ | { type: AgentVaultCredentialType.Basic }
+ | { type: AgentVaultCredentialType.Passthrough };
+ customHeaders: { name: string; prefix: string }[];
+ substitutions: { placeholder: string; surfaces: AgentVaultSubstitutionSurface[] }[];
+};
+
export type TMintSessionDTO = {
projectId: string;
ctx: TGenericPermission;
diff --cc backend/src/ee/services/agent-vault/AGENTS.md
index 2d6beb6c8e,5033c7383a..5a6141ffa4
--- a/backend/src/ee/services/agent-vault/AGENTS.md
+++ b/backend/src/ee/services/agent-vault/AGENTS.md
@@@ -198,47 -199,6 +199,49 @@@ is one `agent_vault_delegations` row pe
- **Delegation routes take no `AuthMode.OAUTH`.** The admin check reads the role, which a delegated token's scopes
don't narrow, and a delegation lets an identity act as other users.
+## Inline services
+
+An Agent Vault admin can send services with a session itself, without an access bundle or alongside one, for a caller
+that holds its own credentials and needs a host for one session only. The API calls them the session's `services` (on
+mint, on session reads and in the mint audit event); the code and the Sessions page say inline services, which is what
+tells them apart from a bundle's. They are rows of `agent_vault_session_inline_services` and belong to that session
+alone: nothing edits them, no bundle or other session reads them, and only resolve opens their secrets.
+
+- **Admin only, at mint and on every resolve.** Whoever starts the session decides which hosts it reaches and with
+ which credentials, an admin's call for a bundle's services too. It also keeps `service-hosts` meaningful: a proxy lets
+ through any host a session's services cover, so a member's inline service would open any host they chose. Resolve
+ sends inline services only while the session's owner (the identity, on an on-behalf-of session) is a live admin, so a
+ demotion keeps the bundle and drops the inline services until they are an admin again, the way a lost grant drops a
+ bundle.
+- **No value may wrap text in double braces, and resolve never expands one.** Whoever starts the session names its
+ hosts, so a variable reference would let them send any variable's value to a host of their choosing, and the stored
+ `{{<uuid>}}` form is refused by the same rule (`acceptsNoVariableReferences` on every value field). Resolve adds
+ inline services after `$expandVariableReferences` and `$applyPersonalValues`, so the rule doesn't rest on the refusal
+ alone.
+- **No member-provided fields and no OAuth.** Every value arrives with the mint, and an OAuth service needs a sign-in in
+ the UI and a refresh that writes the service row. The schema accepts both, hidden, so `prepareInlineServices` refuses
+ them by name, as a bundle service's create refuses fields its type doesn't take.
++- **No tool filtering.** An inline MCP server takes no `allowedTools`, and resolve sends it `allowedTools: null`, so
++ the proxy lets the agent call every tool on it, as it does for a bundle service with no list set.
+- **The name is optional.** An unnamed service goes by its first host (`inlineServiceDisplayName`), worked out on the
+ server only: resolve (so the proxy's messages and session logs), the audit log and the session responses all send
+ that name, so `name` is never null on the wire and the frontend shows it as is. Mint refuses a name, given or
+ fallen back to, that another inline service or a service in the session's bundle already goes by, so a name in a
+ session log always points at one service. Resolve sends `accessBundleName: null` for an inline service.
+- **The host rule of one bundle's services applies across the session**: two inline services covering the same pattern
+ are refused, and so is one covering a pattern the session's bundle covers. Mint checks it without the bundle lock, so
+ a later bundle edit can still create the overlap; resolve puts the bundle's services first, and the Go matcher breaks
+ a tie by slice order, so the bundle's service gets the host.
+- **Secrets go when the session ends; the rest stays.** The credential, custom header values and substitution values are
+ sealed together in `encryptedSecrets`, so deleting them is one write. The row keeps the name, type, hosts, rules,
+ credential type, header names and placeholders, since sessions are never deleted and the Sessions page shows what an
+ ended session could reach. Revoke deletes the secrets in its transaction, and the hourly `FrequentResourceCleanup`
+ (`deleteSecretsOfEndedSessions`) catches sessions that expired or lost their owner, matching `deriveSessionStatus`.
+ Neither writes the session row, so an ownerless session's `updatedAt` never moves. `ttl: never` is allowed, so such a
+ session keeps its secrets until it is revoked or its owner is deleted.
+- **A NULL `encryptedSecrets` means nothing to send only for a pass-through service with no custom headers or
+ substitutions.** On any other service it means the session ended, and resolve leaves the service out.
+
## Proxies
- There is no enrollment. Create and rotate return a proxy token (the non-expiring access JWT) and every proxy
diff --cc docs/documentation/platform/agent-vault/guides/daytona.mdx
index 1b9319df04,8c97357c40..e9aa1210d6
--- a/docs/documentation/platform/agent-vault/guides/daytona.mdx
+++ b/docs/documentation/platform/agent-vault/guides/daytona.mdx
@@@ -1092,7 -1076,7 +1076,7 @@@ To check which requests the agent made
### Network access from the agent's sandbox
- The agent's sandbox can only connect to the proxy's address on the network between the two sandboxes. With the **Service hosts only** traffic policy, the agent can reach two kinds of hosts through the proxy: the hosts of the services in the session's access bundle, and the proxy's exceptions.
-The agent's sandbox can only connect to the proxy's address on the network between the two sandboxes. Under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the agent's requests to any host on the internet. To allow only the hosts of the services in the session's access bundle, set the traffic policy to **Access bundle hosts only**, and add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++The agent's sandbox can only connect to the proxy's address on the network between the two sandboxes. Under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the agent's requests to any host on the internet. To allow only the hosts of the services in the session's access bundle, set the traffic policy to **Service hosts only**, and add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
### Compromised sandboxes
@@@ -1112,7 -1096,7 +1096,7 @@@ Each proxy's sandbox holds a copy of th
The session expired or was revoked. Set the session's `ttl` a few minutes longer than the proxy sandbox's time to live, so the session lasts as long as the sandboxes can run.
</Accordion>
<Accordion title="Requests to a host fail with a 403 from the start">
- The proxy's traffic policy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
- If the proxy's traffic policy is **Access bundle hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++ If the proxy's traffic policy is **Service hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
</Accordion>
</AccordionGroup>
diff --cc docs/documentation/platform/agent-vault/guides/docker.mdx
index 8e69da7ea7,2736f95aed..7012901000
--- a/docs/documentation/platform/agent-vault/guides/docker.mdx
+++ b/docs/documentation/platform/agent-vault/guides/docker.mdx
@@@ -213,7 -213,7 +213,7 @@@ To check which requests the agent made
### Network access from the agent's container
- The agent's container can't reach the internet. It can't look up hostnames on the internet either, because on an internal network, Docker only answers DNS lookups for the names of containers. With the **Service hosts only** traffic policy, the agent can reach two kinds of hosts through the proxy: the hosts of the services in the session's access bundle, and the proxy's exceptions.
-The agent's container can't reach the internet. It can't look up hostnames on the internet either, because on an internal network, Docker only answers DNS lookups for the names of containers. Under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the agent's requests to any host on the internet. To allow only the hosts of the services in the session's access bundle, set the traffic policy to **Access bundle hosts only**, and add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++The agent's container can't reach the internet. It can't look up hostnames on the internet either, because on an internal network, Docker only answers DNS lookups for the names of containers. Under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the agent's requests to any host on the internet. To allow only the hosts of the services in the session's access bundle, set the traffic policy to **Service hosts only**, and add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
The agent can still connect to services on the Docker host that listen on all of the host's addresses, such as `0.0.0.0`, through the gateway address of the run's network. To keep the agent away from a service on the host, have the service listen only on `127.0.0.1`, or block traffic from Docker's networks to the host with a firewall rule.
@@@ -239,7 -239,7 +239,7 @@@ If you think someone took control of th
The session expired before the agent finished. Set the session's `ttl` in the script longer than your longest run.
</Accordion>
<Accordion title="Requests to a host fail with a 403 from the start">
- The proxy's traffic policy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
- If the proxy's traffic policy is **Access bundle hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++ If the proxy's traffic policy is **Service hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
</Accordion>
<Accordion title="The agent says its API key is invalid">
The agent has only a placeholder, so the error is about the key in the access bundle. The proxy's log shows `decision=brokered` and `status=401` for the provider's host. Update the key in the access bundle's service for that provider, such as **Anthropic** for Claude Code.
diff --cc docs/documentation/platform/agent-vault/guides/e2b.mdx
index 0000000000,d613c6f768..fb039ea73b
mode 000000,100644..100644
--- a/docs/documentation/platform/agent-vault/guides/e2b.mdx
+++ b/docs/documentation/platform/agent-vault/guides/e2b.mdx
@@@ -1,0 -1,559 +1,559 @@@
+ ---
+ title: "Run agents in E2B sandboxes with Agent Vault"
+ sidebarTitle: "E2B"
+ icon: "/images/agent-vault-agents/e2b.svg"
+ description: "Send each E2B sandbox's traffic to an Agent Vault proxy over SOCKS5 so the agent never has access to a credential."
+ ---
+
+ import SandboxAgentVaultSetup from "/snippets/agent-vault/SandboxAgentVaultSetup.mdx";
+
+ [E2B sandboxes](https://e2b.dev/docs/sandbox) are isolated virtual machines you create from code to run an agent. The agent in a sandbox runs commands that a prompt can influence, so any API key you give the sandbox can leak through a [prompt injection](/documentation/platform/agent-vault/why-agent-vault).
+
+ With Agent Vault, you don't give the sandbox any API keys. E2B's [bring your own proxy](https://e2b.dev/docs/network/byop) option sends the sandbox's outbound connections to a SOCKS5 proxy you run. You run an Agent Vault [proxy](/documentation/platform/agent-vault/proxies) with its SOCKS5 port turned on, and the proxy attaches the real credential to requests for the APIs you allowed. E2B connects to the proxy from its own servers, not from inside the sandbox, so nothing in the sandbox is configured to use the proxy, and code in the sandbox can't send traffic that skips it.
+
+ ```mermaid
+ flowchart LR
+ orchestrator["Your code"]
+ subgraph e2b["E2B"]
+ agent["Sandbox<br/>(runs the agent)"]
+ host["E2B host<br/>(holds the session token)"]
+ end
+ proxy["Agent Vault proxy<br/>(SOCKS5 over TLS)"]
+ apis["api.anthropic.com<br/>api.github.com<br/>..."]
+ infisical["Infisical"]
+ orchestrator -->|"creates the sandbox"| e2b
+ orchestrator -->|"gets the CA and creates a session"| infisical
+ agent -->|"HTTP and HTTPS connections"| host
+ host -->|"SOCKS5 over TLS, with the session token"| proxy
+ proxy -->|"request with the credential"| apis
+ proxy -->|"fetches the credentials"| infisical
+ ```
+
+ For each run, your code does the following:
+
+ 1. [Gets the proxy's certificate authority (CA)](/api-reference/endpoints/agent-vault-proxies/get-ca) from Infisical
+ 2. [Creates an Agent Vault session](/api-reference/endpoints/agent-vault-sessions/create) for the run ([learn more about sessions](/documentation/platform/agent-vault/sessions))
+ 3. Creates a sandbox that sends its traffic to the proxy, with the session token as the SOCKS5 password
+ 4. Adds the proxy's CA to the sandbox's trust store, and runs the agent
+ 5. [Revokes the session](/api-reference/endpoints/agent-vault-sessions/revoke) and kills the sandbox when the agent finishes
+
+ One proxy serves every sandbox, so you set it up once.
+
+ <Accordion title="Why the proxy can be reachable from the internet">
+ E2B only connects to proxies that are reachable from the internet, so the proxy can't be on a private network. These parts of the setup protect the session tokens and the proxy:
+
+ - **TLS on the SOCKS5 port:** The SOCKS5 port only accepts TLS, so the session token and the traffic are encrypted on the way to the proxy
+ - **No token in the sandbox:** E2B holds the session token on its servers, so the agent can't read it
+ - **Short sessions:** Your code creates a session for each run and revokes it when the run ends, so a leaked token only works until then
+ - **A local HTTP port:** The proxy's HTTP port stays local to the proxy's machine, and only the SOCKS5 port is public
+ - **Private destinations blocked:** Through the SOCKS5 port, the proxy refuses requests to private and internal addresses, such as cloud metadata endpoints, unless a service in the session's access bundle names the host
+
+ You can also use a firewall to limit the SOCKS5 port to the Google Cloud address ranges of the regions your sandboxes run in, as [E2B describes](https://e2b.dev/docs/faq/egress-ip-ranges). E2B publishes no ranges for its AWS region, and other Google Cloud customers share the Google Cloud ranges, so the firewall adds to these protections rather than replacing them.
+ </Accordion>
+
+ ## Prerequisites
+
+ - The **Admin** role in [Agent Vault](/documentation/platform/agent-vault/access-control#product-membership)
+ - An [access bundle](/documentation/platform/agent-vault/access-bundles) with a service for each key the agent uses, including its model provider's key, such as **Anthropic** for Claude Code (see the [quickstart](/documentation/platform/agent-vault/quickstart))
+ - An [E2B](https://e2b.dev) account with [bring your own proxy](https://e2b.dev/docs/network/byop) turned on (E2B lists it as a private beta, so you may need to ask E2B to turn it on)
+ - An [E2B API key](https://e2b.dev/docs/api-key) in the `E2B_API_KEY` environment variable on the machine that runs your code
+ - The E2B SDK version 2.57.0 or later for your language: [Python](https://pypi.org/project/e2b/) (with [`requests`](https://pypi.org/project/requests/)) or [TypeScript](https://www.npmjs.com/package/e2b)
+ - A Linux machine or Kubernetes cluster to run the proxy, reachable from the internet, with a DNS name that points to it
+ - For the systemd setup, the [Infisical CLI](/cli/install) installed on that machine
+
+ ## Step 1: Set up Agent Vault
+
+ <SandboxAgentVaultSetup />
+
+ ## Step 2: Run the proxy on a public machine
+
+ Run the proxy where E2B can reach it from the internet, with its SOCKS5 port turned on. E2B runs sandboxes in Google Cloud's `us-west1` region by default, so a machine in or near that region adds the least latency to each request.
+
+ These commands start the proxy with its SOCKS5 port on port `1080`. With `--socks5-tls-name`, the proxy makes the port's TLS certificate from its CA for the DNS name you pass. Replace `<proxy-dns-name>` with the machine's DNS name, and `<your-instance-url>` with the URL of your Infisical instance:
+
+ <Tabs>
+ <Tab title="systemd">
+ 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`:
+
+ ```ini
+ [Unit]
+ Description=Infisical Agent Vault proxy
+ After=network-online.target
+ Wants=network-online.target
+
+ [Service]
+ EnvironmentFile=/etc/infisical/agent-vault-proxy.env
+ ExecStart=infisical agent-vault proxy --domain <your-instance-url> --listen-host 127.0.0.1 --socks5-port 1080 --socks5-tls-name <proxy-dns-name>
+ Restart=always
+
+ [Install]
+ WantedBy=multi-user.target
+ ```
+
+ `--listen-host 127.0.0.1` keeps the HTTP port local to the machine. Run `sudo systemctl enable --now agent-vault-proxy` to start the proxy now and every time the machine boots.
+ </Tab>
+ <Tab title="Docker">
+ ```bash
+ docker run -d --name agent-vault-proxy --restart unless-stopped \
+ -p 1080:1080 \
+ -v agent-vault-proxy:/etc/infisical/agent-vault \
+ -e INFISICAL_AGENT_VAULT_PROXY_TOKEN=<proxy-token> \
+ infisical/cli agent-vault proxy \
+ --domain <your-instance-url> \
+ --listen-host 127.0.0.1 \
+ --socks5-port 1080 \
+ --socks5-tls-name <proxy-dns-name>
+ ```
+
+ The command publishes only the SOCKS5 port, and `--listen-host 127.0.0.1` keeps the HTTP port, `17323`, from other containers on the same network.
+
+ From inside a container, the proxy can't see the host's own addresses, so it can't refuse requests to them. If the host has its public IP address on its network interface, such as on DigitalOcean or Hetzner, and runs other services that only a cloud firewall hides, add a firewall rule on the host that blocks the proxy's container from the host's public IP address.
+ </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>
+ - --listen-host
+ - 127.0.0.1
+ - --socks5-port
+ - "1080"
+ - --socks5-tls-name
+ - <proxy-dns-name>
+ envFrom:
+ - secretRef:
+ name: agent-vault-proxy
+ ports:
+ - containerPort: 1080
+ readinessProbe:
+ tcpSocket:
+ port: 1080
+ ---
+ apiVersion: v1
+ kind: Service
+ metadata:
+ name: agent-vault-proxy
+ spec:
+ type: LoadBalancer
+ selector:
+ app: agent-vault-proxy
+ ports:
+ - port: 1080
+ targetPort: 1080
+ ```
+
+ The Service exposes only the SOCKS5 port. Use a TCP (layer 4) load balancer, which passes the TLS connection through to the proxy. If the load balancer ends TLS itself, connections fail, because the SOCKS5 port only accepts TLS. Point `<proxy-dns-name>` at the load balancer's address.
+ </Tab>
+ </Tabs>
+
+ To check that the proxy is up, such as in a load balancer's health check, open a TCP connection to port `1080`.
+
+ When the proxy starts, it logs `agent-vault: proxy listening`, with the proxy's ID in the `proxyId` field, then `agent-vault: SOCKS5 listening`. To read the log, run `journalctl -u agent-vault-proxy` for systemd, `docker logs agent-vault-proxy` for Docker, or `kubectl logs deploy/agent-vault-proxy` for Kubernetes.
+
+ Copy the proxy's ID for [Step 4](#step-4-run-a-command-in-a-sandbox).
+
+ <Info>
+ To serve your own certificate on the SOCKS5 port instead, pass `--socks5-tls-cert` and `--socks5-tls-key` in place of `--socks5-tls-name`. Then change the `tls` setting in [Step 4](#step-4-run-a-command-in-a-sandbox) to match the certificate:
+
+ | Certificate on the SOCKS5 port | `tls` in your code |
+ | --- | --- |
+ | Made by the proxy, with `--socks5-tls-name` | The proxy's CA as `ca_cert` (`caCert` in TypeScript), as the code in Step 4 does |
+ | Yours, from a publicly trusted CA | `True` in Python, or `true` in TypeScript, so E2B uses its trust store |
+ | Yours, from a private CA | That CA's certificate as `ca_cert` (`caCert` in TypeScript) |
+
+ Learn more about the [SOCKS5 port's certificate](/documentation/platform/agent-vault/proxies#certificate-for-the-socks5-port).
+ </Info>
+
+ ## Step 3: Give your code the credentials
+
+ Set `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` and `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET` to the machine identity's client ID and client secret, in the environment of the code that creates your sandboxes. Your code never passes these credentials to a sandbox.
+
+ The proxy token stays on the proxy's machine, so your code doesn't need it.
+
+ ## Step 4: Run a command in a sandbox
+
+ This function runs one shell command in a new sandbox and returns the command's output. Replace the values at the top:
+
+ - `<access-bundle-name>`: your access bundle's name
+ - `<proxy-id>`: the proxy's ID from [Step 2](#step-2-run-the-proxy-on-a-public-machine)
+ - `<proxy-dns-name>`: the proxy machine's DNS name
+ - `https://app.infisical.com`: if you use EU Cloud or self-host Infisical, the URL of your instance
+
+ <CodeGroup>
+
+ ```python Python expandable
+ # run_in_sandbox.py
+ import os
+
+ import requests
+ from e2b import Sandbox
+
+ INFISICAL_URL = "https://app.infisical.com"
+ ACCESS_BUNDLE = "<access-bundle-name>"
+ PROXY_ID = "<proxy-id>"
+ PROXY_ADDRESS = "<proxy-dns-name>:1080"
+ TEMPLATE = "base"
+ SANDBOX_TIMEOUT = 15 * 60
+ SANDBOX_ENV = {}
+
+ CA_PATH = "/usr/local/share/ca-certificates/agent-vault-ca.crt"
+ # Points the tools that don't read the system trust store at the proxy's CA.
+ CA_ENV = {
+ name: CA_PATH
+ for name in ["SSL_CERT_FILE", "NODE_EXTRA_CA_CERTS", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "GIT_SSL_CAINFO", "DENO_CERT"]
+ }
+
+
+ def run_in_sandbox(command: str) -> str:
+ # The machine identity's credentials stay here and never enter the sandbox.
+ login = requests.post(
+ f"{INFISICAL_URL}/api/v1/auth/universal-auth/login",
+ json={
+ "clientId": os.environ["INFISICAL_UNIVERSAL_AUTH_CLIENT_ID"],
+ "clientSecret": os.environ["INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET"],
+ },
+ timeout=30,
+ )
+ login.raise_for_status()
+ headers = {"Authorization": f"Bearer {login.json()['accessToken']}"}
+
+ # Fetched on every run, because the CA changes when you rotate the proxy's token.
+ ca_response = requests.get(f"{INFISICAL_URL}/api/v1/agent-vault/proxies/{PROXY_ID}/ca", headers=headers, timeout=30)
+ ca_response.raise_for_status()
+ ca = ca_response.json()["ca"]["certificate"]
+
+ # One session per run. The ttl outlasts the sandbox's timeout, so the agent
+ # can't lose access mid-run.
+ created = requests.post(
+ f"{INFISICAL_URL}/api/v1/agent-vault/sessions",
+ headers=headers,
+ json={"accessBundles": [ACCESS_BUNDLE], "ttl": "20m"},
+ timeout=30,
+ )
+ created.raise_for_status()
+ session = created.json()["session"]
+
+ sandbox = None
+ try:
+ sandbox = Sandbox.create(
+ template=TEMPLATE,
+ timeout=SANDBOX_TIMEOUT,
+ envs={**CA_ENV, **SANDBOX_ENV},
+ network={
+ # E2B sends hostnames to the proxy, instead of IP addresses, only for
+ # traffic that a domain entry in allow_out lets through.
+ "allow_out": ["*"],
+ "deny_out": ["0.0.0.0/0"],
+ "egress_proxy": {
+ "address": PROXY_ADDRESS,
+ # The proxy ignores the username and reads the session token from the password.
+ "username": "x-agent-vault",
+ "password": session["token"],
+ "tls": {"ca_cert": ca},
+ },
+ },
+ )
+ sandbox.files.write("/tmp/agent-vault-ca.pem", ca)
+ sandbox.commands.run(
+ f"install -m 644 /tmp/agent-vault-ca.pem {CA_PATH} && update-ca-certificates",
+ user="root",
+ )
+ result = sandbox.commands.run(command, timeout=SANDBOX_TIMEOUT - 60)
+ return result.stdout
+ finally:
+ # Revoke first, so the session ends even if killing the sandbox fails.
+ try:
+ requests.post(
+ f"{INFISICAL_URL}/api/v1/agent-vault/sessions/{session['id']}/revoke",
+ headers=headers,
+ timeout=30,
+ ).raise_for_status()
+ finally:
+ if sandbox:
+ sandbox.kill()
+ ```
+
+ ```typescript TypeScript expandable
+ // runInSandbox.ts
+ import { Sandbox } from "e2b";
+
+ const INFISICAL_URL = "https://app.infisical.com";
+ const ACCESS_BUNDLE = "<access-bundle-name>";
+ const PROXY_ID = "<proxy-id>";
+ const PROXY_ADDRESS = "<proxy-dns-name>:1080";
+ const TEMPLATE = "base";
+ const SANDBOX_TIMEOUT_MS = 15 * 60 * 1000;
+ const SANDBOX_ENV: Record<string, string> = {};
+
+ const CA_PATH = "/usr/local/share/ca-certificates/agent-vault-ca.crt";
+ // Points the tools that don't read the system trust store at the proxy's CA.
+ const CA_ENV = Object.fromEntries(
+ ["SSL_CERT_FILE", "NODE_EXTRA_CA_CERTS", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "GIT_SSL_CAINFO", "DENO_CERT"].map(
+ (name) => [name, CA_PATH],
+ ),
+ );
+
+ async function infisical(
+ path: string,
+ { method = "POST", token, body }: { method?: string; token?: string; body?: unknown } = {},
+ ) {
+ const headers: Record<string, string> = {};
+ if (token) headers.Authorization = `Bearer ${token}`;
+ if (body !== undefined) headers["Content-Type"] = "application/json";
+ const response = await fetch(`${INFISICAL_URL}${path}`, {
+ method,
+ headers,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!response.ok) throw new Error(`Infisical returned ${response.status}: ${await response.text()}`);
+ return response.json();
+ }
+
+ export async function runInSandbox(command: string): Promise<string> {
+ // The machine identity's credentials stay here and never enter the sandbox.
+ const { accessToken } = await infisical("/api/v1/auth/universal-auth/login", {
+ body: {
+ clientId: process.env.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID,
+ clientSecret: process.env.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET,
+ },
+ });
+
+ // Fetched on every run, because the CA changes when you rotate the proxy's token.
+ const { ca } = await infisical(`/api/v1/agent-vault/proxies/${PROXY_ID}/ca`, { method: "GET", token: accessToken });
+
+ // One session per run. The ttl outlasts the sandbox's timeout, so the agent
+ // can't lose access mid-run.
+ const { session } = await infisical("/api/v1/agent-vault/sessions", {
+ token: accessToken,
+ body: { accessBundles: [ACCESS_BUNDLE], ttl: "20m" },
+ });
+
+ let sandbox: Sandbox | undefined;
+ try {
+ sandbox = await Sandbox.create(TEMPLATE, {
+ timeoutMs: SANDBOX_TIMEOUT_MS,
+ envs: { ...CA_ENV, ...SANDBOX_ENV },
+ network: {
+ // E2B sends hostnames to the proxy, instead of IP addresses, only for
+ // traffic that a domain entry in allowOut lets through.
+ allowOut: ["*"],
+ denyOut: ["0.0.0.0/0"],
+ egressProxy: {
+ address: PROXY_ADDRESS,
+ // The proxy ignores the username and reads the session token from the password.
+ username: "x-agent-vault",
+ password: session.token,
+ tls: { caCert: ca.certificate },
+ },
+ },
+ });
+ await sandbox.files.write("/tmp/agent-vault-ca.pem", ca.certificate);
+ await sandbox.commands.run(`install -m 644 /tmp/agent-vault-ca.pem ${CA_PATH} && update-ca-certificates`, {
+ user: "root",
+ });
+ const result = await sandbox.commands.run(command, { timeoutMs: SANDBOX_TIMEOUT_MS - 60_000 });
+ return result.stdout;
+ } finally {
+ // Revoke first, so the session ends even if killing the sandbox fails.
+ try {
+ await infisical(`/api/v1/agent-vault/sessions/${session.id}/revoke`, { token: accessToken });
+ } finally {
+ await sandbox?.kill();
+ }
+ }
+ }
+ ```
+
+ </CodeGroup>
+
+ The function adds the proxy's CA to the sandbox's system trust store, and sets the variables that [`agent-vault run`](/documentation/platform/agent-vault/proxies#certificate-trust) sets for the tools that don't read that store.
+
+ To keep the same CA when you rotate the proxy's token, [use your own CA](/documentation/platform/agent-vault/proxies#use-your-own-certificate-authority). Infisical doesn't have your own CA, so read its certificate from a file instead of [getting it from Infisical](/api-reference/endpoints/agent-vault-proxies/get-ca).
+
+ For more about creating sessions from code, see [Create sessions with the API](/documentation/platform/agent-vault/sessions-api).
+
+ ## Step 5: Verify it works
+
+ Call the function with a request to an API in the access bundle. This example calls the Anthropic API, which returns a list of models only if the request has an API key. If your access bundle doesn't have an **Anthropic** service, replace the URL with the URL of an API that the access bundle has a service for:
+
+ <CodeGroup>
+
+ ```python Python
+ # main.py
+ from run_in_sandbox import run_in_sandbox
+
+ print(run_in_sandbox("curl -s https://api.anthropic.com/v1/models -H 'anthropic-version: 2023-06-01'"))
+ ```
+
+ ```typescript TypeScript
+ // main.ts
+ import { runInSandbox } from "./runInSandbox.js";
+
+ console.log(await runInSandbox("curl -s https://api.anthropic.com/v1/models -H 'anthropic-version: 2023-06-01'"));
+ ```
+
+ </CodeGroup>
+
+ The response lists Anthropic's models, even though the sandbox has no Anthropic API key and no settings for the proxy.
+
+ <Check>
+ Each run now gets its own sandbox and session. The session token never enters the sandbox, and your code revokes the session when the run ends.
+ </Check>
+
+ To check which requests the sandbox made, [set up session logs](/documentation/platform/agent-vault/session-logs), then [view the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) in Agent Vault. Requests that got a credential have the outcome **Brokered**.
+
+ ## Step 6: Run an agent
+
+ To run an agent such as Claude Code, start the sandbox from an E2B template that has the agent installed:
+
+ <Steps>
+ <Step>
+ Set `TEMPLATE` at the top of the code from Step 4 to the template's name. For Claude Code, use `claude`, a [template E2B provides](https://e2b.dev/docs/agents/claude-code) with Claude Code installed. For another agent, [build a template](https://e2b.dev/docs/template/quickstart) with the agent installed.
+ </Step>
+ <Step>
+ Add the agent's settings to `SANDBOX_ENV`. For Claude Code, add these:
+
+ <CodeGroup>
+
+ ```python Python
+ SANDBOX_ENV = {
+ # Claude Code won't start without a key; the proxy replaces this one.
+ "ANTHROPIC_API_KEY": "agent-vault",
+ # Skips Claude Code's update checks and telemetry. If the proxy only allows
+ # access bundle hosts, it blocks them.
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
+ "DISABLE_AUTOUPDATER": "1",
+ }
+ ```
+
+ ```typescript TypeScript
+ const SANDBOX_ENV: Record<string, string> = {
+ // Claude Code won't start without a key; the proxy replaces this one.
+ ANTHROPIC_API_KEY: "agent-vault",
+ // Skips Claude Code's update checks and telemetry. If the proxy only allows
+ // access bundle hosts, it blocks them.
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
+ DISABLE_AUTOUPDATER: "1",
+ };
+ ```
+
+ </CodeGroup>
+ </Step>
+ <Step>
+ Call the function with the agent's non-interactive command, such as `claude -p 'Reply with the word OK.' --permission-mode bypassPermissions`.
+ </Step>
+ </Steps>
+
+ The agent calls its APIs the same way it does without Agent Vault, and E2B sends the connections to the proxy, so the agent doesn't need `HTTPS_PROXY` or `infisical agent-vault run`.
+
+ ## Security considerations
+
+ ### Network access from the sandbox
+
+ The sandbox can look up hostnames over DNS at `8.8.8.8`, which E2B lets through without the proxy, so an agent can still send data out in the names it looks up, though never a credential. To limit DNS, see [E2B's DNS settings](https://e2b.dev/docs/network/internet-access#dns-when-you-filter-by-domain).
+
+ Every other connection goes through the proxy:
+
+ - **Hosts through the proxy:** under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the sandbox's requests to any host on the internet
+ - **Ports:** E2B only sends connections on ports `80` and `443` to the proxy, so the sandbox can't reach a service on any other port
+
-To allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Access bundle hosts only**. Add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++To allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Service hosts only**. Add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
+
+ ### Compromised sandboxes or leaked tokens
+
+ The session token is in your code and in E2B's settings for the sandbox, not in the sandbox. If you think a session token leaked, [revoke the session](/documentation/platform/agent-vault/sessions#revoke-a-session).
+
+ The proxy token is only on the proxy's machine. If you think someone took control of that machine, [rotate the proxy's token](/documentation/platform/agent-vault/proxies#rotate-a-proxys-token).
+
+ ## Troubleshooting
+
+ <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. Run `which infisical` to find your CLI's path. In `/etc/systemd/system/agent-vault-proxy.service`, replace `infisical` at the start of the `ExecStart=` line with that path, then reload and restart the proxy:
+
+ ```bash
+ sudo systemctl daemon-reload
+ sudo systemctl restart agent-vault-proxy
+ ```
+ </Accordion>
+ <Accordion title="Requests fail with a certificate error, or reach the API without a credential">
+ E2B sent the proxy an IP address instead of a hostname, so HTTPS requests fail with a certificate error, and the proxy can't match the request to a service. The proxy's log shows `closed a SOCKS5 connection the proxy can't handle` with a TLS handshake error for the host's IP address.
+
+ E2B only sends hostnames for traffic that a domain entry allows, so create the sandbox with `allow_out` set to `["*"]` and `deny_out` set to `["0.0.0.0/0"]`, as the function in [Step 4](#step-4-run-a-command-in-a-sandbox) does.
+ </Accordion>
+ <Accordion title="Connections from the sandbox fail right away">
+ The proxy refused the connection before any request. Check the proxy's log for one of these lines:
+
+ - `agent-vault: refused, the session is no longer valid`: the session expired or was revoked
+ - `agent-vault: refused, Infisical rejected this proxy's token`: someone rotated or revoked the proxy's token, so restart the proxy with the new token
+ - `agent-vault: refused, the session could not be resolved`: the proxy couldn't reach Infisical to check the session
+ - `agent-vault: a client spoke plain SOCKS5 to the TLS port`: the sandbox's `egress_proxy` has no `tls` setting
+
+ If none of these lines appears, the password might not be a session token, or E2B might not trust the SOCKS5 port's certificate. Start the proxy with `--log-level debug` to log these refusals too.
+ </Accordion>
+ <Accordion title="Requests fail with a 403 partway through a run">
+ The session expired or was revoked while the sandbox was running. Set the session's `ttl` a few minutes longer than the sandbox's timeout, so the session lasts as long as the sandbox can run.
+ </Accordion>
+ <Accordion title="Requests to a host fail with a 403 from the start">
- If the proxy's traffic policy is **Access bundle hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++ If the proxy's traffic policy is **Service hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
+
+ If the 403 says `the destination is a private or internal address`, the host resolves to an internal address, such as a private network or the proxy's own machine. The SOCKS5 port refuses those for every host that no service covers, including exceptions. Add a service for the host, or start the proxy with `--socks5-allow-private-destinations`.
+ </Accordion>
+ <Accordion title="A service on a port other than 80 or 443 doesn't work">
+ E2B only sends connections on ports `80` and `443` to the proxy. Use the service's HTTPS endpoint on port `443` instead.
+ </Accordion>
+ <Accordion title="A tool in the sandbox rejects the proxy's certificate">
+ The tool doesn't read the system trust store or the variables the function sets. Java programs use their own keystore, and some Rust programs have a built-in certificate list. Add the proxy's CA to the tool's own trust settings.
+ </Accordion>
+ <Accordion title="The sandbox's traffic stops going through the proxy">
+ Updating a running sandbox's network settings with `update_network` (`updateNetwork` in TypeScript) replaces all of them. If the update doesn't include `egress_proxy`, E2B sends the sandbox's traffic out directly. Include the same `egress_proxy`, with its `tls` setting, in every update.
+ </Accordion>
+ <Accordion title="Getting the CA from Infisical fails with a 409">
+ The proxy serves your own CA, which Infisical doesn't have. [With your own CA](/documentation/platform/agent-vault/proxies#use-your-own-certificate-authority), read the certificate you passed with `--ca-cert` from a file instead.
+ </Accordion>
+ </AccordionGroup>
+
+ ## Next steps
+
+ <CardGroup cols={2}>
+ <Card title="Proxies" icon="server" href="/documentation/platform/agent-vault/proxies#accept-connections-over-socks5">
+ Learn more about the proxy's SOCKS5 port and its settings.
+ </Card>
+ <Card title="Session logs" icon="list" href="/documentation/platform/agent-vault/session-logs">
+ Record every request an agent makes during a session.
+ </Card>
+ </CardGroup>
diff --cc docs/documentation/platform/agent-vault/guides/kubernetes-setup.mdx
index 0000000000,f7f3f6e959..fae500d157
mode 000000,100644..100644
--- a/docs/documentation/platform/agent-vault/guides/kubernetes-setup.mdx
+++ b/docs/documentation/platform/agent-vault/guides/kubernetes-setup.mdx
@@@ -1,0 -1,466 +1,466 @@@
+ ---
+ title: "Set up Agent Vault on Kubernetes"
+ sidebarTitle: "Setup"
+ description: "Deploy the Agent Vault proxy in your cluster, restrict agent pods to it, and start each agent with its own session."
+ ---
+
+ import SandboxAgentVaultSetup from "/snippets/agent-vault/SandboxAgentVaultSetup.mdx";
+
+ This guide deploys an Agent Vault [proxy](/documentation/platform/agent-vault/proxies) in its own namespace, locks a namespace of agent pods to it, and starts each agent with its own [session](/documentation/platform/agent-vault/sessions).
+
+ <Note>
+ Before you start, choose an [isolation level](/documentation/platform/agent-vault/guides/kubernetes#choose-an-isolation-level) for agent pods: the standard runtime, gVisor, or Kata Containers. For gVisor or Kata, your cluster needs a RuntimeClass for that runtime. The [Kubernetes overview](/documentation/platform/agent-vault/guides/kubernetes) also explains why each piece runs where it does.
+ </Note>
+
+ ## Prerequisites
+
+ - The **Admin** role in [Agent Vault](/documentation/platform/agent-vault/access-control#product-membership)
+ - An [access bundle](/documentation/platform/agent-vault/access-bundles) with a service for each key the agent uses, including its model provider's key, such as **Anthropic** for Claude Code (see the [quickstart](/documentation/platform/agent-vault/quickstart))
+ - A Kubernetes cluster whose network plugin enforces network policies, such as [Cilium](https://cilium.io) or [Calico](https://www.tigera.io/project-calico/)
+ - [`curl`](https://curl.se), [`jq`](https://jqlang.org), and [`openssl`](https://openssl-library.org) on the machine where you run the script in Step 6
+
+ ## Step 1: Set up Agent Vault
+
+ <SandboxAgentVaultSetup />
+
+ ## Step 2: Deploy the proxy
+
+ Save this manifest as `agent-vault-proxy.yaml` and apply it to your cluster. It creates the `agent-vault` namespace and runs the proxy in it:
+
+ ```yaml expandable
+ apiVersion: v1
+ kind: Namespace
+ metadata:
+ name: agent-vault
+ labels:
+ pod-security.kubernetes.io/enforce: restricted
+ ---
+ apiVersion: apps/v1
+ kind: Deployment
+ metadata:
+ name: agent-vault-proxy
+ namespace: agent-vault
+ spec:
+ replicas: 2
+ selector:
+ matchLabels:
+ app: agent-vault-proxy
+ template:
+ metadata:
+ labels:
+ app: agent-vault-proxy
+ spec:
+ automountServiceAccountToken: false
+ securityContext:
+ runAsNonRoot: true
+ runAsUser: 1000
+ seccompProfile:
+ type: RuntimeDefault
+ containers:
+ - name: agent-vault-proxy
+ image: infisical/cli
+ args: ["agent-vault", "proxy", "--domain", "https://app.infisical.com"]
+ envFrom:
+ - secretRef:
+ name: agent-vault-proxy
+ env:
+ # The proxy saves its cache under the home directory.
+ - name: HOME
+ value: /tmp
+ ports:
+ - containerPort: 17323
+ readinessProbe:
+ httpGet:
+ path: /_agent-vault/ca
+ port: 17323
+ securityContext:
+ allowPrivilegeEscalation: false
+ readOnlyRootFilesystem: true
+ capabilities:
+ drop: ["ALL"]
+ volumeMounts:
+ - name: tmp
+ mountPath: /tmp
+ volumes:
+ - name: tmp
+ emptyDir: {}
+ ---
+ apiVersion: v1
+ kind: Service
+ metadata:
+ name: agent-vault-proxy
+ namespace: agent-vault
+ spec:
+ selector:
+ app: agent-vault-proxy
+ ports:
+ - port: 17323
+ targetPort: 17323
+ ---
+ # Only agent pods can connect. The proxy can reach DNS and public HTTP and HTTPS
+ # hosts, but not private networks or your cloud's metadata service.
+ apiVersion: networking.k8s.io/v1
+ kind: NetworkPolicy
+ metadata:
+ name: agent-vault-proxy
+ namespace: agent-vault
+ spec:
+ podSelector:
+ matchLabels:
+ app: agent-vault-proxy
+ policyTypes: [Ingress, Egress]
+ ingress:
+ - from:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: agents
+ ports:
+ - port: 17323
+ egress:
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: kube-system
+ podSelector:
+ matchLabels:
+ k8s-app: kube-dns
+ ports:
+ - protocol: UDP
+ port: 53
+ - protocol: TCP
+ port: 53
+ - to:
+ - ipBlock:
+ cidr: 0.0.0.0/0
+ except:
+ - 10.0.0.0/8
+ - 100.64.0.0/10
+ - 169.254.0.0/16
+ - 172.16.0.0/12
+ - 192.168.0.0/16
+ ports:
+ - port: 443
+ - port: 80
+ ```
+
+ - **Instance URL:** if you use EU Cloud or self-host Infisical, replace `https://app.infisical.com` with `https://eu.infisical.com` or the URL of your self-hosted instance
+ - **Egress:** the proxy can only reach public addresses on ports 443 and 80, so add an egress rule for anything else, such as a self-hosted Infisical instance on a private address or a service at `api.example.com:8443`
+ - **DNS:** this policy and the one in Step 3 allow DNS only to `k8s-app: kube-dns` pods in `kube-system`, so change both if your DNS runs elsewhere, such as a node-local DNS cache or OpenShift's `openshift-dns`
+
+ ### Store the proxy token
+
+ Store the proxy token in a Secret named `agent-vault-proxy` in the `agent-vault` namespace, under the key `INFISICAL_AGENT_VAULT_PROXY_TOKEN`. The proxy's pods start once the Secret exists.
+
+ On the **Proxies** page in Agent Vault, the proxy's status changes to **Healthy** once it connects. Both replicas use the same token and certificate authority, and the Service spreads connections across them ([high availability](/documentation/platform/agent-vault/proxies#high-availability)).
+
+ ## Step 3: Create the agents namespace
+
+ Save this manifest as `agents-namespace.yaml` and apply it to your cluster. It creates the `agents` namespace and blocks all traffic to and from its pods, except DNS lookups and connections to the proxy:
+
+ ```yaml expandable
+ apiVersion: v1
+ kind: Namespace
+ metadata:
+ name: agents
+ labels:
+ pod-security.kubernetes.io/enforce: restricted
+ ---
+ apiVersion: networking.k8s.io/v1
+ kind: NetworkPolicy
+ metadata:
+ name: agents-to-proxy-only
+ namespace: agents
+ spec:
+ podSelector: {}
+ policyTypes: [Ingress, Egress]
+ egress:
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: kube-system
+ podSelector:
+ matchLabels:
+ k8s-app: kube-dns
+ ports:
+ - protocol: UDP
+ port: 53
+ - protocol: TCP
+ port: 53
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: agent-vault
+ podSelector:
+ matchLabels:
+ app: agent-vault-proxy
+ ports:
+ - port: 17323
+ ```
+
+ The `restricted` [Pod Security Standard](https://kubernetes.io/docs/concepts/security/pod-security-standards/) refuses pods that run as root, keep Linux capabilities, or can raise their privileges. The [agent pod](#define-the-agents-pod) in Step 6 meets it.
+
+ ## Step 4: Set up your orchestrator
+
+ Your orchestrator starts each agent run, and it can be a script, a CI pipeline, a job runner, or a Kubernetes controller. Run it outside the `agents` namespace, so agent pods can't reach it.
+
+ ### Give your orchestrator the machine identity's credentials
+
+ Set the client ID and client secret of the machine identity from [Step 1](#step-1-set-up-agent-vault) in the environment where your orchestrator runs:
+
+ ```bash
+ export INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id>
+ export INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret>
+ ```
+
+ <Tip>
+ If your orchestrator runs in a Kubernetes cluster whose API server Infisical can reach, use [Kubernetes Auth](/documentation/platform/identities/kubernetes-auth) instead, so it logs in with its service account token and has no client secret to store.
+ </Tip>
+
+ ### Allow the orchestrator to start agent pods
+
+ Save this manifest as `agent-orchestrator-role.yaml` and apply it to your cluster, then bind the role to the service account or user that your orchestrator runs as. The role only applies in the `agents` namespace:
+
+ ```yaml
+ apiVersion: rbac.authorization.k8s.io/v1
+ kind: Role
+ metadata:
+ name: agent-orchestrator
+ namespace: agents
+ rules:
+ - apiGroups: [""]
+ resources: [pods]
+ verbs: [create, get, list, watch, delete]
+ - apiGroups: [""]
+ resources: [secrets]
+ verbs: [create, get, delete]
+ - apiGroups: [""]
+ resources: [pods/log]
+ verbs: [get]
+ ```
+
+ ## Step 5: Build the agent's image
+
+ Build an image from this Dockerfile and push it to a registry your cluster can pull from:
+
+ ```dockerfile
+ # Dockerfile
+ FROM node:24-bookworm-slim
+ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
+ RUN npm install -g @infisical/cli @anthropic-ai/claude-code
+ USER node
+ WORKDIR /home/node
+ ENTRYPOINT ["infisical", "agent-vault", "run", "--telemetry=false", "--"]
+ CMD ["claude", "-p", "--permission-mode", "bypassPermissions"]
+ ```
+
+ - **The `node` user:** the `restricted` Pod Security Standard refuses pods that run as root, and Claude Code won't skip its permission prompts as root, so the agent runs as the image's `node` user
+ - **The entrypoint:** `infisical agent-vault run` fetches the proxy's certificate, sets the proxy and certificate trust variables, and starts the agent's command after `--`
+ - **`curl`:** the checks in [Step 7](#step-7-verify-it-works) run it in the agent's pod
+
+ ## Step 6: Run an agent
+
+ ### Define the agent's pod
+
+ Save this manifest as `agent-pod.yaml`. The script in the next step starts a pod from it for each run:
+
+ ```yaml expandable
+ apiVersion: v1
+ kind: Pod
+ metadata:
+ # Leave <run-id> as is. The script replaces it with a unique ID for each run.
+ name: agent-<run-id>
+ namespace: agents
+ spec:
+ # The isolation level. For gVisor or Kata, uncomment this line and set it to
+ # your cluster's RuntimeClass, such as gvisor or kata-qemu.
+ # runtimeClassName: gvisor
+ automountServiceAccountToken: false
+ restartPolicy: Never
+ # Stops a stuck agent after 30 minutes, so its session doesn't stay open.
+ activeDeadlineSeconds: 1800
+ securityContext:
+ runAsNonRoot: true
+ # The node user's ID in the image from Step 5.
+ runAsUser: 1000
+ seccompProfile:
+ type: RuntimeDefault
+ containers:
+ - name: agent
+ # The image you pushed in Step 5.
+ image: <agent-image>
+ # The agent's command, one list item per argument. The image's entrypoint
+ # starts it through infisical agent-vault run. Replace <prompt> with the
+ # agent's task, such as "Fix the failing test".
+ args:
+ - claude
+ - -p
+ - --permission-mode
+ - bypassPermissions
+ - <prompt>
+ # INFISICAL_AGENT_VAULT_SESSION_TOKEN, which the script in the next step creates.
+ envFrom:
+ - secretRef:
+ name: agent-<run-id>
+ env:
+ - name: INFISICAL_AGENT_VAULT_PROXY_ADDRESS
+ value: agent-vault-proxy.agent-vault.svc.cluster.local:17323
+ # Claude Code won't start without a key; the proxy replaces this one.
+ - name: ANTHROPIC_API_KEY
+ value: agent-vault
+ # Node.js 24 or later: make the built-in fetch read HTTPS_PROXY.
+ - name: NODE_USE_ENV_PROXY
+ value: "1"
+ securityContext:
+ allowPrivilegeEscalation: false
+ capabilities:
+ drop: ["ALL"]
+ resources:
+ limits:
+ cpu: "1"
+ memory: 1Gi
+ ```
+
+ Remove the real API keys from your agent's configuration. If an SDK won't start without a key, pass a placeholder such as `agent-vault` instead, as in [Connect your own agent](/documentation/platform/agent-vault/guides/custom-agent#step-3-replace-the-api-keys-with-placeholders).
+
+ ### Start the agent with a new session
+
+ This script is a minimal orchestrator that runs one agent with its own session. Replace `<access-bundle-name>` with your access bundle's name, and `https://app.infisical.com` with your instance's URL if you don't use US Cloud:
+
+ ```bash expandable
+ set -euo pipefail
+
+ INFISICAL_URL=https://app.infisical.com
+ # Logs in with Universal Auth. For Kubernetes Auth, call
+ # /api/v1/auth/kubernetes-auth/login with {"identityId", "jwt"} instead, where
+ # jwt is your orchestrator's service account token. The identity's allowed
+ # namespaces must include the orchestrator's namespace.
+ ACCESS_TOKEN=$(curl -fsS -X POST "$INFISICAL_URL/api/v1/auth/universal-auth/login" \
+ -H "Content-Type: application/json" \
+ -d "{\"clientId\": \"$INFISICAL_UNIVERSAL_AUTH_CLIENT_ID\", \"clientSecret\": \"$INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET\"}" \
+ | jq -r .accessToken)
+ # Unique per run, so runs started at the same time don't share names.
+ RUN_ID=$(date +%s)-$(openssl rand -hex 3)
+ echo "Run ID: $RUN_ID"
+
+ # One session per run. The ttl outlasts the pod's 30-minute deadline, so the
+ # agent can't lose access mid-run.
+ SESSION=$(curl -fsS -X POST "$INFISICAL_URL/api/v1/agent-vault/sessions" \
+ -H "Authorization: Bearer $ACCESS_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d "{\"accessBundles\": [\"<access-bundle-name>\"], \"ttl\": \"35m\", \"label\": \"kubernetes run $RUN_ID\"}")
+ SESSION_ID=$(echo "$SESSION" | jq -r .session.id)
+
+ cleanup() {
+ # Revoke first, so the session ends even if deleting the pod fails.
+ curl -fsS -X POST "$INFISICAL_URL/api/v1/agent-vault/sessions/$SESSION_ID/revoke" \
+ -H "Authorization: Bearer $ACCESS_TOKEN" > /dev/null \
+ || echo "Couldn't revoke session $SESSION_ID. Revoke it in Agent Vault." >&2
+ kubectl -n agents delete "pod/agent-$RUN_ID" "secret/agent-$RUN_ID" --ignore-not-found
+ }
+ trap cleanup EXIT
+ # Bash skips the EXIT trap when it's killed, such as when CI cancels a job.
+ trap 'exit 143' TERM INT
+
+ # The token goes through stdin, so it doesn't appear in the process list.
+ echo "$SESSION" | jq -r '"INFISICAL_AGENT_VAULT_SESSION_TOKEN=" + .session.token' \
+ | kubectl -n agents create secret generic "agent-$RUN_ID" --from-env-file=/dev/stdin
+
+ sed "s/<run-id>/$RUN_ID/g" agent-pod.yaml | kubectl apply -f -
+
+ not_started() {
+ echo "The agent's pod didn't start:" >&2
+ kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.phase} {.status.containerStatuses[0].state.waiting.reason} {.status.containerStatuses[0].state.waiting.message}{.status.conditions[?(@.reason=="Unschedulable")].message}{"\n"}' >&2
+ exit 1
+ }
+ # kubectl logs returns at once for a pod that isn't on a node yet, so wait for
+ # the scheduler first.
+ kubectl -n agents wait --for=condition=PodScheduled --timeout=2m "pod/agent-$RUN_ID" > /dev/null || not_started
+ # Wait up to 2 minutes for the container to start, then follow its output until
+ # the agent exits. In the background, so a canceled script cleans up right away
+ # instead of after the agent exits.
+ kubectl -n agents logs -f --pod-running-timeout=2m "agent-$RUN_ID" &
+ if ! wait $!; then
+ # The container started, so kubectl stopped following because the script was canceled.
+ [ -z "$(kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.containerStatuses[0].state.waiting}')" ] && exit 130
+ not_started
+ fi
+
+ # Exit with the agent's exit code.
+ EXIT_CODE=""
+ until [ -n "$EXIT_CODE" ]; do
+ sleep 1
+ EXIT_CODE=$(kubectl -n agents get pod "agent-$RUN_ID" -o jsonpath='{.status.containerStatuses[0].state.terminated.exitCode}')
+ done
+ exit "$EXIT_CODE"
+ ```
+
+ Your own orchestrator can make the same [login](/api-reference/endpoints/universal-auth/login), [create](/api-reference/endpoints/agent-vault-sessions/create), and [revoke](/api-reference/endpoints/agent-vault-sessions/revoke) calls in any language, as in [Create sessions with the API](/documentation/platform/agent-vault/sessions-api). For Kubernetes Auth, use the [Kubernetes Auth login](/api-reference/endpoints/kubernetes-auth/login) instead.
+
+ ## Step 7: Verify it works
+
+ While an agent runs, check its traffic as a cluster admin. Replace `<run-id>` with the run ID the script printed, and `<api-host>` with a host in your access bundle:
+
+ ```bash
+ # Through the proxy: returns the API's own status code, such as 200 or 401
+ kubectl -n agents exec agent-<run-id> -- infisical agent-vault run -- \
+ curl -s -o /dev/null -w '%{http_code}\n' https://<api-host>
+
-# Not in the access bundle: returns 200 without a credential, or 403 under Access bundle hosts only
++# Not in the access bundle: returns 200 without a credential, or 403 under Service hosts only
+ kubectl -n agents exec agent-<run-id> -- infisical agent-vault run -- \
+ curl -s -o /dev/null -w '%{http_code}\n' https://example.com
+
+ # Around the proxy: the network policy blocks it, so curl times out
+ kubectl -n agents exec agent-<run-id> -- curl -s --max-time 5 https://example.com
+ ```
+
+ In Agent Vault, find the session under **Sessions** > **All Sessions** by its label, `kubernetes run <run-id>`. It's **Active** while the agent runs and **Revoked** after the script exits. [View the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to see each request the agent made.
+
+ <Check>
+ Your agents now run in pods that contain only a session token, can only connect to the proxy, and lose access when the session is revoked.
+ </Check>
+
+ ## Security considerations
+
-- **Hosts through the proxy:** agent pods can only connect to the proxy and DNS, but under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards their requests to any host its network policy allows (to allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Access bundle hosts only** and add any other hosts the agents need to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions))
++- **Hosts through the proxy:** agent pods can only connect to the proxy and DNS, but under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards their requests to any host its network policy allows (to allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Service hosts only** and add any other hosts the agents need to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions))
+ - **DNS:** agent pods still need DNS to find the proxy, and DNS lookups can carry data out of the pod, so a network policy doesn't close every channel
+ - **APIs that echo requests:** if an endpoint returns the request's headers in its response, such as an echo or debug endpoint, the response exposes the credential that the proxy attached, so limit each service to the [methods and paths](/documentation/platform/agent-vault/http-apis#methods-and-paths) the agent needs
+ - **Revoking a session:** the proxy stops attaching credentials for a revoked session within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval)
+ - **Several teams:** a proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy) and exceptions apply to every agent that uses it, so give each team or customer its own proxy and agents namespace if they need different access
+ - **Unsupported connections:** WebSocket connections and clients that only speak HTTP/2, such as gRPC clients, fail through the proxy (see [Supported connections](/documentation/platform/agent-vault/proxies#supported-connections))
+
+ ## Troubleshooting
+
+ <AccordionGroup>
+ <Accordion title="Agent or proxy pods can't resolve hostnames">
+ The network policies allow DNS only to pods labeled `k8s-app: kube-dns` in `kube-system`. If your cluster's DNS runs elsewhere, such as a node-local DNS cache or OpenShift's `openshift-dns`, change the DNS rule in both network policies to match it. Until then, the proxy never becomes ready, and `infisical agent-vault run` can't find the proxy.
+ </Accordion>
+ <Accordion title="Requests through the proxy time out">
+ The proxy's network policy blocks the host or port. It allows only ports 443 and 80 on public addresses, so add an egress rule for a private address or another port, as [Step 2](#step-2-deploy-the-proxy) describes.
+ </Accordion>
+ <Accordion title="The agent reaches the internet without going through the proxy">
+ Your cluster's network plugin doesn't enforce network policies, so Kubernetes accepts the policies but nothing applies them. Flannel, the default network plugin in k3s, is one example. Install a network plugin that enforces policies, such as Cilium or Calico.
+ </Accordion>
+ <Accordion title="Requests fail with a certificate error">
+ The agent's HTTP client doesn't trust the proxy's certificate. Check that the agent starts through `infisical agent-vault run`, as the [image's entrypoint](#step-5-build-the-agents-image) does, and that its HTTP client reads one of the [certificate trust](/documentation/platform/agent-vault/proxies#certificate-trust) variables.
+ </Accordion>
+ <Accordion title="The proxy returns 403 with &quot;host blocked by policy&quot;">
+ The proxy's traffic policy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
+ </Accordion>
+ <Accordion title="Kata pods stay in ContainerCreating or fail to start">
+ The node doesn't have hardware virtualization. Run `ls /dev/kvm` on the node; if the file doesn't exist, schedule Kata pods on nodes that support it (see [Choose an isolation level](/documentation/platform/agent-vault/guides/kubernetes#choose-an-isolation-level)).
+ </Accordion>
+ <Accordion title="On Kata, output from kubectl exec stops early">
+ If you send input to `kubectl exec -i` and then close it, Kata ends the command's output stream right away, while the command keeps running. Anything the command prints after that is lost. To run commands in a Kata pod, pass the input as an argument or in a file instead of on stdin, or start the agent as the pod's own command, as this guide does.
+ </Accordion>
+ </AccordionGroup>
+
+ ## Next steps
+
+ <CardGroup cols={2}>
+ <Card title="Session logs" icon="list" href="/documentation/platform/agent-vault/session-logs">
+ Record every request an agent makes during a session.
+ </Card>
+ <Card title="Proxies" icon="server" href="/documentation/platform/agent-vault/proxies">
+ Change the proxy's traffic policy, exceptions, and poll interval.
+ </Card>
+ </CardGroup>
diff --cc docs/documentation/platform/agent-vault/guides/modal.mdx
index c92563f7d5,03eeea11ab..b1ee2da638
--- a/docs/documentation/platform/agent-vault/guides/modal.mdx
+++ b/docs/documentation/platform/agent-vault/guides/modal.mdx
@@@ -685,7 -669,7 +669,7 @@@ To check which requests the agent made
The agent's container can't connect to the internet directly, but it has two kinds of network access:
- **DNS:** Modal answers DNS lookups in a sandbox even with an empty allowlist, so the agent can look up hostnames
- - **Hosts through the proxy:** with **Service hosts only**, the agent can reach the hosts that services in the session's access bundle cover, and the proxy's exceptions
-- **Hosts through the proxy:** under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the agent's requests to any host on the internet (to allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Access bundle hosts only** and add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions))
++- **Hosts through the proxy:** under the default [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), **Any host**, the proxy forwards the agent's requests to any host on the internet (to allow only the hosts that services in the session's access bundle cover, set the traffic policy to **Service hosts only** and add any other hosts the agent needs, such as `registry.npmjs.org`, to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions))
### Compromised sandboxes
@@@ -707,7 -691,7 +691,7 @@@ Each sidecar has a copy of the proxy to
The session expired or was revoked. Set the session's `ttl` a few minutes longer than the sandbox's `timeout`, so the session lasts as long as the sandbox can run.
</Accordion>
<Accordion title="Requests to a host fail with a 403 from the start">
- The proxy's traffic policy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
- If the proxy's traffic policy is **Access bundle hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
++ If the proxy's traffic policy is **Service hosts only**, the proxy blocks hosts that no service in the access bundle covers. Add a service for the host, or add the host to the proxy's [exceptions](/documentation/platform/agent-vault/proxies#exceptions).
</Accordion>
<Accordion title="Can I use Modal's `proxy_traffic_via_sidecar` option instead?">
No. That option sends the agent's HTTPS connections to the sidecar without a session token, and the proxy needs the session token to know which credentials to attach. Use `infisical agent-vault run`, or set the proxy in the agent's HTTP client.
diff --cc docs/documentation/platform/agent-vault/inline-services.mdx
index d7f39b800e,0000000000..2c410b42cd
mode 100644,000000..100644
--- a/docs/documentation/platform/agent-vault/inline-services.mdx
+++ b/docs/documentation/platform/agent-vault/inline-services.mdx
@@@ -1,113 -1,0 +1,113 @@@
+---
+title: "Inline services"
+description: "Services and credentials that you send when you create a session, so nothing needs to be set up in Agent Vault in advance."
+---
+
+An inline service is a [service](/documentation/platform/agent-vault/services) that you send in the request that creates a [session](/documentation/platform/agent-vault/sessions), instead of adding the service to an [access bundle](/documentation/platform/agent-vault/access-bundles). Only that session can use the inline service. A session can have inline services on their own, or together with one access bundle.
+
+Use inline services when the code that creates sessions, such as an agent orchestrator or a job runner, already knows which APIs an agent needs and holds their credentials. That code sends the services with each session, so nothing has to be set up in Agent Vault in advance, and a credential that exists for only one run is deleted when the session ends. You can also use inline services to give one session access to an API that isn't in its access bundle, without giving the API to the other sessions that use the bundle.
+
+## Prerequisites
+
+- A machine identity with the **Admin** role in [Agent Vault](/documentation/platform/agent-vault/access-control#product-membership) (to set one up, follow [Step 1 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-1-set-up-a-machine-identity) and choose **Admin** in **Role**)
+- An access token for the machine identity, from [Step 2 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-2-log-in-as-the-machine-identity)
+- A running [proxy](/documentation/platform/agent-vault/proxies) that the agent's machine can reach
+
+## Create a session with inline services
+
+You can send inline services only through the API, not from the dashboard or the CLI. Call [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create) as the machine identity, and list the inline services in `services`. In this example, the session gets one HTTP service for `api.github.com` with a bearer token, and the agent can send only `GET` requests to that host:
+
+```bash
+curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \
+ -H "Authorization: Bearer <access-token>" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "ttl": "1h",
+ "label": "release notes",
+ "services": [
+ {
+ "type": "http",
+ "name": "github",
+ "hostPattern": "api.github.com",
+ "allowedMethods": ["GET"],
+ "credential": {"type": "bearer", "value": "<github-token>"}
+ }
+ ]
+ }'
+```
+
+An inline service has the same fields as an [HTTP API](/documentation/platform/agent-vault/http-apis) or an [MCP server](/documentation/platform/agent-vault/mcp-servers) in an access bundle, with these differences:
+
+- `name` is optional (without a name, the service goes by its first host on the **Sessions** page and in the [session logs](/documentation/platform/agent-vault/session-logs))
+- Credentials, custom header values, and substitution values can't use [variables](/documentation/platform/agent-vault/variables), so they can't contain text in double braces, such as `{{GITHUB_TOKEN}}`
- - An MCP server can't use [OAuth](/documentation/platform/agent-vault/mcp-servers#oauth)
++- An MCP server can't use [OAuth](/documentation/platform/agent-vault/mcp-servers#oauth), or limit the agent to some of its [tools](/documentation/platform/agent-vault/mcp-servers#allowed-tools)
+- A credential can't use [member-provided values](/documentation/platform/agent-vault/http-apis#member-provided-values)
+- You can't change an inline service after you create the session
+
+A session can have up to 20 inline services, and no two of its services can have the same name, including the services in its access bundle. A service sent without a name counts as its first host. The reference for [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create) lists every field and its limits.
+
+Start the agent with the session token from the response, as [Step 4 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-4-start-the-agent-with-the-session-token) describes. When the agent finishes, [revoke the session](/documentation/platform/agent-vault/sessions-api#step-5-revoke-the-session).
+
+<Tip>
+ A machine identity can also send inline services with a session that it creates [on behalf of a user](/documentation/platform/agent-vault/sessions-on-behalf-of-users). The user doesn't need the **Admin** role, and the inline services don't use the user's [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values).
+</Tip>
+
+## Combine inline services with an access bundle
+
+To give a session an access bundle as well as inline services, name the access bundle in `accessBundles` in the same request. A session can have only one access bundle.
+
+When you create the session, Infisical compares the host patterns of the inline services with each other and with the access bundle's services, using the same [host conflict rules](/documentation/platform/agent-vault/http-apis#host-conflicts) as for the services in one access bundle:
+
+- If two of the services use the same host pattern, creating the session fails
+- If an inline service and a service in the access bundle cover the same host with different patterns, such as `api.github.com` and `*.github.com`, requests to that host use the service with the more specific pattern
+
+## Find a session's inline services
+
+To see a session's inline services, go to **Sessions** in Agent Vault, select **View Session Logs** on the session's row, and look under **Inline Services**.
+
+[The endpoint that reads a session](/api-reference/endpoints/agent-vault-sessions/get) and [the endpoint that lists sessions](/api-reference/endpoints/agent-vault-sessions/list) return the inline services in `services`, and the [audit event](/documentation/platform/agent-vault/sessions#audit-trail) for creating the session lists them too.
+
+## When the session ends
+
+Infisical deletes the inline services' credentials, custom header values, and substitution values once the session ends:
+
+- If someone revokes the session, Infisical deletes the values right away
+- If the session expires, Infisical deletes the values within an hour
+
+If you set `ttl` to `never`, revoke the session when the agent finishes, so that Infisical deletes the values. Infisical keeps the rest of each inline service, such as its name and hosts, so you can still [find the session's inline services](#find-a-sessions-inline-services) after the session ends.
+
+## Troubleshooting
+
+<AccordionGroup>
+ <Accordion title="Creating the session fails with &quot;Only an Agent Vault admin can send services with a session&quot;">
+ The machine identity has the **Member** role in Agent Vault. Either give it the **Admin** role, or add the services to an access bundle and [grant the bundle](/documentation/platform/agent-vault/access-bundles#grant-access) to the machine identity.
+
+ To give the machine identity the **Admin** role:
+
+ <Steps>
+ <Step>
+ In Agent Vault, go to **Access Control** > **Machine Identities**.
+ </Step>
+ <Step>
+ Open the machine identity's menu and select **Change Role**.
+ </Step>
+ <Step>
+ Choose **Admin** in **Product Role**, then select **Save**.
+ </Step>
+ </Steps>
+ </Accordion>
+ <Accordion title="Requests to an inline service's host stop getting credentials">
+ The user or machine identity that created the session no longer has the **Admin** role in Agent Vault. Give the role back, or create a new session as an admin.
+ </Accordion>
+</AccordionGroup>
+
+## Next steps
+
+<CardGroup cols={2}>
+ <Card title="Session logs" icon="list" href="/documentation/platform/agent-vault/session-logs">
+ Record every request an agent makes during a session.
+ </Card>
+ <Card title="HTTP APIs" icon="plug" href="/documentation/platform/agent-vault/http-apis">
+ Limit an HTTP service's methods and paths, and add custom headers and substitutions.
+ </Card>
+</CardGroup>
diff --cc frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx
index 532cfe8d99,1a1da25672..04c3f354ff
--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx
@@@ -65,7 -68,8 +68,8 @@@ import
} from "@app/helpers/userTablePreferences";
import { useResetPageHelper } from "@app/hooks";
import {
- AgentVaultTrafficPolicy,
+ fetchAgentVaultProxyCa,
+ isServiceHostsPolicy,
useDeleteAgentVaultProxy,
useListAgentVaultProxies,
useRevokeAgentVaultProxyAccess,
diff --cc frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx
index 0a8e2a4c5d,93b6342a49..521e1e2540
--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/components/ProxyFormDialog.tsx
@@@ -156,10 -157,8 +158,11 @@@ export const ProxyFormDialog = ({ isOpe
reset({
name: proxy?.name ?? "",
+ description: proxy?.description ?? "",
- trafficPolicy: proxy?.trafficPolicy ?? AgentVaultTrafficPolicy.AnyHost,
+ trafficPolicy:
+ proxy && isServiceHostsPolicy(proxy.trafficPolicy)
+ ? AgentVaultTrafficPolicy.ServiceHosts
+ : AgentVaultTrafficPolicy.AnyHost,
allowedHosts: proxy?.allowedHosts ?? "",
pollInterval: proxy?.pollInterval ?? 60
});