Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(agent-vault): inline services on sessions
Scott Wilson00f0292bf23a
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 803cbd1bbb..4c7e52206d 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -21,6 +21,7 @@ import {} from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";+import { agentVaultSessionInlineServiceDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-inline-service-dal";import { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";import { AGENT_VAULT_MAX_SKILLS } from "@app/ee/services/agent-vault-skill/agent-vault-skill-fns";import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-dal";@@ -5653,6 +5654,370 @@ describe("Agent Vault V1 Router", async () => {});});+ describe("inline services", async () => {+ const sessionsUrl = "/api/v1/agent-vault/sessions";+ const inlineServicesTable = "agent_vault_session_inline_services";++ type TInlineSummary = {+ id: string;+ name: string | null;+ hostPattern: string;+ credential: Record<string, string>;+ customHeaders: { name: string; prefix: string }[];+ substitutions: { placeholder: string; surfaces: string[] }[];+ };+ type TResolvedService = {+ name: string;+ accessBundleName: string | null;+ allowedMethods: string[] | null;+ credential: Record<string, string>;+ customHeaders: { name: string; prefix: string; value: string }[];+ substitutions: { placeholder: string; surfaces: string[]; value: string }[];+ };++ // A real proxy on the real resolve route, so the inline secrets go through the project's actual KMS key.+ const createResolver = async (name: string) => {+ const proxy = await inject("POST", "/api/v1/agent-vault/proxies", { name });+ expect(proxy.statusCode).toBe(200);+ const proxyToken = proxy.json().proxyToken as string;+ return (sessionToken: string) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/resolve",+ headers: { authorization: `Bearer ${proxyToken}`, "x-infisical-agent-session": sessionToken }+ });+ };++ const openai = {+ type: "http",+ name: "openai",+ hostPattern: "api.openai.com",+ credential: { type: "bearer", value: "sk-inline-openai" }+ };++ test("an admin starts a session with inline services only, and resolve sends them exactly as sent", async () => {+ const mint = await inject("POST", sessionsUrl, {+ ttl: "1h",+ services: [+ openai,+ {+ type: "http",+ hostPattern: "api.stripe.com,files.stripe.com",+ allowedMethods: ["GET"],+ credential: { type: "basic", username: "rk_inline_stripe" },+ customHeaders: [{ name: "Stripe-Account", value: "acct_inline" }],+ substitutions: [{ placeholder: "__STRIPE_ID__", surfaces: ["path"], value: "cus_inline" }]+ }+ ]+ });+ expect(mint.statusCode).toBe(200);+ const { session } = mint.json() as {+ session: { id: string; token: string; accessBundles: unknown[]; services: TInlineSummary[] };+ };+ expect(session.accessBundles).toEqual([]);+ expect(session.services).toMatchObject([+ {+ name: "openai",+ hostPattern: "api.openai.com",+ credential: { type: "bearer", headerName: "Authorization", headerPrefix: "Bearer" }+ },+ {+ name: null,+ hostPattern: "api.stripe.com,files.stripe.com",+ credential: { type: "basic" },+ customHeaders: [{ name: "Stripe-Account", prefix: "" }],+ substitutions: [{ placeholder: "__STRIPE_ID__", surfaces: ["path"] }]+ }+ ]);++ const byId = await inject("GET", `${sessionsUrl}/${session.id}`);+ expect(byId.json().session.services).toEqual(session.services);+ const list = await inject("GET", `${sessionsUrl}?limit=100`);+ expect(+ (list.json().sessions as { id: string; services: TInlineSummary[] }[]).find(+ (row) => row.id === session.id+ )?.services+ ).toEqual(session.services);++ // No read returns a secret, and the rows hold them only sealed.+ const rows = await testDb(inlineServicesTable).where({ sessionId: session.id }).orderBy("position");+ expect(rows.map((row: { encryptedSecrets: Buffer | null }) => Boolean(row.encryptedSecrets))).toEqual([+ true,+ true+ ]);+ [mint.payload, byId.payload, list.payload, JSON.stringify(rows)].forEach((text) =>+ ["sk-inline-openai", "rk_inline_stripe", "acct_inline", "cus_inline"].forEach((secret) =>+ expect(text).not.toContain(secret)+ )+ );++ const resolve = await createResolver(`inline-only-${Date.now()}`);+ const resolved = await resolve(session.token);+ expect(resolved.statusCode).toBe(200);+ expect(resolved.json().services as TResolvedService[]).toMatchObject([+ {+ name: "openai",+ accessBundleName: null,+ credential: { type: "bearer", headerName: "Authorization", headerPrefix: "Bearer", value: "sk-inline-openai" }+ },+ {+ name: "api.stripe.com",+ accessBundleName: null,+ allowedMethods: ["GET"],+ credential: { type: "basic", username: "rk_inline_stripe", password: "" },+ customHeaders: [{ name: "Stripe-Account", prefix: "", value: "acct_inline" }],+ substitutions: [{ placeholder: "__STRIPE_ID__", surfaces: ["path"], value: "cus_inline" }]+ }+ ]);+ });++ test("a session needs an access bundle or inline services", async () => {+ const res = await inject("POST", sessionsUrl, { ttl: "1h" });+ expect(res.statusCode).toBe(400);+ expect(res.json().message).toBe(+ "Name the access bundle this session should carry, or send the services it should reach."+ );+ });++ test("a value can't use a variable, by key or by the id it is stored as", async () => {+ const key = `INLINE_PROBE_${Date.now()}`;+ const created = await inject("POST", "/api/v1/agent-vault/variables", {+ scope: "global",+ key,+ value: "variable-secret"+ });+ expect(created.statusCode).toBe(200);+ const variableId = created.json().variable.id as string;+ try {+ for await (const value of [`{{${key}}}`, `Bearer {{${variableId}}}`]) {+ const res = await inject("POST", sessionsUrl, {+ ttl: "1h",+ services: [{ ...openai, credential: { type: "bearer", value } }]+ });+ expect(res.statusCode).toBe(422);+ expect(JSON.stringify(res.json().message)).toContain("Services sent with a session can't use variables");+ }+ } finally {+ expect((await inject("DELETE", `/api/v1/agent-vault/variables/${variableId}`)).statusCode).toBe(200);+ }+ });++ test("what an inline service can't take is refused by name", async () => {+ const oauth = await inject("POST", sessionsUrl, {+ ttl: "1h",+ services: [{ ...openai, credential: { type: "oauth" } }]+ });+ expect(oauth.statusCode).toBe(400);+ expect(oauth.json().message).toMatch(/^Service 'openai': Services sent with a session can't use OAuth/);++ const memberField = await inject("POST", sessionsUrl, {+ ttl: "1h",+ services: [+ {+ ...openai,+ name: undefined,+ credential: { ...openai.credential, memberProvidedFields: ["credential-value"] }+ }+ ]+ });+ expect(memberField.statusCode).toBe(400);+ expect(memberField.json().message).toMatch(/^Service at index 0: Services sent with a session can't leave a field/);+ });++ test("only an Agent Vault admin can start a session with inline services", async () => {+ const member = await createMemberIdentity(`inline-member-${Date.now()}`);+ try {+ const refused = await member.as("POST", sessionsUrl, { ttl: "1h", services: [openai] });+ expect(refused.statusCode).toBe(403);+ expect(refused.json().message).toBe(+ "Only an Agent Vault admin can send services with a session. Name an access bundle instead."+ );+ } finally {+ await member.cleanup();+ }+ });++ test("an admin adds inline services to a bundle session, but not one covering a pattern the bundle covers", async () => {+ const bundle = await createAccessBundle(`inline-extend-${Date.now()}`);+ const service = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", value: "ghp_bundle" }+ });+ expect(service.statusCode).toBe(200);++ const clash = await inject("POST", sessionsUrl, {+ accessBundles: [bundle.name],+ ttl: "1h",+ services: [{ ...openai, hostPattern: "api.github.com" }]+ });+ expect(clash.statusCode).toBe(400);+ expect(clash.json().message).toBe(+ `Service 'openai' covers api.github.com:443, which 'github' in the access bundle '${bundle.name}' already covers. Remove it from 'openai'.`+ );++ // A wildcard beside the bundle's exact host is how an override is written, as within one bundle.+ const mint = await inject("POST", sessionsUrl, {+ accessBundles: [bundle.name],+ ttl: "1h",+ services: [openai, { ...openai, name: "github-other", hostPattern: "*.github.com" }]+ });+ expect(mint.statusCode).toBe(200);+ const { session } = mint.json() as { session: { token: string; accessBundles: { id: string }[] } };+ expect(session.accessBundles).toEqual([expect.objectContaining({ id: bundle.id })]);++ const resolve = await createResolver(`inline-extend-${Date.now()}`);+ const resolved = (await resolve(session.token)).json().services as TResolvedService[];+ expect(resolved.map((entry) => [entry.name, entry.accessBundleName, entry.credential.value])).toEqual([+ ["github", bundle.name, "ghp_bundle"],+ ["openai", null, "sk-inline-openai"],+ ["github-other", null, "sk-inline-openai"]+ ]);+ });++ test("an owner who stops being an admin keeps the bundle and loses the inline services until promoted again", async () => {+ const bundle = await createAccessBundle(`inline-demote-${Date.now()}`);+ expect(+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "passthrough" }+ })+ ).statusCode+ ).toBe(200);++ const projectId = await getProjectId();+ const owner = await createMemberIdentity(`inline-demote-${Date.now()}`);+ // Resolve reads the role through the permission cache, so the cached entry goes with each change.+ const setRole = async (role: string) => {+ expect(+ (await inject("PATCH", "/api/v1/agent-vault/members", { machineIdentityIds: [owner.id], role })).statusCode+ ).toBe(200);+ await testKeyStore.deleteItemsByKeyIn([+ KeyStorePrefixes.ProjectPermissionMarker(+ projectId,+ ActorType.IDENTITY,+ owner.id,+ ActionProjectType.AgentVault+ ),+ KeyStorePrefixes.ProjectPermissionData(projectId, ActorType.IDENTITY, owner.id, ActionProjectType.AgentVault)+ ]);+ };+ try {+ await setRole("admin");+ expect(+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {+ machineIdentityIds: [owner.id]+ })+ ).statusCode+ ).toBe(200);+ const mint = await owner.as("POST", sessionsUrl, {+ accessBundles: [bundle.name],+ ttl: "1h",+ services: [openai]+ });+ expect(mint.statusCode).toBe(200);+ const token = mint.json().session.token as string;++ const resolve = await createResolver(`inline-demote-${Date.now()}`);+ const serviceNames = async () =>+ ((await resolve(token)).json().services as TResolvedService[]).map((entry) => entry.name);+ expect(await serviceNames()).toEqual(["github", "openai"]);++ await setRole("member");+ expect(await serviceNames()).toEqual(["github"]);+ await setRole("admin");+ expect(await serviceNames()).toEqual(["github", "openai"]);+ } finally {+ await owner.cleanup();+ }+ });++ test("a machine identity that is an admin can send inline services with a session on a user's behalf", async () => {+ const bot = await createMemberIdentity(`inline-obo-${Date.now()}`);+ try {+ expect(+ (await inject("PATCH", "/api/v1/agent-vault/members", { machineIdentityIds: [bot.id], role: "admin" }))+ .statusCode+ ).toBe(200);+ expect(+ (+ await inject("PUT", `/api/v1/agent-vault/delegations/${bot.id}`, {+ scope: "selected",+ userIds: [seedData1.id]+ })+ ).statusCode+ ).toBe(200);++ const mint = await bot.as("POST", sessionsUrl, {+ onBehalfOf: { userId: seedData1.id },+ services: [openai]+ });+ expect(mint.statusCode).toBe(200);+ const { session } = mint.json() as { session: { id: string; token: string } };++ const read = await bot.as("GET", `${sessionsUrl}/${session.id}`);+ expect(read.json().session).toMatchObject({+ actor: { type: "machineIdentity", id: bot.id },+ onBehalfOf: expect.objectContaining({ id: seedData1.id }),+ accessBundles: [],+ services: [expect.objectContaining({ name: "openai" })]+ });++ const resolve = await createResolver(`inline-obo-${Date.now()}`);+ const resolved = await resolve(session.token);+ expect(resolved.statusCode).toBe(200);+ expect(resolved.json().services as TResolvedService[]).toMatchObject([+ { name: "openai", credential: { value: "sk-inline-openai" } }+ ]);+ } finally {+ await bot.cleanup();+ }+ });++ test("revoking deletes the secrets and keeps what the session could reach", async () => {+ const mint = await inject("POST", sessionsUrl, { ttl: "never", services: [openai] });+ expect(mint.statusCode).toBe(200);+ const { session } = mint.json() as { session: { id: string; expiresAt: string | null } };+ expect(session.expiresAt).toBeNull();++ expect((await inject("POST", `${sessionsUrl}/${session.id}/revoke`)).statusCode).toBe(200);++ const [row] = await testDb(inlineServicesTable).where({ sessionId: session.id });+ expect(row.encryptedSecrets).toBeNull();+ const read = await inject("GET", `${sessionsUrl}/${session.id}`);+ expect(read.json().session).toMatchObject({+ status: "revoked",+ services: [expect.objectContaining({ name: "openai", hostPattern: "api.openai.com" })]+ });+ });++ test("the hourly cleanup deletes the secrets of sessions that ended without a revoke", async () => {+ const mintInline = async () => {+ const res = await inject("POST", sessionsUrl, { ttl: "1h", services: [openai] });+ expect(res.statusCode).toBe(200);+ return res.json().session as { id: string };+ };+ const expired = await mintInline();+ const live = await mintInline();+ await testDb("agent_vault_sessions")+ .where({ id: expired.id })+ .update({ expiresAt: new Date(Date.now() - 1000) });++ await agentVaultSessionInlineServiceDALFactory(testDb).deleteSecretsOfEndedSessions();++ const secretsOf = async (sessionId: string) =>+ ((await testDb(inlineServicesTable).where({ sessionId }).first()) as { encryptedSecrets: Buffer | null })+ .encryptedSecrets;+ expect(await secretsOf(expired.id)).toBeNull();+ expect(await secretsOf(live.id)).not.toBeNull();+ });+ });+describe("session resolve", async () => {const buildResolver = (overrides: Partial<@@ -5667,6 +6032,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionInlineServiceDAL: agentVaultSessionInlineServiceDALFactory(testDb),agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),@@ -5805,6 +6171,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionInlineServiceDAL: agentVaultSessionInlineServiceDALFactory(testDb),agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),@@ -5981,6 +6348,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionInlineServiceDAL: agentVaultSessionInlineServiceDALFactory(testDb),agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),@@ -7851,6 +8219,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionInlineServiceDAL: agentVaultSessionInlineServiceDALFactory(testDb),agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),@@ -7956,6 +8325,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionInlineServiceDAL: agentVaultSessionInlineServiceDALFactory(testDb),agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 4530013491..b1ef890e1d 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -56,6 +56,9 @@ import {TAgentVaultSessionAccessBundles,TAgentVaultSessionAccessBundlesInsert,TAgentVaultSessionAccessBundlesUpdate,+ TAgentVaultSessionInlineServices,+ TAgentVaultSessionInlineServicesInsert,+ TAgentVaultSessionInlineServicesUpdate,TAgentVaultSessionLogConfigs,TAgentVaultSessionLogConfigsInsert,TAgentVaultSessionLogConfigsUpdate,@@ -1899,6 +1902,11 @@ declare module "knex/types/tables" {TAgentVaultSessionAccessBundlesInsert,TAgentVaultSessionAccessBundlesUpdate>;+ [TableName.AgentVaultSessionInlineService]: KnexOriginal.CompositeTableType<+ TAgentVaultSessionInlineServices,+ TAgentVaultSessionInlineServicesInsert,+ TAgentVaultSessionInlineServicesUpdate+ >;[TableName.AgentVaultDelegation]: KnexOriginal.CompositeTableType<TAgentVaultDelegations,TAgentVaultDelegationsInsert,diff --git a/backend/src/db/migrations/20261030180530_agent-vault-session-inline-services.ts b/backend/src/db/migrations/20261030180530_agent-vault-session-inline-services.tsnew file mode 100644index 0000000000..c97d08de0a--- /dev/null+++ b/backend/src/db/migrations/20261030180530_agent-vault-session-inline-services.ts@@ -0,0 +1,71 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++const TYPE_CHECK = "agent_vault_session_inline_services_type_check";+const CREDENTIAL_TYPE_CHECK = "agent_vault_session_inline_services_credential_type_check";+const WITH_SECRETS_INDEX = "agent_vault_session_inline_services_with_secrets";++export async function up(knex: Knex): Promise<void> {+ // Services an Agent Vault admin sends with a session instead of adding them to an access bundle. They belong to that+ // one session and are never edited. The rows stay once the session ends, so its history still shows what it could+ // reach, but their secrets don't.+ if (!(await knex.schema.hasTable(TableName.AgentVaultSessionInlineService))) {+ await knex.schema.createTable(TableName.AgentVaultSessionInlineService, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("sessionId").notNullable();+ t.foreign("sessionId").references("id").inTable(TableName.AgentVaultSession).onDelete("CASCADE");++ t.integer("position").notNullable();++ // NULL when the request left it out.+ t.string("name", 64);++ t.string("type", 32).notNullable();+ t.jsonb("config");+ t.string("hostPattern", 1024).notNullable();+ t.specificType("allowedMethods", "text[]");+ t.specificType("allowedPathPrefixes", "text[]");++ t.string("credentialType", 32).notNullable();+ t.jsonb("credentialConfig").notNullable();++ // Header names and substitution placeholders only. Their values are sealed in encryptedSecrets.+ t.jsonb("customHeaders").notNullable();+ t.jsonb("substitutions").notNullable();++ // The credential, custom header values and substitution values sealed together, so deleting them once the session+ // ends is one write. NULL after that, and for a pass-through service with nothing to seal.+ t.binary("encryptedSecrets");++ t.timestamps(true, true, true);++ // sessionId leads, so the index also serves the session foreign key's cascade.+ t.unique(["sessionId", "position"], { indexName: "agent_vault_session_inline_services_session_position" });+ });++ await knex.raw(`ALTER TABLE ?? ADD CONSTRAINT ?? CHECK ("type" IN ('http', 'mcp'))`, [+ TableName.AgentVaultSessionInlineService,+ TYPE_CHECK+ ]);+ await knex.raw(`ALTER TABLE ?? ADD CONSTRAINT ?? CHECK ("credentialType" IN ('bearer', 'basic', 'passthrough'))`, [+ TableName.AgentVaultSessionInlineService,+ CREDENTIAL_TYPE_CHECK+ ]);+ // The hourly cleanup looks only at rows that still hold secrets, so it never scans the history of ended sessions.+ await knex.raw(`CREATE INDEX ?? ON ?? ("sessionId") WHERE "encryptedSecrets" IS NOT NULL`, [+ WITH_SECRETS_INDEX,+ TableName.AgentVaultSessionInlineService+ ]);++ await createOnUpdateTrigger(knex, TableName.AgentVaultSessionInlineService);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultSessionInlineService]);+ await knex.schema.dropTableIfExists(TableName.AgentVaultSessionInlineService);+ await dropOnUpdateTrigger(knex, TableName.AgentVaultSessionInlineService);+}diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 77a537b585..f857807939 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -121,6 +121,19 @@ tables:- accessBundleId- createdAt+ - name: agent_vault_session_inline_services+ source: public.agent_vault_session_inline_services+ columns:+ - id+ - sessionId+ - type+ - hostPattern+ - credentialType+ - allowedMethods+ - allowedPathPrefixes+ - createdAt+ - updatedAt+- name: agent_vault_session_log_configssource: public.agent_vault_session_log_configscolumns:diff --git a/backend/src/db/schemas/agent-vault-session-inline-services.ts b/backend/src/db/schemas/agent-vault-session-inline-services.tsnew file mode 100644index 0000000000..c4104c1dd6--- /dev/null+++ b/backend/src/db/schemas/agent-vault-session-inline-services.ts@@ -0,0 +1,38 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultSessionInlineServicesSchema = z.object({+ id: z.string().uuid(),+ sessionId: z.string().uuid(),+ position: z.number(),+ name: z.string().nullable().optional(),+ type: z.string(),+ config: z.unknown().nullable().optional(),+ hostPattern: z.string(),+ allowedMethods: z.string().array().nullable().optional(),+ allowedPathPrefixes: z.string().array().nullable().optional(),+ credentialType: z.string(),+ credentialConfig: z.unknown(),+ customHeaders: z.unknown(),+ substitutions: z.unknown(),+ encryptedSecrets: zodBuffer.nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAgentVaultSessionInlineServices = z.infer<typeof AgentVaultSessionInlineServicesSchema>;+export type TAgentVaultSessionInlineServicesInsert = Omit<+ z.input<typeof AgentVaultSessionInlineServicesSchema>,+ TImmutableDBKeys+>;+export type TAgentVaultSessionInlineServicesUpdate = Partial<+ Omit<z.input<typeof AgentVaultSessionInlineServicesSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 36843026fb..8262dfb4da 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -16,6 +16,7 @@ export * from "./agent-vault-service-substitutions";export * from "./agent-vault-service-variable-references";export * from "./agent-vault-services";export * from "./agent-vault-session-access-bundles";+export * from "./agent-vault-session-inline-services";export * from "./agent-vault-session-log-configs";export * from "./agent-vault-sessions";export * from "./agent-vault-skill-versions";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex c4e055deef..149aacdf97 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -285,6 +285,7 @@ export enum TableName {AgentVaultPersonalValueReference = "agent_vault_personal_value_references",AgentVaultSession = "agent_vault_sessions",AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",+ AgentVaultSessionInlineService = "agent_vault_session_inline_services",AgentVaultDelegation = "agent_vault_delegations",AgentVaultDelegationSubject = "agent_vault_delegation_subjects",AgentVaultProxy = "agent_vault_proxies",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-inline-service-schemas.test.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-inline-service-schemas.test.tsnew file mode 100644index 0000000000..e90612b8c6--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-inline-service-schemas.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from "vitest";++import { AGENT_VAULT_INLINE_SERVICE_VARIABLE_MESSAGE } from "@app/ee/services/agent-vault/agent-vault-variable-fns";++import { AgentVaultInlineServicesInputSchema } from "./agent-vault-schemas";++const bearer = (value: string, extra: Record<string, unknown> = {}) => ({+ type: "http",+ hostPattern: "api.example.com",+ credential: { type: "bearer", value },+ ...extra+});++const issuesOf = (input: unknown) => {+ const result = AgentVaultInlineServicesInputSchema.safeParse(input);+ return result.success ? [] : result.error.issues;+};++describe("inline services request schema", () => {+ test("refuses a variable reference, well formed or not, and names the field without quoting it", () => {+ const [wellFormed] = issuesOf([bearer("Bearer {{GITHUB_TOKEN}}")]);+ expect(wellFormed.message).toBe(AGENT_VAULT_INLINE_SERVICE_VARIABLE_MESSAGE);+ expect(wellFormed.path).toEqual([0, "credential", "value"]);+ expect(wellFormed.message).not.toContain("Bearer");++ expect(issuesOf([bearer("{{not a key}}")])[0].message).toBe(AGENT_VAULT_INLINE_SERVICE_VARIABLE_MESSAGE);+ });++ test("refuses one in a basic credential, a custom header and a substitution", () => {+ const issues = issuesOf([+ {+ type: "http",+ hostPattern: "api.example.com",+ credential: { type: "basic", username: "{{USER}}", password: "secret" },+ customHeaders: [{ name: "X-Key", value: "{{KEY}}" }],+ substitutions: [{ placeholder: "TEAM", surfaces: ["path"], value: "{{TEAM}}" }]+ }+ ]);+ expect(issues.map((issue) => issue.path)).toEqual([+ [0, "credential", "username"],+ [0, "customHeaders", 0, "value"],+ [0, "substitutions", 0, "value"]+ ]);+ });++ test("accepts braces that don't read as a reference", () => {+ expect(issuesOf([bearer('{"scope":{"read":true}}'), bearer("a {{ b", { hostPattern: "b.example.com" })])).toEqual(+ []+ );+ });++ test("needs a name to be unique, but not present", () => {+ const issues = issuesOf([+ bearer("one", { name: "api" }),+ bearer("two", { name: "api", hostPattern: "b.example.com" }),+ bearer("three", { hostPattern: "c.example.com" })+ ]);+ expect(issues).toHaveLength(1);+ expect(issues[0].path).toEqual([1, "name"]);+ });++ test("caps the list at 20", () => {+ const services = Array.from({ length: 21 }, (_, index) =>+ bearer("token", { hostPattern: `h${index}.example.com` })+ );+ expect(issuesOf(services)[0]).toMatchObject({+ code: "too_big",+ message:+ "A session can have at most 20 services. Add the others to an access bundle and name it in accessBundles."+ });+ });++ test("needs a half of a basic credential", () => {+ const [issue] = issuesOf([{ type: "http", hostPattern: "api.example.com", credential: { type: "basic" } }]);+ expect(issue.message).toBe("A basic credential needs a username, a password, or both");+ });++ // Refused by name in the session service, which can say why.+ test("passes OAuth and member-provided fields through to be refused by name", () => {+ expect(issuesOf([{ type: "http", hostPattern: "api.example.com", credential: { type: "oauth" } }])).toEqual([]);+ expect(+ issuesOf([+ bearer("token", { credential: { type: "bearer", value: "token", memberProvidedFields: ["credential-value"] } })+ ])+ ).toEqual([]);+ });+});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex 3b0b9cb086..e0a4c0d2c0 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts@@ -159,7 +159,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi.object({id: z.string().uuid(),name: z.string(),- accessBundleName: z.string(),+ accessBundleName: z.string().nullable(),type: z.nativeEnum(AgentVaultServiceType).describe(AGENT_VAULT.SERVICE.type),hostPattern: z.string(),allowedMethods: z.string().array().nullable(),diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex 3d09eed03c..adf7877a03 100644--- 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@@ -2,6 +2,7 @@ import { z } from "zod";import { ProjectMembershipRole } from "@app/db/schemas";import { AGENT_VAULT_MAX_GRANTEES } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";+import { AGENT_VAULT_MAX_SESSION_INLINE_SERVICES } from "@app/ee/services/agent-vault-session/agent-vault-session-inline-service-fns";import {AGENT_VAULT_SKILL_MAX_PATH_LENGTH,AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT@@ -28,6 +29,7 @@ import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-hostimport { 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 {+ acceptsNoVariableReferences,acceptsVariableReferences,addDuplicateCustomHeaderNameIssues,addDuplicatePlaceholderIssues,@@ -37,6 +39,8 @@ import {AgentVaultCustomHeaderUpdateSchema,agentVaultHeaderNameSchema,agentVaultHeaderPrefixSchema,+ AgentVaultInlineCustomHeaderInputSchema,+ AgentVaultInlineSubstitutionInputSchema,AgentVaultSubstitutionInputSchema,AgentVaultSubstitutionUpdateSchema} from "@app/ee/services/agent-vault/agent-vault-transformation-schemas";@@ -387,6 +391,164 @@ export const AgentVaultUpdateServiceBodySchema = z"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())+ })+ .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())+ })+ .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().nullable().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)+});+const variableReferenceBase = {variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),key: z.string().describe(AGENT_VAULT.VARIABLE.key)diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.tsindex 3755027a31..fa4832b685 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts@@ -14,7 +14,11 @@ import {AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,AGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";-import { AgentVaultSessionScope, AgentVaultSessionStatus } from "@app/ee/services/agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultSessionScope,+ AgentVaultSessionStatus+} from "@app/ee/services/agent-vault/agent-vault-enums";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";@@ -28,7 +32,12 @@ import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { actorContext } from "./agent-vault-router-fns";-import { AgentVaultSessionActorSchema, AgentVaultSessionOnBehalfOfSchema } from "./agent-vault-schemas";+import {+ AgentVaultInlineServiceSchema,+ AgentVaultInlineServicesInputSchema,+ AgentVaultSessionActorSchema,+ AgentVaultSessionOnBehalfOfSchema+} from "./agent-vault-schemas";const SessionAccessBundleSchema = z.object({id: z.string().uuid().nullable(),@@ -47,10 +56,33 @@ const SessionSchema = z.object({createdAt: z.date()});+const SessionInlineServicesSchema = AgentVaultInlineServiceSchema.array().describe(+ AGENT_VAULT.SESSION.inlineServicesRead+);+const SessionWithAccessBundlesSchema = SessionSchema.extend({- accessBundles: SessionAccessBundleSchema.array()+ accessBundles: SessionAccessBundleSchema.array(),+ services: SessionInlineServicesSchema});+// Whole-body examples, so the docs show the usual session, one access bundle and no services of its own, rather+// than one generated from every optional field.+const EXAMPLE_ACCESS_BUNDLE = { id: "3c90c3cc-0d44-4b50-8888-8dd25736052a", name: "prod-deploy", position: 0 };++const EXAMPLE_SESSION = {+ id: "d1f0b5a2-6c3e-4f8a-9b7d-2e4c6a8f0b13",+ label: "Nightly deploy",+ actor: { type: "machineIdentity", id: "7b1e4f2a-9c3d-4a6b-8e5f-1d2c3b4a5e6f", name: "deploy-bot" },+ onBehalfOf: null,+ status: "active",+ expiresAt: "2026-11-01T02:00:00.000Z",+ revokedAt: null,+ createdAt: "2026-10-31T18:00:00.000Z",+ accessBundles: [EXAMPLE_ACCESS_BUNDLE]+};++const docsExample = (example: unknown) => JSON.stringify({ example });+export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",@@ -85,10 +117,12 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvideroffset: z.coerce.number().int().min(0).default(0).describe(AGENT_VAULT.SESSION.offset)}),response: {- 200: z.object({- sessions: SessionWithAccessBundlesSchema.array(),- totalCount: z.number()- })+ 200: z+ .object({+ sessions: SessionWithAccessBundlesSchema.array(),+ totalCount: z.number()+ })+ .describe(docsExample({ sessions: [EXAMPLE_SESSION], totalCount: 1 }))}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),@@ -114,7 +148,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvidertags: [ApiDocsTags.AgentVaultSessions],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),response: {- 200: z.object({ session: SessionWithAccessBundlesSchema })+ 200: z.object({ session: SessionWithAccessBundlesSchema }).describe(docsExample({ session: EXAMPLE_SESSION }))}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),@@ -134,78 +168,98 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProviderhide: false,operationId: "createAgentVaultSession",description:- "Create an Agent Vault session with an access bundle you can reach, or, as a machine identity with a delegation, on behalf of a user",+ "Create an Agent Vault session with an access bundle you can reach, services of its own (Agent Vault admins), or both, for yourself or, as a machine identity with a delegation, on behalf of a user",tags: [ApiDocsTags.AgentVaultSessions],- body: z.object({- accessBundles: slugSchema({ max: 64, field: "Access bundle" })- .array()- .min(1)- .max(AGENT_VAULT_MAX_SESSION_BUNDLES)- .describe(AGENT_VAULT.SESSION.accessBundles),- // Optional rather than defaulted: the default depends on whether the session is on a user's behalf.- ttl: z- .string()- .trim()- .optional()- .superRefine((val, ctx) => {- if (val === undefined) return;- if (val === AGENT_VAULT_SESSION_TTL_NEVER) return;- let parsed: number | undefined;- try {- parsed = ms(val);- } catch {- parsed = undefined;- }- if (typeof parsed !== "number" || Number.isNaN(parsed) || parsed < 60 * 1000) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "TTL must be a duration of at least 1 minute, such as 30m, 8h, 7d, or never"- });- return;- }- if (parsed > AGENT_VAULT_SESSION_MAX_TTL_MS) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "TTL must be at most 100 years. Use never for a session that doesn't expire"- });- }- })- .describe(AGENT_VAULT.SESSION.ttl),- onBehalfOf: z+ body: z+ .object({+ accessBundles: slugSchema({ max: 64, field: "Access bundle" })+ .array()+ .max(AGENT_VAULT_MAX_SESSION_BUNDLES)+ .default([])+ .describe(AGENT_VAULT.SESSION.accessBundles),+ // Optional rather than defaulted, so the docs' request example leaves it out instead of showing an empty list.+ services: AgentVaultInlineServicesInputSchema.optional(),+ // Optional rather than defaulted: the default depends on whether the session is on a user's behalf.+ ttl: z+ .string()+ .trim()+ .optional()+ .superRefine((val, ctx) => {+ if (val === undefined) return;+ if (val === AGENT_VAULT_SESSION_TTL_NEVER) return;+ let parsed: number | undefined;+ try {+ parsed = ms(val);+ } catch {+ parsed = undefined;+ }+ if (typeof parsed !== "number" || Number.isNaN(parsed) || parsed < 60 * 1000) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "TTL must be a duration of at least 1 minute, such as 30m, 8h, 7d, or never"+ });+ return;+ }+ if (parsed > AGENT_VAULT_SESSION_MAX_TTL_MS) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "TTL must be at most 100 years. Use never for a session that doesn't expire"+ });+ }+ })+ .describe(AGENT_VAULT.SESSION.ttl),+ onBehalfOf: z+ .object({+ userId: z.string().uuid().optional().describe(AGENT_VAULT.SESSION.onBehalfOfUserId),+ userEmail: z+ .string()+ .trim()+ .toLowerCase()+ .email()+ .max(255)+ .optional()+ .describe(AGENT_VAULT.SESSION.onBehalfOfUserEmail)+ })+ .refine((val) => Boolean(val.userId) !== Boolean(val.userEmail), {+ message: "Name the user by userId or by userEmail, not both"+ })+ .optional()+ .describe(+ JSON.stringify({+ description: AGENT_VAULT.SESSION.onBehalfOf,+ example: { userEmail: "[email protected]" }+ })+ ),+ label: agentVaultSessionLabelSchema.describe(AGENT_VAULT.SESSION.label)+ })+ .describe(+ docsExample({ accessBundles: [EXAMPLE_ACCESS_BUNDLE.name], ttl: "8h", label: EXAMPLE_SESSION.label })+ ),+ response: {+ 200: z.object({- userId: z.string().uuid().optional().describe(AGENT_VAULT.SESSION.onBehalfOfUserId),- userEmail: z- .string()- .trim()- .toLowerCase()- .email()- .max(255)- .optional()- .describe(AGENT_VAULT.SESSION.onBehalfOfUserEmail)- })- .refine((val) => Boolean(val.userId) !== Boolean(val.userEmail), {- message: "Name the user by userId or by userEmail, not both"+ session: z.object({+ id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),+ label: z.string().nullable().describe(AGENT_VAULT.SESSION.label),+ token: z.string().describe(AGENT_VAULT.SESSION.token),+ expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),+ createdAt: z.date(),+ accessBundles: SessionAccessBundleSchema.array(),+ services: SessionInlineServicesSchema+ })})- .optional().describe(- JSON.stringify({- description: AGENT_VAULT.SESSION.onBehalfOf,- example: { userEmail: "[email protected]" }+ docsExample({+ session: {+ id: EXAMPLE_SESSION.id,+ label: EXAMPLE_SESSION.label,+ token: "agv_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ expiresAt: EXAMPLE_SESSION.expiresAt,+ createdAt: EXAMPLE_SESSION.createdAt,+ accessBundles: [EXAMPLE_ACCESS_BUNDLE]+ }})- ),- label: agentVaultSessionLabelSchema.describe(AGENT_VAULT.SESSION.label)- }),- response: {- 200: z.object({- session: z.object({- id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),- label: z.string().nullable().describe(AGENT_VAULT.SESSION.label),- token: z.string().describe(AGENT_VAULT.SESSION.token),- expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),- createdAt: z.date(),- accessBundles: SessionAccessBundleSchema.array()- })- })+ )}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -238,9 +292,27 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvidermetadata: {sessionId: session.id,label: session.label,- accessBundleId: session.accessBundles[0].id,- accessBundleName: session.accessBundles[0].name,+ accessBundleId: session.accessBundles[0]?.id ?? null,+ accessBundleName: session.accessBundles[0]?.name ?? null,expiresAt: session.expiresAt?.toISOString() ?? null,+ ...(session.services.length > 0 && {+ services: session.services.map((service) => ({+ serviceId: service.id,+ name: service.name,+ serviceType: service.type,+ serverUrl: service.serverUrl ?? undefined,+ hostPattern: service.hostPattern,+ credentialType: service.credential.type,+ headerName:+ service.credential.type === AgentVaultCredentialType.Bearer+ ? service.credential.headerName+ : undefined,+ allowedMethods: service.allowedMethods,+ allowedPathPrefixes: service.allowedPathPrefixes,+ customHeaderNames: service.customHeaders.map((header) => header.name),+ substitutionPlaceholders: service.substitutions.map((substitution) => substitution.placeholder)+ }))+ }),...(onBehalfOf && {onBehalfOfUserId: onBehalfOf.userId,onBehalfOfUserName: onBehalfOf.username,@@ -254,7 +326,8 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProviderevent: PostHogEventTypes.AgentVaultSessionCreated,properties: {sessionId: session.id,- accessBundleId: session.accessBundles[0].id,+ accessBundleId: session.accessBundles[0]?.id ?? null,+ inlineServiceCount: session.services.length,ttlSeconds,isOnBehalfOfUser: Boolean(onBehalfOf)}@@ -277,7 +350,9 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProviderbody: z.object({label: agentVaultSessionLabelUpdateSchema.describe(AGENT_VAULT.SESSION.updateLabel)}),- response: { 200: z.object({ session: SessionWithAccessBundlesSchema }) }+ response: {+ 200: z.object({ session: SessionWithAccessBundlesSchema }).describe(docsExample({ session: EXAMPLE_SESSION }))+ }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex 853936cb9c..b291e4d32c 100644--- 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@@ -40,7 +40,7 @@ import {OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE,TAgentVaultOauthServiceFactory} from "../agent-vault-oauth/agent-vault-oauth-service";-import { AGENT_VAULT_OAUTH_HEADER_NAME, TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";+import { TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";import {clearPersonalValuesAfterRevoke,@@ -127,7 +127,11 @@ import {TAgentVaultServiceVariableReferenceDALFactory,TAgentVaultVariableReferenceWithKey} from "./agent-vault-service-variable-reference-dal";-import { planTransformationDiff, TTransformationWrite } from "./agent-vault-transformation-fns";+import {+ assertCustomHeadersDoNotShadowCredential,+ planTransformationDiff,+ TTransformationWrite+} from "./agent-vault-transformation-fns";type TAgentVaultAccessBundleServiceFactoryDep = {agentVaultAccessBundleDAL: TAgentVaultAccessBundleDALFactory;@@ -602,38 +606,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE ="This service's credential was changed by another save while this one was in progress. Reload the service and save again.";- // Basic and OAuth have no header name in their config, but the proxy always writes Authorization for both.- const credentialHeaderName = (credentialType: AgentVaultCredentialType, headerName?: string): string | null => {- switch (credentialType) {- case AgentVaultCredentialType.Bearer:- return headerName || "Authorization";- case AgentVaultCredentialType.OAuth:- return AGENT_VAULT_OAUTH_HEADER_NAME;- case AgentVaultCredentialType.Basic:- return "Authorization";- default:- return null;- }- };-- // The proxy writes the credential last, so a collision costs the header rather than the token; refusing it- // on write is what tells the author. Either half of a PATCH can introduce one, which is why both are read.- const assertCustomHeadersDoNotShadowCredential = (- config: { type: AgentVaultCredentialType; headerName?: string },- customHeaders: { name: string }[] | undefined- ) => {- if (!customHeaders?.length) return;- const credentialHeader = credentialHeaderName(config.type, config.headerName);- if (!credentialHeader) return;-- const clash = customHeaders.find((header) => header.name.toLowerCase() === credentialHeader.toLowerCase());- if (clash) {- throw new BadRequestError({- message: `The ${credentialHeader} header is already set by the credential. Rename the custom header or change the credential.`- });- }- };-// An authorization only comes from a browser sign-in in the UI, so a machine identity could never hold one.const assertOauthConnectedByUser = (ctx: TGetAccessBundleDTO["ctx"], credential?: TAgentVaultCredentialUpdate) => {if (credential?.type === AgentVaultCredentialType.OAuth && ctx.actor !== ActorType.USER) {diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.tsindex 3b05f52956..d1a706a770 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts@@ -1,5 +1,8 @@import { BadRequestError } from "@app/lib/errors";+import { AGENT_VAULT_OAUTH_HEADER_NAME } from "../agent-vault-oauth/agent-vault-oauth-types";+import { AgentVaultCredentialType } from "../agent-vault/agent-vault-enums";+type TStoredRow = { id: string; encryptedValue: Buffer };/** `encryptedValue` is undefined when the caller omitted the value, which means "keep whatever is stored". */@@ -102,3 +105,35 @@ export const planTransformationDiff = <TRow extends TStoredRow, TColumns>({return plan;};++// Basic and OAuth have no header name in their config, but the proxy always writes Authorization for both.+const credentialHeaderName = (credentialType: AgentVaultCredentialType, headerName?: string): string | null => {+ switch (credentialType) {+ case AgentVaultCredentialType.Bearer:+ return headerName || "Authorization";+ case AgentVaultCredentialType.OAuth:+ return AGENT_VAULT_OAUTH_HEADER_NAME;+ case AgentVaultCredentialType.Basic:+ return "Authorization";+ default:+ return null;+ }+};++// The proxy writes the credential last, so a collision costs the header rather than the token; refusing it+// on write is what tells the author. Either half of a PATCH can introduce one, which is why both are read.+export const assertCustomHeadersDoNotShadowCredential = (+ config: { type: AgentVaultCredentialType; headerName?: string },+ customHeaders: { name: string }[] | undefined+) => {+ if (!customHeaders?.length) return;+ const credentialHeader = credentialHeaderName(config.type, config.headerName);+ if (!credentialHeader) return;++ const clash = customHeaders.find((header) => header.name.toLowerCase() === credentialHeader.toLowerCase());+ if (clash) {+ throw new BadRequestError({+ message: `The ${credentialHeader} header is already set by the credential. Rename the custom header or change the credential.`+ });+ }+};diff --git 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.tsindex 50b62e6b51..f1ee98b72b 100644--- 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@@ -79,6 +79,7 @@ const setup = (findByTokenHash: async () =>({ id: "session-1", projectId: PROJECT_ID, userId: "user-1", revokedAt: null, expiresAt: null }) as never},+ agentVaultSessionInlineServiceDAL: { findBySessionId: async () => [] },agentVaultDelegationDAL: { identityCoversUser: async () => false },agentVaultSessionLogConfigDAL: {findOne: async () => sessionLogConfig,@@ -337,6 +338,7 @@ describe("resolve for a session on a user's behalf", () => {expiresAt: null}) as never},+ agentVaultSessionInlineServiceDAL: { findBySessionId: async () => [] },agentVaultDelegationDAL: { identityCoversUser: async () => delegationCoversUser },agentVaultSessionLogConfigDAL: {findOne: async () => sessionLogConfig,diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 2046fad832..68bb61870c 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -50,6 +50,11 @@ import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-sessioimport { getEffectiveSessionLogConfig } from "../agent-vault-session-log/agent-vault-session-log-storage-fns";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";+import { TAgentVaultSessionInlineServiceDALFactory } from "../agent-vault-session/agent-vault-session-inline-service-dal";+import {+ parseInlineServiceSecrets,+ toResolvedInlineService+} from "../agent-vault-session/agent-vault-session-inline-service-fns";import { deserializeSkillFiles } from "../agent-vault-skill/agent-vault-skill-fns";import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";@@ -110,6 +115,7 @@ type TAgentVaultProxyServiceFactoryDep = {agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findValuesForResolve">;agentVaultPersonalValueDAL: Pick<TAgentVaultPersonalValueDALFactory, "findForResolve">;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;+ agentVaultSessionInlineServiceDAL: Pick<TAgentVaultSessionInlineServiceDALFactory, "findBySessionId">;agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "identityCoversUser">;agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne" | "findByProjectIdFromPrimary">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;@@ -168,6 +174,7 @@ export const agentVaultProxyServiceFactory = ({agentVaultVariableDAL,agentVaultPersonalValueDAL,agentVaultSessionDAL,+ agentVaultSessionInlineServiceDAL,agentVaultDelegationDAL,agentVaultSessionLogConfigDAL,membershipDAL,@@ -746,7 +753,7 @@ export const agentVaultProxyServiceFactory = ({// Shared by the proxy's session routes and the CLI's skills fetch, so none of them can reach a bundle resolve// would not. Returns the bundles the session reaches now, null for every bundle: its owner's, and on a user's behalf- // only those the user reaches too.+ // only those the user reaches too. Also whether the owner is an admin now, which inline services need.const $authorizeSessionOwner = async (session: TAgentVaultSessions, orgId: string) => {if (session.revokedAt) throw new UnauthorizedError({ message: "This session has been revoked" });if (session.expiresAt && session.expiresAt <= new Date()) {@@ -823,7 +830,10 @@ export const agentVaultProxyServiceFactory = ({actor,groupIds: liveGroupIds});- return onBehalfOf ? intersectAccessBundleIds(actorReach, onBehalfOf.reach) : actorReach;+ return {+ accessBundleIds: onBehalfOf ? intersectAccessBundleIds(actorReach, onBehalfOf.reach) : actorReach,+ isOwnerAdmin: isAdmin+ };};const $authorizeSession = async ({ proxyId, orgId, sessionToken }: TAuthorizeSessionDTO) => {@@ -836,19 +846,23 @@ export const agentVaultProxyServiceFactory = ({throw new NotFoundError({ message: "Session not found" });}- const accessBundleIds = await $authorizeSessionOwner(session, orgId);- return { session, proxy, accessBundleIds };+ const { accessBundleIds, isOwnerAdmin } = await $authorizeSessionOwner(session, orgId);+ return { session, proxy, accessBundleIds, isOwnerAdmin };};/** Resolve services and decrypt their credentials. The proxy's JWT authorizes; the session token is a selector. */const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {- const { session, proxy, accessBundleIds } = await $authorizeSession({ proxyId, orgId, sessionToken });+ const { session, proxy, accessBundleIds, isOwnerAdmin } = await $authorizeSession({ proxyId, orgId, sessionToken });const rows = await agentVaultResolveDAL.findResolvableServices({sessionId: session.id,projectId: session.projectId,accessBundleIds});+ // Starting a session with inline services is an admin's call, and like a grant it is re-checked on every resolve: an+ // owner who is no longer an admin keeps the session's bundle, if it has one, and loses its inline services until+ // they are an admin again.+ const inlineServiceRows = isOwnerAdmin ? await agentVaultSessionInlineServiceDAL.findBySessionId(session.id) : [];// A token that expires before the proxy's next poll is refreshed now, which also keeps proxies that can't// refresh on their own working. The proxy gives up on resolve after 15 seconds, and one refresh can wait on@@ -937,6 +951,7 @@ export const agentVaultProxyServiceFactory = ({// a kms_keys read (or an external KMS round trip) per resolve for nothing.const hasSealedValue =rows.some((row) => row.encryptedCredential || row.memberProvidedFields?.length) ||+ inlineServiceRows.some((row) => row.encryptedSecrets) ||customHeaderRows.length > 0 ||substitutionRows.length > 0 ||sessionLogKeyNeeded;@@ -977,7 +992,7 @@ export const agentVaultProxyServiceFactory = ({personalValuesMissing: false}));- const services = await $applyPersonalValues({+ const bundleServices = await $applyPersonalValues({sessionId: session.id,projectId: session.projectId,owner: personalValuesOwner(session),@@ -992,6 +1007,23 @@ export const agentVaultProxyServiceFactory = ({decryptJson: $decryptJson});+ // Never expanded: an inline service's values were sent exactly as they are. After the bundle's services, so a host a+ // later bundle edit shares with one goes to the bundle's service, which the Go matcher picks on a tie by order.+ const inlineServices = inlineServiceRows.flatMap((row) => {+ const resolved = toResolvedInlineService(+ row,+ row.encryptedSecrets ? parseInlineServiceSecrets($decryptJson(row.encryptedSecrets)) : null+ );+ if (!resolved) {+ logger.warn(+ `agentVaultResolve: inline service has no secrets to send, leaving it out [sessionId=${session.id}] [inlineServiceId=${row.id}]`+ );+ return [];+ }+ return [resolved];+ });+ const services = [...bundleServices, ...inlineServices];+// A key that can't be opened turns logs off for this session instead of cutting the agent off from its services.const $sessionLogs = (): { enabled: boolean; sessionKey: string | null } => {if (!sessionLogKeyNeeded || !session.encryptedSessionLogKey) {@@ -1014,7 +1046,7 @@ export const agentVaultProxyServiceFactory = ({const sessionLogs = $sessionLogs();logger.info(- `agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}] [personalValuesMissing=${services.filter((service) => service.personalValuesMissing).length}]`+ `agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}] [inlineServices=${inlineServices.length}] [personalValuesMissing=${services.filter((service) => service.personalValuesMissing).length}]`);return {@@ -1090,7 +1122,7 @@ export const agentVaultProxyServiceFactory = ({throw new UnauthorizedError({ message: "This Agent Vault session token is not valid" });}- const accessBundleIds = await $authorizeSessionOwner(session, project.orgId);+ const { accessBundleIds } = await $authorizeSessionOwner(session, project.orgId);const rows = await agentVaultResolveDAL.findSessionSkills({sessionId: session.id,diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex 74ec3be54d..33cbe14a9c 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -85,7 +85,8 @@ export type TReportMissingScopesDTO = TRefreshCredentialDTO & {export type TResolvedService = {id: string;name: string;- accessBundleName: string;+ // Null for a service sent inline with the session, which belongs to no bundle.+ accessBundleName: string | null;type: AgentVaultServiceType;hostPattern: string;allowedMethods: string[] | null;diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-dal.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-dal.tsnew file mode 100644index 0000000000..c8b368ccfc--- /dev/null+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-dal.ts@@ -0,0 +1,118 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultSessionInlineServices } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";+import { logger } from "@app/lib/logger";++import { TAgentVaultSessionInlineServiceSummaryRow } from "./agent-vault-session-inline-service-fns";++export type TAgentVaultSessionInlineServiceDALFactory = ReturnType<typeof agentVaultSessionInlineServiceDALFactory>;++const DELETE_SECRETS_BATCH_SIZE = 1000;++const SUMMARY_COLUMNS: string[] = [+ "id",+ "sessionId",+ "position",+ "name",+ "type",+ "config",+ "hostPattern",+ "allowedMethods",+ "allowedPathPrefixes",+ "credentialType",+ "credentialConfig",+ "customHeaders",+ "substitutions",+ "createdAt",+ "updatedAt"+];++export const agentVaultSessionInlineServiceDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultSessionInlineService);++ // Never selects the sealed column, so a read that lists sessions holds no secret.+ const findSummariesBySessionIds = async (+ sessionIds: string[],+ tx?: Knex+ ): Promise<TAgentVaultSessionInlineServiceSummaryRow[]> => {+ if (!sessionIds.length) return [];+ try {+ return (await (tx || db.replicaNode())(TableName.AgentVaultSessionInlineService)+ .whereIn("sessionId", sessionIds)+ .select(...SUMMARY_COLUMNS)+ .orderBy("position", "asc")) as TAgentVaultSessionInlineServiceSummaryRow[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault session inline services" });+ }+ };++ const findBySessionId = async (sessionId: string, tx?: Knex): Promise<TAgentVaultSessionInlineServices[]> => {+ try {+ return await (tx || db.replicaNode())(TableName.AgentVaultSessionInlineService)+ .where({ sessionId })+ .orderBy("position", "asc");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault session inline services for resolve" });+ }+ };++ // Writes only the inline service rows, never the session's, whose updatedAt dates an ownerless session's last logs.+ const deleteSecretsBySessionId = async (sessionId: string, tx?: Knex) => {+ try {+ await (tx || db)(TableName.AgentVaultSessionInlineService)+ .where({ sessionId })+ .whereNotNull("encryptedSecrets")+ .update({ encryptedSecrets: null });+ } catch (error) {+ throw new DatabaseError({ error, name: "Delete agent vault session inline service secrets" });+ }+ };++ /**+ * Deletes the secrets of every inline service whose session can no longer resolve: revoked, expired, or left without+ * its owner or the user it acts for, matching deriveSessionStatus. In batches, each its own statement, so no one+ * transaction grows with the number of sessions that ended since the last run.+ */+ const deleteSecretsOfEndedSessions = async () => {+ let deleted = 0;+ try {+ for (;;) {+ // eslint-disable-next-line no-await-in-loop+ const { rows } = (await db.raw(+ `UPDATE ?? AS inline_service SET "encryptedSecrets" = NULL+ WHERE inline_service.id IN (+ SELECT candidate.id FROM ?? AS candidate+ JOIN ?? AS owning_session ON owning_session.id = candidate."sessionId"+ WHERE candidate."encryptedSecrets" IS NOT NULL+ AND (+ owning_session."revokedAt" IS NOT NULL+ OR owning_session."expiresAt" <= NOW()+ OR (owning_session."userId" IS NULL AND owning_session."identityId" IS NULL)+ OR (owning_session."onBehalfOfUserName" IS NOT NULL AND owning_session."onBehalfOfUserId" IS NULL)+ )+ LIMIT ?+ )+ RETURNING inline_service.id`,+ [+ TableName.AgentVaultSessionInlineService,+ TableName.AgentVaultSessionInlineService,+ TableName.AgentVaultSession,+ DELETE_SECRETS_BATCH_SIZE+ ]+ )) as { rows: { id: string }[] };+ deleted += rows.length;+ if (rows.length < DELETE_SECRETS_BATCH_SIZE) break;+ }+ } catch (error) {+ throw new DatabaseError({ error, name: "Delete agent vault inline service secrets of ended sessions" });+ }+ if (deleted) {+ logger.info(`frequent-resource-cleanup: deleted the secrets of ${deleted} agent vault inline services`);+ }+ };++ return { ...orm, findSummariesBySessionIds, findBySessionId, deleteSecretsBySessionId, deleteSecretsOfEndedSessions };+};diff --git 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.tsnew file mode 100644index 0000000000..9902acb04f--- /dev/null+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.test.ts@@ -0,0 +1,236 @@+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("Services 'first' and 'API.example.com' both cover api.example.com:443. Remove it from one of them.");+ expect(() => prepareInlineServices([httpBearer({ hostPattern: "*.example.com" }), httpBearer()])).not.toThrow();+ });+});++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(+ "Service 'uploads.github.com' covers api.github.com:443, which 'github' in the access bundle 'prod' already covers. Remove it from 'uploads.github.com'."+ );+ });++ 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");+ });++ test("the summary carries no secret", () => {+ const summary = toInlineServiceSummary(storedRow({ encryptedSecrets: Buffer.from("sealed") }));+ 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,+ 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();+ });+});diff --git 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.tsnew file mode 100644index 0000000000..6fc0629a44--- /dev/null+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-inline-service-fns.ts@@ -0,0 +1,286 @@+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.+export const inlineServiceDisplayName = ({ name, hostPattern }: { name?: string | null; hostPattern: string }) =>+ name || hostPattern.split(",")[0].trim();++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+ });++ 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+ };+};++const toConflictCandidate = (service: TPreparedInlineService): TConflictCandidate => ({+ id: String(service.position),+ name: inlineServiceDisplayName(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 = input.name ? `Service '${input.name}'` : `Service at index ${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: `Services '${conflict.serviceName}' and '${inlineServiceDisplayName(service)}' both cover ${conflict.patterns.join(", ")}. Remove it from one of them.`+ });+ }+ });++ 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.+ * 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 [conflict] = findHostPatternConflicts(service.hostPattern, accessBundle.services);+ if (conflict) {+ throw new BadRequestError({+ message: `Service '${inlineServiceDisplayName(service)}' covers ${conflict.patterns.join(", ")}, which '${conflict.serviceName}' in the access bundle '${accessBundle.name}' already covers. Remove it from '${inlineServiceDisplayName(service)}'.`+ });+ }+ });+};++export type TAgentVaultSessionInlineServiceSummaryRow = Omit<TAgentVaultSessionInlineServices, "encryptedSecrets">;++// 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: row.name ?? null,+ 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: 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 = { ...credentialConfig, value: secrets.credential.value };+ } else if (+ credentialConfig.type === AgentVaultCredentialType.Basic &&+ secrets?.credential &&+ "username" in secrets.credential+ ) {+ credential = { type: AgentVaultCredentialType.Basic, ...secrets.credential };+ } 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,+ credential,+ customHeaders: customHeaders.map((header, index) => ({ ...header, value: secrets!.customHeaders[index] })),+ substitutions: substitutions.map((substitution, index) => ({+ ...substitution,+ value: secrets!.substitutions[index]+ })),+ personalValuesMissing: false+ };+};diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.tsindex f871ccd331..491c083632 100644--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts@@ -10,11 +10,13 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/import { ms } from "@app/lib/ms";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TUserDALFactory } from "@app/services/user/user-dal";import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";+import { TAgentVaultServiceDALFactory } from "../agent-vault-access-bundle/agent-vault-service-dal";import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";import { findCallerDelegation, resolveOnBehalfOfUser } from "../agent-vault-delegation/agent-vault-on-behalf-of-fns";import { generateSessionLogKey, wrapSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";@@ -23,7 +25,14 @@ import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vauimport { TAgentVaultSessionAccessBundleDALFactory } from "./agent-vault-session-access-bundle-dal";import { TAgentVaultSessionDALFactory, TAgentVaultSessionListRow } from "./agent-vault-session-dal";import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";+import { TAgentVaultSessionInlineServiceDALFactory } from "./agent-vault-session-inline-service-dal";import {+ assertNoAccessBundleConflicts,+ prepareInlineServices,+ toInlineServiceSummary+} from "./agent-vault-session-inline-service-fns";+import {+ TAgentVaultInlineServiceSummary,TGetSessionByIdDTO,TListSessionsDTO,TMintSessionDTO,@@ -45,13 +54,18 @@ export const AGENT_VAULT_ON_BEHALF_OF_SESSION_DEFAULT_TTL = "1h";type TAgentVaultSessionServiceFactoryDep = {agentVaultSessionDAL: TAgentVaultSessionDALFactory;agentVaultSessionAccessBundleDAL: TAgentVaultSessionAccessBundleDALFactory;+ agentVaultSessionInlineServiceDAL: Pick<+ TAgentVaultSessionInlineServiceDALFactory,+ "insertMany" | "findSummariesBySessionIds" | "deleteSecretsBySessionId"+ >;agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;+ agentVaultServiceDAL: Pick<TAgentVaultServiceDALFactory, "findByAccessBundleId">;agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findForIdentity" | "coversUser">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;userDAL: Pick<TUserDALFactory, "findOne">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;- kmsService: Pick<TKmsServiceFactory, "wrapKey">;+ kmsService: Pick<TKmsServiceFactory, "wrapKey" | "createCipherPairWithDataKey">;};export type TAgentVaultSessionServiceFactory = ReturnType<typeof agentVaultSessionServiceFactory>;@@ -59,7 +73,9 @@ export type TAgentVaultSessionServiceFactory = ReturnType<typeof agentVaultSessiexport const agentVaultSessionServiceFactory = ({agentVaultSessionDAL,agentVaultSessionAccessBundleDAL,+ agentVaultSessionInlineServiceDAL,agentVaultAccessBundleDAL,+ agentVaultServiceDAL,agentVaultDelegationDAL,membershipDAL,userDAL,@@ -85,6 +101,17 @@ export const agentVaultSessionServiceFactory = ({status: deriveSessionStatus({ ...session, userId, identityId, onBehalfOfUserId, onBehalfOfUserName })});+ const withInlineServices = async <T extends { id: string }>(sessions: T[]) => {+ const rows = await agentVaultSessionInlineServiceDAL.findSummariesBySessionIds(+ sessions.map((session) => session.id)+ );+ const bySession = new Map<string, TAgentVaultInlineServiceSummary[]>();+ rows.forEach((row) => {+ bySession.set(row.sessionId, [...(bySession.get(row.sessionId) ?? []), toInlineServiceSummary(row)]);+ });+ return sessions.map((session) => ({ ...session, services: bySession.get(session.id) ?? [] }));+ };+const resolveSessionTtl = (ttl: string | undefined, isOnBehalfOf: boolean) =>ttl ?? (isOnBehalfOf ? AGENT_VAULT_ON_BEHALF_OF_SESSION_DEFAULT_TTL : AGENT_VAULT_SESSION_DEFAULT_TTL);@@ -92,6 +119,7 @@ export const agentVaultSessionServiceFactory = ({projectId,ctx,accessBundles,+ services = [],actorName,actorEmail,ttl: requestedTtl,@@ -101,14 +129,22 @@ export const agentVaultSessionServiceFactory = ({const caller = requireSessionActor(ctx);const ttl = resolveSessionTtl(requestedTtl, Boolean(onBehalfOf));- const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultSessionActions.Create,ProjectPermissionSub.AgentVaultSessions);- if (!accessBundles.length) {- throw new BadRequestError({ message: "Name the access bundle this session should carry" });+ if (!accessBundles.length && !services.length) {+ throw new BadRequestError({+ message: "Name the access bundle this session should carry, or send the services it should reach."+ });+ }+ // An inline service names its own hosts and credentials, which is an admin's call, as it is for a bundle's services.+ if (services.length && !isAdmin) {+ throw new ForbiddenRequestError({+ message: "Only an Agent Vault admin can send services with a session. Name an access bundle instead."+ });}if (accessBundles.length > AGENT_VAULT_MAX_SESSION_BUNDLES) {throw new BadRequestError({ message: "A session carries one access bundle. Name only one." });@@ -117,7 +153,11 @@ export const agentVaultSessionServiceFactory = ({throw new BadRequestError({ message: "You've named the same access bundle more than once. Name it only once." });}- const bundles = await agentVaultAccessBundleDAL.find({ projectId, $in: { name: accessBundles } });+ const preparedInlineServices = prepareInlineServices(services);++ const bundles = accessBundles.length+ ? await agentVaultAccessBundleDAL.find({ projectId, $in: { name: accessBundles } })+ : [];const bundlesByName = new Map(bundles.map((bundle) => [bundle.name, bundle]));// An unknown name reads like an ungranted one, so the error never confirms that a bundle exists.const firstUnreachable = (reachable: string[] | null) =>@@ -170,6 +210,34 @@ export const agentVaultSessionServiceFactory = ({}}+ if (preparedInlineServices.length) {+ const bundlesWithServices = await Promise.all(+ accessBundles.map(async (name) => {+ const bundle = bundlesByName.get(name)!;+ return { name: bundle.name, services: await agentVaultServiceDAL.findByAccessBundleId(bundle.id) };+ })+ );+ bundlesWithServices.forEach((bundle) => assertNoAccessBundleConflicts(preparedInlineServices, bundle));+ }++ // Sealed before the transaction: with an external KMS this is a network call, and the transaction stays short.+ let sealInlineSecrets: ((plainText: Buffer) => Buffer) | null = null;+ if (preparedInlineServices.some((service) => service.secrets)) {+ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ sealInlineSecrets = (plainText) => encryptor({ plainText }).cipherTextBlob;+ }+ const inlineServiceRows = preparedInlineServices.map(({ secrets, customHeaders, substitutions, ...service }) => ({+ ...service,+ credentialType: service.credentialConfig.type,+ // Serialized here because the pg driver writes a bare array as a Postgres array, which a jsonb column refuses.+ customHeaders: JSON.stringify(customHeaders),+ substitutions: JSON.stringify(substitutions),+ encryptedSecrets: secrets ? sealInlineSecrets!(Buffer.from(JSON.stringify(secrets))) : null+ }));+const ttlMs = ttl === AGENT_VAULT_SESSION_TTL_NEVER ? null : ms(ttl);const expiresAt = ttlMs === null ? null : new Date(Date.now() + ttlMs);const { token, tokenHash } = generateSessionToken();@@ -197,7 +265,7 @@ export const agentVaultSessionServiceFactory = ({})};- const session = await agentVaultSessionDAL.transaction(async (tx) => {+ const { session, insertedInlineServices } = await agentVaultSessionDAL.transaction(async (tx) => {const created = await agentVaultSessionDAL.createWithId({id: sessionId,@@ -221,7 +289,12 @@ export const agentVaultSessionServiceFactory = ({tx);- return created;+ const inserted = await agentVaultSessionInlineServiceDAL.insertMany(+ inlineServiceRows.map((row) => ({ ...row, sessionId: created.id })),+ tx+ );++ return { session: created, insertedInlineServices: inserted };});return {@@ -234,7 +307,10 @@ export const agentVaultSessionServiceFactory = ({id: bundlesByName.get(name)!.id,name,position- }))+ })),+ services: insertedInlineServices+ .sort((a, b) => a.position - b.position)+ .map((row) => toInlineServiceSummary(row))},token,ttlSeconds: ttlMs === null ? null : Math.floor(ttlMs / 1000),@@ -266,7 +342,7 @@ export const agentVaultSessionServiceFactory = ({offset});- return { sessions: sessions.map(toSessionView), totalCount };+ return { sessions: await withInlineServices(sessions.map(toSessionView)), totalCount };};// A session you may not see reads exactly like one that does not exist.@@ -296,7 +372,10 @@ export const agentVaultSessionServiceFactory = ({ProjectPermissionSub.AgentVaultSessions);- return { session: toSessionView(await findVisibleSession({ projectId, ctx, sessionId, isAdmin })) };+ const [session] = await withInlineServices([+ toSessionView(await findVisibleSession({ projectId, ctx, sessionId, isAdmin }))+ ]);+ return { session };};const revokeSession = async ({ projectId, ctx, sessionId }: TRevokeSessionDTO) => {@@ -313,7 +392,12 @@ export const agentVaultSessionServiceFactory = ({if (session.revokedAt) return { session: toSessionView(session), revokedNow: false };// The timestamp comes from the written row: a read-back could land on a replica that has not seen it.- const revoked = await agentVaultSessionDAL.revokeIfActive(session.id, new Date());+ const revoked = await agentVaultSessionDAL.transaction(async (tx) => {+ const row = await agentVaultSessionDAL.revokeIfActive(session.id, new Date(), tx);+ // Revoked by this call or found already over, the session can't use its inline services' secrets again.+ await agentVaultSessionInlineServiceDAL.deleteSecretsBySessionId(session.id, tx);+ return row;+ });if (revoked) {return { session: toSessionView({ ...session, revokedAt: revoked.revokedAt ?? null }), revokedNow: true };}@@ -357,7 +441,8 @@ export const agentVaultSessionServiceFactory = ({});}- return { session: toSessionView({ ...session, label }), previousLabel: updated.previousLabel };+ const [view] = await withInlineServices([toSessionView({ ...session, label })]);+ return { session: view, previousLabel: updated.previousLabel };};return {diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.tsindex 53a272701c..00fa8006e0 100644--- 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@@ -1,18 +1,73 @@import { TGenericPermission } from "@app/lib/types";import {+ AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultMcpTransport,AgentVaultMemberType,+ AgentVaultServiceType,AgentVaultSessionScope,- AgentVaultSessionStatus+ AgentVaultSessionStatus,+ AgentVaultSubstitutionSurface} from "../agent-vault/agent-vault-enums";/** 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;+ 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;+ name: string | null;+ 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;accessBundles: string[];+ // Inline services, which the API calls the session's services.+ services?: TAgentVaultInlineServiceInput[];/** The caller's name and email, snapshotted from the request. */actorName: string;actorEmail: string | null;diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex 3553392567..fd211ad521 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -12,7 +12,7 @@ never in anything the agent holds.| --- | --- || **Access bundle** | A named set of services. The unit you grant || **Service** | One host pattern set plus its credential |-| **Session** | A minted token naming one actor, one of their bundles, and an expiry. The token *is* the session |+| **Session** | A minted token naming one actor, one of their bundles, services of its own, or both, and an expiry. The token *is* the session || **Proxy** | One egress identity and its CA. Any number of processes can run it from its proxy token |```@@ -198,6 +198,45 @@ is one `agent_vault_delegations` row per identity, with a scope of `all-members`- **Delegation routes take no `AuthMode.OAUTH`.** The admin check reads the role, which a delegated token's scopesdon'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 `bundle-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.+- **The name is optional.** Wherever a name is shown (resolve, so the proxy's messages and session logs, the audit log,+ the Sessions page), an unnamed service goes by its first host (`inlineServiceDisplayName`, mirrored in the frontend).+ 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 proxydiff --git a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.tsindex 0daa6ab1a6..d16f252c7d 100644--- a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts@@ -218,10 +218,12 @@ const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {export const assertCredentialTypeSupported = (definition: TAgentVaultServiceTypeDefinition,- credentialType: AgentVaultCredentialType+ credentialType: AgentVaultCredentialType,+ // Narrower than the type's own list where a caller can't offer every credential, so the refusal names only what works.+ allowedCredentialTypes: AgentVaultCredentialType[] = definition.allowedCredentialTypes) => {- if (definition.allowedCredentialTypes.includes(credentialType)) return;- const allowed = definition.allowedCredentialTypes.map((type) => CREDENTIAL_LABELS[type]);+ if (allowedCredentialTypes.includes(credentialType)) return;+ const allowed = allowedCredentialTypes.map((type) => CREDENTIAL_LABELS[type]);throw new BadRequestError({message: `An ${definition.label} service can't use ${CREDENTIAL_LABELS[credentialType]} as its credential. Use ${allowed.join(" or ")}.`});diff --git a/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.tsindex a0b0305dc7..02e7abe6b8 100644--- a/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts@@ -10,10 +10,12 @@ import {} from "./agent-vault-credential-schemas";import { AgentVaultSubstitutionSurface } from "./agent-vault-enums";import {+ AGENT_VAULT_INLINE_SERVICE_VARIABLE_MESSAGE,AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE,AGENT_VAULT_TOO_MANY_REFERENCES_MESSAGE,hasMalformedVariableReference,- hasTooManyVariableReferences+ hasTooManyVariableReferences,+ hasVariableReference} from "./agent-vault-variable-fns";export const AGENT_VAULT_MAX_CUSTOM_HEADERS = 20;@@ -114,6 +116,23 @@ export const AgentVaultSubstitutionUpdateSchema = z.object({value: secretValueSchema.optional().describe(AGENT_VAULT.SERVICE.updateSubstitutionValue)});+// For every value of a service sent inline with a session. Whoever starts a session names the hosts its inline+// services reach, so a variable reference would let them send any variable's value to a host of their choosing.+export const acceptsNoVariableReferences = (schema: z.ZodString) =>+ schema.refine((value) => !hasVariableReference(value), AGENT_VAULT_INLINE_SERVICE_VARIABLE_MESSAGE);++const inlineSecretValueSchema = acceptsNoVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+);++export const AgentVaultInlineCustomHeaderInputSchema = AgentVaultCustomHeaderInputSchema.extend({+ value: inlineSecretValueSchema.describe(AGENT_VAULT.SESSION.inlineCustomHeaderValue)+});++export const AgentVaultInlineSubstitutionInputSchema = AgentVaultSubstitutionInputSchema.extend({+ value: inlineSecretValueSchema.describe(AGENT_VAULT.SESSION.inlineSubstitutionValue)+});+type TNamed = { name: string };type TPlaceheld = { placeholder: string };diff --git a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.tsindex 722fd124b0..b4782b5541 100644--- a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts@@ -19,6 +19,9 @@ export const AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE = `Double braces are reservexport const AGENT_VAULT_TOO_MANY_REFERENCES_MESSAGE = `A value can use at most ${AGENT_VAULT_MAX_REFERENCES_PER_FIELD} variable references, and a reference that repeats counts each time. Combine some into one variable to use fewer.`;+export const AGENT_VAULT_INLINE_SERVICE_VARIABLE_MESSAGE =+ "Services sent with a session can't use variables, so a value can't wrap text in double braces, as in {{GITHUB_TOKEN}}. Send the value itself, or add the service to an access bundle to use a variable.";+// Every {{...}} counts as a reference, so a mistyped one fails the save instead of reaching a real host as// literal text.const REFERENCE_RE = new RE2(/\{\{([^{}]*)\}\}/g);@@ -36,6 +39,9 @@ export const hasMalformedVariableReference = (text: string) =>export const hasTooManyVariableReferences = (text: string) =>findReferenceTokens(text).length > AGENT_VAULT_MAX_REFERENCES_PER_FIELD;+// Well formed or not, anything that would count as a reference in a service that takes them.+export const hasVariableReference = (text: string) => findReferenceTokens(text).length > 0;+export const findVariableKeys = (text: string) => [...new Set(findReferenceTokens(text).filter((token) => isVariableKey(token)))];diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 82c9fe6120..acd4090cc1 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6908,9 +6908,24 @@ interface AgentVaultSessionMintEvent {metadata: {sessionId: string;label: string | null;- accessBundleId: string;- accessBundleName: string;+ // Null for a session started with inline services only.+ accessBundleId: string | null;+ accessBundleName: string | null;expiresAt: string | null;+ // Set when an admin sent services with the session. Never their values.+ services?: {+ serviceId: string;+ name: string | null;+ serviceType: string;+ serverUrl?: string;+ hostPattern: string;+ credentialType: string;+ headerName?: string;+ allowedMethods: string[] | null;+ allowedPathPrefixes: string[] | null;+ customHeaderNames: string[];+ substitutionPlaceholders: string[];+ }[];// Set when a machine identity started the session on this user's behalf.onBehalfOfUserId?: string;onBehalfOfUserName?: string;diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 57baaf28eb..adc852a136 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4950,7 +4950,32 @@ export const AGENT_VAULT = {SESSION: {sessionId: "The ID of the session.",- accessBundles: "The access bundle this session carries, by name. A list that accepts exactly one name.",+ accessBundles:+ "The access bundle this session carries, by name. A list that accepts one name at most. Leave it out to start a session with services of its own only.",+ inlineServices:+ "Services this session carries itself, alongside its access bundle's or without one. Agent Vault admins only, up to 20. Each takes the same fields as a service in an access bundle, with three differences: the name is optional, every value is sent exactly as given because variables aren't available, and no field can be left to members. They belong to this session only and can't be edited. Their credentials, custom header values and substitution values are deleted once the session is revoked or expires.",+ inlineServiceName:+ "A name for the service, shown in session logs and in the proxy's error messages. Lowercase letters, numbers and hyphens, unique within the session. Leave it out to show the service's host instead.",+ inlineServiceValue:+ "The secret, sent exactly as given. Services sent with a session can't use variables, so it can't wrap text in double braces. Never returned.",+ inlineServiceUsername:+ "The username half of the basic credential, sent exactly as given. May be empty if a password is set. Services sent with a session can't use variables, so it can't wrap text in double braces. Never returned.",+ inlineServicePassword:+ "The password half of the basic credential, sent exactly as given. May be empty if a username is set. Services sent with a session can't use variables, so it can't wrap text in double braces. Never returned.",+ inlineMcpCredential: "The credential the proxy attaches to requests to the MCP server, a bearer token.",+ inlineCustomHeaders:+ "Additional headers the proxy attaches to every request to this service, on top of the credential. Up to 20.",+ inlineSubstitutions: "Placeholders the proxy swaps for a real secret before forwarding. Up to 20.",+ inlineCustomHeadersRead: "The headers the proxy attaches besides the credential, without their values.",+ inlineSubstitutionsRead: "The placeholders the proxy swaps for a real secret, without their values.",+ inlineCustomHeaderValue:+ "The header value, sent exactly as given. Services sent with a session can't use variables, so it can't wrap text in double braces. Never returned.",+ inlineSubstitutionValue:+ "The real value the placeholder is replaced with, sent exactly as given. Services sent with a session can't use variables, so it can't wrap text in double braces. Never returned.",+ inlineServicesRead:+ "The services sent with this session when it was created, without their secrets. Its access bundle's services aren't listed here. Empty when the session carries only an access bundle.",+ inlineServiceId: "The ID of the service sent with this session.",+ inlineServiceNameRead: "The name the service was sent with, or null if it was sent without one.",ttl: "How long the session lasts: a duration such as 30m, 8h or 7d (at least 1m), or never. Defaults to 7d, or to 1h for a session started on behalf of a user.",label:"A short description of what the session is for, such as `nightly deploy` or `support ticket triage`. Up to 128 characters, without line breaks, tabs, or invisible characters. Shown wherever the session is listed.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 38cf70e767..6be510ff29 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -51,6 +51,7 @@ import { AgentVaultSessionLogsNamespace } from "@app/ee/services/agent-vault-sesimport { agentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";import { agentVaultSessionAccessBundleDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal";import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";+import { agentVaultSessionInlineServiceDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-inline-service-dal";import { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { agentVaultSkillBundleDALFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-bundle-dal";import { agentVaultSkillDALFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-dal";@@ -2067,6 +2068,7 @@ export const registerRoutes = async (const agentVaultPersonalValueReferenceDAL = agentVaultPersonalValueReferenceDALFactory(db);const agentVaultSessionDAL = agentVaultSessionDALFactory(db);const agentVaultSessionAccessBundleDAL = agentVaultSessionAccessBundleDALFactory(db);+ const agentVaultSessionInlineServiceDAL = agentVaultSessionInlineServiceDALFactory(db);const agentVaultProxyDAL = agentVaultProxyDALFactory(db);const agentVaultResolveDAL = agentVaultResolveDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);@@ -2140,7 +2142,9 @@ export const registerRoutes = async (const agentVaultSessionService = agentVaultSessionServiceFactory({agentVaultSessionDAL,agentVaultSessionAccessBundleDAL,+ agentVaultSessionInlineServiceDAL,agentVaultAccessBundleDAL,+ agentVaultServiceDAL,agentVaultDelegationDAL,membershipDAL,userDAL,@@ -2272,6 +2276,7 @@ export const registerRoutes = async (agentVaultVariableDAL,agentVaultPersonalValueDAL,agentVaultSessionDAL,+ agentVaultSessionInlineServiceDAL,agentVaultDelegationDAL,agentVaultSessionLogConfigDAL,membershipDAL,@@ -3222,7 +3227,8 @@ export const registerRoutes = async (approvalRequestDAL,approvalRequestGrantsDAL,certificateRequestDAL,- scepTransactionDAL+ scepTransactionDAL,+ agentVaultSessionInlineServiceDAL});const healthAlert = healthAlertServiceFactory({diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex 00686f708f..85d7525d86 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -1,3 +1,4 @@+import { TAgentVaultSessionInlineServiceDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-inline-service-dal";import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TScepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";@@ -40,6 +41,7 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "markExpiredGrants">;certificateRequestDAL: Pick<TCertificateRequestDALFactory, "markExpiredApprovalRequests">;scepTransactionDAL: Pick<TScepTransactionDALFactory, "pruneExpiredTransactions">;+ agentVaultSessionInlineServiceDAL: Pick<TAgentVaultSessionInlineServiceDALFactory, "deleteSecretsOfEndedSessions">;};export type TDailyResourceCleanUpQueueServiceFactory = ReturnType<typeof dailyResourceCleanUpQueueServiceFactory>;@@ -63,7 +65,8 @@ export const dailyResourceCleanUpQueueServiceFactory = ({approvalRequestDAL,approvalRequestGrantsDAL,certificateRequestDAL,- scepTransactionDAL+ scepTransactionDAL,+ agentVaultSessionInlineServiceDAL}: TDailyResourceCleanUpQueueServiceFactoryDep) => {const appCfg = getConfig();@@ -159,6 +162,8 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await certificateRequestDAL.markExpiredApprovalRequests();}await approvalRequestGrantsDAL.markExpiredGrants();+ // Revoke deletes them at once, so this catches sessions that expired or lost their owner within the hour.+ await agentVaultSessionInlineServiceDAL.deleteSecretsOfEndedSessions();}});};diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 2f5e37ed75..8bcc62378a 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -2581,7 +2581,9 @@ export type TAgentVaultSessionCreatedEvent = {event: PostHogEventTypes.AgentVaultSessionCreated;properties: TAgentVaultEventBase & {sessionId: string;- accessBundleId: string;+ // Null for a session started with inline services only.+ accessBundleId: string | null;+ inlineServiceCount: number;ttlSeconds: number | null;isOnBehalfOfUser: boolean;};diff --git a/docs/docs.json b/docs/docs.jsonindex c7c61e5ee1..ecd441ede6 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -752,6 +752,7 @@"documentation/platform/agent-vault/sessions-cli","documentation/platform/agent-vault/sessions-api","documentation/platform/agent-vault/sessions-on-behalf-of-users",+ "documentation/platform/agent-vault/inline-services","documentation/platform/agent-vault/session-logs"]},diff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdxindex 4ed976e318..e672be3aa3 100644--- a/docs/documentation/platform/agent-vault/access-control.mdx+++ b/docs/documentation/platform/agent-vault/access-control.mdx@@ -25,7 +25,7 @@ Agent Vault has one member list for your whole organization, instead of one per| Role | What they can do ||------|------------------|-| **Admin** | <ul><li>Create and manage access bundles, services, variables, skills, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Let machine identities [create sessions on behalf of users](/documentation/platform/agent-vault/sessions-on-behalf-of-users)</li><li>Read audit logs</li></ul> |+| **Admin** | <ul><li>Create and manage access bundles, services, variables, skills, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Let machine identities [create sessions on behalf of users](/documentation/platform/agent-vault/sessions-on-behalf-of-users)</li><li>Send [inline services](/documentation/platform/agent-vault/inline-services) with a session</li><li>Read audit logs</li></ul> || **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li><li>Set up their [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) and keep [personal variables](/documentation/platform/agent-vault/variables#personal-variables)</li><li>View the latest version of the skills in the access bundles granted to them</li></ul> |An admin can use every access bundle without a grant. A member can't use an access bundle until an admin grants it, and only sees the bundles granted to them. On the **Sessions** page, members see their own sessions, and admins can switch between **All Sessions** and **My Sessions**.diff --git a/docs/documentation/platform/agent-vault/inline-services.mdx b/docs/documentation/platform/agent-vault/inline-services.mdxnew file mode 100644index 0000000000..13638d202b--- /dev/null+++ b/docs/documentation/platform/agent-vault/inline-services.mdx@@ -0,0 +1,101 @@+---+title: "Inline services"+description: "Services that an Agent Vault admin sends in the request that creates a session, for that session alone."+---++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 an agent needs a credential that exists for only one run, such as a token that your job runner creates for each job. You can also use them to give one session access to an API that isn't in its access bundle. The other sessions that use the access bundle don't get access to the API.++## 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 **Sessions** page and the [session logs](/documentation/platform/agent-vault/session-logs) show the service's first host)+- 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)+- 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. 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. Neither the API responses nor the audit event includes the inline services' credentials, custom header values, or substitution values.++## 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 "Only an Agent Vault admin can send services with a session"">+ 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 change the role, go to **Access Control** > **Machine Identities** in Agent Vault, select **Change Role** in the machine identity's menu, choose **Admin** in **Product Role**, and select **Save**.+ </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 --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdxindex 7da9e934c6..67d2ee2f80 100644--- a/docs/documentation/platform/agent-vault/proxies.mdx+++ b/docs/documentation/platform/agent-vault/proxies.mdx@@ -165,7 +165,7 @@ To change a setting, select **Edit Settings** on the proxy's menu. If the proxyThe **Traffic Policy** setting controls which hosts agents can reach through the proxy:- **Any host** (default): the proxy forwards every request, and attaches a credential only for hosts covered by a service-- **Access bundle hosts only**: the proxy refuses requests to hosts that no service in the session's access bundle covers, unless the host is an [exception](#exceptions)+- **Access bundle hosts only**: the proxy refuses requests to hosts that no service in the session's access bundle covers, unless the host is an [exception](#exceptions) or one of the session's [inline services](/documentation/platform/agent-vault/inline-services) covers it<Tip>Use **Access bundle hosts only** if the proxy can reach systems that agents shouldn't have access to, such as internal services on the same network.diff --git a/docs/documentation/platform/agent-vault/sessions-api.mdx b/docs/documentation/platform/agent-vault/sessions-api.mdxindex 675fa661a7..abd5297468 100644--- a/docs/documentation/platform/agent-vault/sessions-api.mdx+++ b/docs/documentation/platform/agent-vault/sessions-api.mdx@@ -55,7 +55,7 @@ curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \-d '{"accessBundles": ["<access-bundle-name>"], "ttl": "1h", "label": "nightly deploy"}'```-- `accessBundles` takes a list, but a session can have only one access bundle, so the list must have exactly one name+- `accessBundles` takes a list, but a session can have only one access bundle, so the list must have exactly one name (unless an admin sends [inline services](/documentation/platform/agent-vault/inline-services) instead)- `ttl` accepts a duration of at least one minute, such as `30m`, `8h`, or `7d`, or `never`, and defaults to `7d` (see [Choose how long a session lasts](#choose-how-long-a-session-lasts) to pick a value)- `label` is optional and describes what the session is for, in up to 128 characters (see [Label a session](/documentation/platform/agent-vault/sessions#label-a-session))diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdxindex eadf04152e..53f54d0c66 100644--- a/docs/documentation/platform/agent-vault/sessions.mdx+++ b/docs/documentation/platform/agent-vault/sessions.mdx@@ -3,9 +3,9 @@ title: "Sessions"description: "Time-bound grants that let AI agents access services without holding real credentials."----A session is a time-bound grant scoped to one [access bundle](/documentation/platform/agent-vault/access-bundles). Infisical returns a session token that identifies the session, and the agent uses that token to authenticate to the [proxy](/documentation/platform/agent-vault/proxies) on every outbound request. The proxy then attaches the real credential from the matching [service](/documentation/platform/agent-vault/services) at the network boundary.+A session is a time-bound grant scoped to one [access bundle](/documentation/platform/agent-vault/access-bundles), to [inline services](/documentation/platform/agent-vault/inline-services) that an admin sends with the session, or to both. Infisical returns a session token that identifies the session, and the agent uses that token to authenticate to the [proxy](/documentation/platform/agent-vault/proxies) on every outbound request. The proxy then attaches the real credential from the matching [service](/documentation/platform/agent-vault/services) at the network boundary.-Every session is scoped to one access bundle and expires on a schedule you set. When the session expires (or [you revoke it](#revoke-a-session)), the proxy stops attaching credentials to the agent's requests within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).+Every session expires on a schedule you set. When the session expires (or [you revoke it](#revoke-a-session)), the proxy stops attaching credentials to the agent's requests within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).## Create a session@@ -104,17 +104,18 @@ The **Sessions** page shows each session as **Active**, **Revoked**, or **Expire## Access changes-The access bundle is chosen when you create the session and can't be changed afterwards. However, the proxy re-checks whether the agent still gets credentials once every [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default). Here's how common access changes affect a session:+The access bundle and any inline services are chosen when you create the session and can't be changed afterwards. However, the proxy re-checks whether the agent still gets credentials once every [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default). Here's how common access changes affect a session:- If someone no longer has any grant on an access bundle, directly or through a group, their sessions for that bundle stop getting credentials- If someone still has another grant on the bundle, such as through a group, revoking one grant doesn't affect their sessions- If you delete an access bundle, every session scoped to it stops getting credentials (the session still lists the bundle's name, so you can see what it was)- If you remove someone from Agent Vault, the proxy refuses every request on their sessions+- If someone loses the **Admin** role in Agent Vault, their sessions stop getting credentials for [inline services](/documentation/platform/agent-vault/inline-services)None of these changes removes the [skills](/documentation/platform/agent-vault/skills) that the CLI already installed on the agent's host. To stop agents from using those skills, [delete the installed copies](/documentation/platform/agent-vault/skills#remove-installed-skills).<Note>-If a session stops getting credentials because of a lost grant or a deleted bundle, the proxy still forwards the agent's requests, without credentials. Whether those requests reach the upstream host depends on the proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy).+If a session stops getting credentials because of a lost grant, a deleted bundle, or a lost **Admin** role, the proxy still forwards the agent's requests, without credentials. Whether those requests reach the upstream host depends on the proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy).</Note>## Audit traildiff --git a/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx b/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsxindex 96e3aef56b..fc7e7632c5 100644--- a/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx+++ b/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx@@ -2,6 +2,7 @@ import { useLayoutEffect, useRef, useState } from "react";import { Link, LinkComponentProps } from "@tanstack/react-router";import { Badge, TBadgeProps } from "../../generic/Badge";+import { HoverCard, HoverCardContent, HoverCardTrigger } from "../../generic/HoverCard";import { Popover, PopoverContent, PopoverTrigger } from "../../generic/Popover";import { Tooltip, TooltipContent, TooltipTrigger } from "../../generic/Tooltip";import { cn } from "../../utils";@@ -12,9 +13,13 @@ type TOverflowBadgeListProps<T> = {getLabel: (item: T) => string;getVariant?: (item: T) => TBadgeProps["variant"];getTooltip?: (item: T) => React.ReactNode;+ // For an item whose details need scrolling or links, which a tooltip can't hold. Replaces its tooltip.+ getHoverCard?: (item: T) => React.ReactNode;getClassName?: (item: T) => string | undefined;appearance?: "badge" | "text";icon?: React.ReactNode;+ // For a list whose items aren't all the same kind. Falls back to `icon`.+ getIcon?: (item: T) => React.ReactNode;getLinkProps?: (item: T) => LinkComponentProps | undefined;onItemClick?: (item: T) => void;maxBadgeWidth?: number;@@ -32,9 +37,11 @@ export const OverflowBadgeList = <T,>({getLabel,getVariant,getTooltip,+ getHoverCard,getClassName,appearance = "badge",icon,+ getIcon,getLinkProps,onItemClick,maxBadgeWidth = 160,@@ -45,6 +52,9 @@ export const OverflowBadgeList = <T,>({const [layout, setLayout] = useState<TOverflowLayout>({visibleCount: items.length});+ const iconOf = (item: T) => getIcon?.(item) ?? icon;+ // The narrowest a truncated badge can get still fits an icon, whichever item it is.+ const minimumIcon = icon ?? (items.length ? iconOf(items[0]) : undefined);const visibleItems = items.slice(0, layout.visibleCount);const hiddenCount = Math.max(0, items.length - layout.visibleCount);const hiddenItems = items.slice(visibleItems.length);@@ -113,7 +123,7 @@ export const OverflowBadgeList = <T,>({resizeObserver.observe(container);return () => resizeObserver.disconnect();- }, [getLabel, getVariant, getClassName, icon, items, maxBadgeWidth]);+ }, [getLabel, getVariant, getClassName, icon, getIcon, items, maxBadgeWidth]);const renderItem = (item: T, width?: number) => {const label = getLabel(item);@@ -141,39 +151,57 @@ export const OverflowBadgeList = <T,>({}const linkProps = getLinkProps?.(item);+ const itemIcon = iconOf(item);+ const badge = (+ <Badge+ variant={getVariant?.(item) ?? "neutral"}+ className={getClassName?.(item)}+ isTruncatable+ iconPosition={itemIcon ? "left" : undefined}+ asChild={Boolean(linkProps)}+ style={{+ maxWidth: width ?? maxBadgeWidth+ }}+ >+ {linkProps ? (+ <Link+ {...linkProps}+ onClick={(event) => {+ event.stopPropagation();+ linkProps.onClick?.(event);+ }}+ >+ {itemIcon}+ <span>{label}</span>+ </Link>+ ) : (+ <>+ {itemIcon}+ <span>{label}</span>+ </>+ )}+ </Badge>+ );++ const hoverCard = getHoverCard?.(item);+ if (hoverCard) {+ return (+ <HoverCard key={getKey(item)} openDelay={150} closeDelay={100}>+ <HoverCardTrigger asChild>{badge}</HoverCardTrigger>+ <HoverCardContent+ align="start"+ className="w-auto"+ onClick={(event) => event.stopPropagation()}+ >+ {hoverCard}+ </HoverCardContent>+ </HoverCard>+ );+ }return (<Tooltip key={getKey(item)}>- <TooltipTrigger asChild>- <Badge- variant={getVariant?.(item) ?? "neutral"}- className={getClassName?.(item)}- isTruncatable- iconPosition={icon ? "left" : undefined}- asChild={Boolean(linkProps)}- style={{- maxWidth: width ?? maxBadgeWidth- }}- >- {linkProps ? (- <Link- {...linkProps}- onClick={(event) => {- event.stopPropagation();- linkProps.onClick?.(event);- }}- >- {icon}- <span>{label}</span>- </Link>- ) : (- <>- {icon}- <span>{label}</span>- </>- )}- </Badge>- </TooltipTrigger>+ <TooltipTrigger asChild>{badge}</TooltipTrigger><TooltipContent>{tooltip}</TooltipContent></Tooltip>);@@ -239,10 +267,10 @@ export const OverflowBadgeList = <T,>({variant={getVariant?.(item) ?? "neutral"}className={getClassName?.(item)}isTruncatable- iconPosition={icon ? "left" : undefined}+ iconPosition={iconOf(item) ? "left" : undefined}style={{ maxWidth: maxBadgeWidth }}>- {icon}+ {iconOf(item)}<span>{getLabel(item)}</span></Badge>)@@ -250,8 +278,12 @@ export const OverflowBadgeList = <T,>({{appearance === "text" ? (<span data-overflow-badge-minimum className="w-6 text-sm" />) : (- <Badge data-overflow-badge-minimum isTruncatable iconPosition={icon ? "left" : undefined}>- {icon}+ <Badge+ data-overflow-badge-minimum+ isTruncatable+ iconPosition={minimumIcon ? "left" : undefined}+ >+ {minimumIcon}<span /></Badge>)}diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 75fbb64bf4..b2c4be31c9 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -252,6 +252,24 @@ export type TAgentVaultSessionAccessBundle = {position: number;};+/** A service an admin sent with the session itself. Its secrets are never returned. */+export type TAgentVaultSessionInlineService = {+ id: string;+ name: string | null;+ 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 TAgentVaultSessionActor =| (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }>, "id"> & {id: string | null;@@ -276,6 +294,7 @@ export type TAgentVaultSession = {revokedAt: string | null;createdAt: string;accessBundles: TAgentVaultSessionAccessBundle[];+ services: TAgentVaultSessionInlineService[];};export type TAgentVaultDelegation = {@@ -325,6 +344,7 @@ export type TAgentVaultMintedSession = {expiresAt: string | null;createdAt: string;accessBundles: TAgentVaultSessionAccessBundle[];+ services: TAgentVaultSessionInlineService[];};export type TAgentVaultProxy = {diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex f6f6afd670..1c7f4f2170 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -5,6 +5,7 @@ import {BanIcon,CircleAlertIcon,FilterIcon,+ GlobeIcon,IdCardIcon,LogsIcon,MoreHorizontalIcon,@@ -92,12 +93,18 @@ import { SessionLogReadAccessAlert } from "@app/pages/agent-vault/AgentVaultSettimport { AgentVaultDocsUrls } from "../agent-vault-docs-urls";import { CreateSessionDialog } from "./components/CreateSessionDialog";import { EditSessionLabelDialog } from "./components/EditSessionLabelDialog";+import { InlineServicesList } from "./components/InlineServicesHoverCard";import { RevokeSessionDialog } from "./components/RevokeSessionDialog";import { SampleSessionSheet, SampleSessionTable } from "./components/SampleSessionSheet";import { SessionCreatedDialog } from "./components/SessionCreatedDialog";import { SessionDetailSheet } from "./components/SessionDetailSheet";import { SessionExpiry } from "./components/SessionExpiry";import { SessionIdentity } from "./components/SessionIdentity";+import {+ inlineServicesLabel,+ toAccessItems,+ TSessionAccessItem+} from "./components/sessionInlineServices";import { SessionLabel } from "./components/SessionLabel";import { SESSION_STATUS_PRESENTATION, SessionStatusBadge } from "./components/SessionStatusBadge";@@ -107,6 +114,12 @@ const STATUS_OPTIONS = [AgentVaultSessionStatus.Expired];+const accessItemIcon = (item: TSessionAccessItem) =>+ item.kind === "bundle" ? <PackageIcon /> : <GlobeIcon />;++const accessItemHoverCard = (item: TSessionAccessItem) =>+ item.kind === "inline" ? <InlineServicesList services={item.services} /> : undefined;+export const AgentVaultSessionsPage = () => {const { currentOrg } = useOrganization();const { hasProjectRole } = useProjectPermission();@@ -457,19 +470,32 @@ export const AgentVaultSessionsPage = () => {<TableCell><div className="max-w-72"><OverflowBadgeList- items={session.accessBundles}- getKey={(bundle) => bundle.id ?? bundle.name}- getLabel={(bundle) => bundle.name}- icon={<PackageIcon />}- getClassName={(bundle) => (bundle.id ? undefined : "text-muted")}- getTooltip={(bundle) =>- bundle.id ? bundle.name : `${bundle.name} (deleted)`+ items={toAccessItems(session)}+ getKey={(item) =>+ item.kind === "bundle"+ ? (item.bundle.id ?? item.bundle.name)+ : "inline-services"+ }+ getLabel={(item) =>+ item.kind === "bundle"+ ? item.bundle.name+ : inlineServicesLabel(item.services.length)+ }+ getIcon={accessItemIcon}+ getClassName={(item) =>+ item.kind === "bundle" && !item.bundle.id ? "text-muted" : undefined+ }+ getHoverCard={accessItemHoverCard}+ getTooltip={(item) =>+ item.kind === "bundle" && !item.bundle.id+ ? `${item.bundle.name} (deleted)`+ : undefined}- getLinkProps={(bundle) =>- bundle.id+ getLinkProps={(item) =>+ item.kind === "bundle" && item.bundle.id? linkOptions({to: "/organizations/$orgId/agent-vault/access-bundles/$accessBundleId",- params: { orgId: currentOrg.id, accessBundleId: bundle.id }+ params: { orgId: currentOrg.id, accessBundleId: item.bundle.id }}): undefined}diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/InlineServicesHoverCard.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/InlineServicesHoverCard.tsxnew file mode 100644index 0000000000..7d592f44dd--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/InlineServicesHoverCard.tsx@@ -0,0 +1,55 @@+import { ReactNode } from "react";++import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+ ScrollableContent+} from "@app/components/v3";+import { TAgentVaultSessionInlineService } from "@app/hooks/api/agentVault/types";++import { inlineServiceDisplayName } from "./sessionInlineServices";++type ListProps = {+ services: TAgentVaultSessionInlineService[];+};++export const InlineServicesList = ({ services }: ListProps) => (+ <div className="flex w-72 flex-col gap-2.5">+ <p className="text-xs text-muted">Sent with the session when it was created.</p>+ {/* A hover card portals out of any open sheet, whose scroll lock would otherwise swallow the wheel. */}+ <ScrollableContent+ aria-label="Inline services"+ edgeBehavior="fade"+ outline={false}+ maxHeight="12rem"+ className="overscroll-contain"+ contentClassName="flex flex-col gap-2"+ onWheel={(event) => event.stopPropagation()}+ >+ {services.map((service) => (+ <div key={service.id} className="flex min-w-0 items-center gap-2">+ <ServiceIcon hostPattern={service.hostPattern} className="size-5" />+ <span className="truncate">{inlineServiceDisplayName(service)}</span>+ {service.name && (+ <span className="truncate text-xs text-muted">{service.hostPattern.split(",")[0]}</span>+ )}+ </div>+ ))}+ </ScrollableContent>+ </div>+);++type HoverCardProps = ListProps & {+ children: ReactNode;+};++export const InlineServicesHoverCard = ({ services, children }: HoverCardProps) => (+ <HoverCard openDelay={150} closeDelay={100}>+ <HoverCardTrigger asChild>{children}</HoverCardTrigger>+ <HoverCardContent align="start" className="w-auto">+ <InlineServicesList services={services} />+ </HoverCardContent>+ </HoverCard>+);diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsxindex 34c69a6d04..14c3b01a1f 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx@@ -4,6 +4,7 @@ import { BanIcon, BotIcon, PackageIcon, PencilIcon, UserIcon } from "lucide-reacimport { twMerge } from "tailwind-merge";import { memberDisplayName, memberSubtitle } from "@app/components/agent-vault/MemberName";+import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";import {Button,Detail,@@ -19,17 +20,24 @@ import {SheetDescription,SheetHeader,SheetTitle,- Spinner+ Spinner,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { useOrganization } from "@app/context";import { AgentVaultMemberType, AgentVaultSessionStatus } from "@app/hooks/api/agentVault";import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";+import { InlineServicesHoverCard } from "./InlineServicesHoverCard";import { SessionExpiry } from "./SessionExpiry";+import { inlineServiceDisplayName } from "./sessionInlineServices";import { SessionLogsPanel } from "./SessionLogsPanel";import { SessionStatusBadge } from "./SessionStatusBadge";+const SHOWN_INLINE_SERVICES = 1;+type Props = {session: TAgentVaultSession | undefined;isPending?: boolean;@@ -53,6 +61,9 @@ export const SessionDetailSheet = ({const hasExpired = Boolean(session?.expiresAt && new Date(session.expiresAt).getTime() <= Date.now());+ const services = session?.services ?? [];+ const shownServices = services.slice(0, SHOWN_INLINE_SERVICES);+ const moreServices = services.slice(SHOWN_INLINE_SERVICES);return (<Sheet open={isOpen} onOpenChange={(open) => !open && closeSheet()}>@@ -136,36 +147,77 @@ export const SessionDetailSheet = ({</DetailValue></Detail>)}- <Detail className="min-w-0">- <DetailLabel>- {session.accessBundles.length === 1 ? "Access Bundle" : "Access Bundles"}- </DetailLabel>- <DetailValue className="flex flex-wrap gap-x-4 gap-y-1">- {session.accessBundles.map((bundle) =>- bundle.id ? (- <Link- key={bundle.id}- to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"- params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}- className="group flex min-w-0 items-center gap-2"- >- <PackageIcon className="size-4 shrink-0 text-muted" />- <span className="truncate group-hover:underline group-hover:underline-offset-2">- {bundle.name}+ {session.accessBundles.length > 0 && (+ <Detail className="min-w-0">+ <DetailLabel>+ {session.accessBundles.length === 1 ? "Access Bundle" : "Access Bundles"}+ </DetailLabel>+ <DetailValue className="flex flex-wrap gap-x-4 gap-y-1">+ {session.accessBundles.map((bundle) =>+ bundle.id ? (+ <Link+ key={bundle.id}+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}+ className="group flex min-w-0 items-center gap-2"+ >+ <PackageIcon className="size-4 shrink-0 text-muted" />+ <span className="truncate group-hover:underline group-hover:underline-offset-2">+ {bundle.name}+ </span>+ </Link>+ ) : (+ <span+ key={bundle.name}+ className="flex min-w-0 items-center gap-2 text-muted"+ >+ <PackageIcon className="size-4 shrink-0" />+ <span className="truncate">{bundle.name} (deleted)</span></span>- </Link>- ) : (- <span- key={bundle.name}- className="flex min-w-0 items-center gap-2 text-muted"- >- <PackageIcon className="size-4 shrink-0" />- <span className="truncate">{bundle.name} (deleted)</span>- </span>- )- )}- </DetailValue>- </Detail>+ )+ )}+ </DetailValue>+ </Detail>+ )}+ {session.services.length > 0 && (+ <Detail className="min-w-0">+ <DetailLabel>Inline Services</DetailLabel>+ <DetailValue className="flex flex-wrap items-center gap-x-4 gap-y-1">+ {shownServices.map((service) => (+ <Tooltip key={service.id}>+ <TooltipTrigger asChild>+ <span className="flex min-w-0 items-center gap-2">+ <ServiceIcon+ hostPattern={service.hostPattern}+ className="size-5"+ />+ <span className="truncate">+ {inlineServiceDisplayName(service)}+ </span>+ </span>+ </TooltipTrigger>+ <TooltipContent>+ Sent with this session when it was created, for{" "}+ {service.hostPattern.split(",").join(", ")}+ </TooltipContent>+ </Tooltip>+ ))}+ {moreServices.length > 0 && (+ <InlineServicesHoverCard services={moreServices}>+ <button+ type="button"+ className="shrink-0 rounded-sm text-muted outline-hidden hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ {/* One text node: a dotted underline restarts its dots at each node, leaving a dash at the seam. */}+ <span className="underline decoration-dotted underline-offset-2">+ {`+${moreServices.length} more`}+ </span>+ </button>+ </InlineServicesHoverCard>+ )}+ </DetailValue>+ </Detail>+ )}<Detail><DetailLabel>Created</DetailLabel><DetailValue>diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/sessionInlineServices.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/sessionInlineServices.tsnew file mode 100644index 0000000000..b3d3993d0a--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/sessionInlineServices.ts@@ -0,0 +1,27 @@+import {+ TAgentVaultSession,+ TAgentVaultSessionAccessBundle,+ TAgentVaultSessionInlineService+} from "@app/hooks/api/agentVault/types";++// The same fallback the API uses wherever it names an inline service sent without a name: its first host.+export const inlineServiceDisplayName = ({+ name,+ hostPattern+}: Pick<TAgentVaultSessionInlineService, "name" | "hostPattern">) =>+ name || hostPattern.split(",")[0].trim();++export const inlineServicesLabel = (count: number) =>+ count === 1 ? "1 inline service" : `${count} inline services`;++export type TSessionAccessItem =+ | { kind: "bundle"; bundle: TAgentVaultSessionAccessBundle }+ | { kind: "inline"; services: TAgentVaultSessionInlineService[] };++// A session's bundle, then one more badge for the services it was sent with.+export const toAccessItems = (+ session: Pick<TAgentVaultSession, "accessBundles" | "services">+): TSessionAccessItem[] => [+ ...session.accessBundles.map((bundle) => ({ kind: "bundle" as const, bundle })),+ ...(session.services.length ? [{ kind: "inline" as const, services: session.services }] : [])+];