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
Merge branch 'main' of https://github.com/Infisical/infisical into sheensantoscapadngan/feat-agent-vault-mcp-proxy
Sheen Capadngan7fa9d1ee925b
diff --cc backend/e2e-test/routes/v1/agent-vault.spec.tsindex 5b3edbbe46,aa09133db7..65ed7f047a--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@@ -7,10 -8,8 +8,11 @@@ import { addUserMembership, createUserimport { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";+import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { MAX_OAUTH_SCOPES } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns";+import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";+ import { agentVaultPersonalValueDALFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";import {AGENT_VAULT_MAX_PROXIES_PER_ORG,@@@ -839,388 -801,6 +841,381 @@@ describe("Agent Vault V1 Router", asyn});});+ describe("MCP services", async () => {+ const servicesUrl = (bundleId: string) => `/api/v1/agent-vault/access-bundles/${bundleId}/services`;++ const createMcpService = async (bundleId: string, name: string, serverUrl: string) => {+ const res = await inject("POST", servicesUrl(bundleId), {+ type: "mcp",+ name,+ serverUrl,+ transport: "streamable-http",+ credential: { type: "bearer", value: "mcp-token" }+ });+ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload) as { service: { id: string; hostPattern: string } }).service;+ };++ const messageOf = (res: { payload: string }) => (JSON.parse(res.payload) as { message: string }).message;++ test("an MCP service takes its host from the server URL, and moves with it", async () => {+ const bundle = await createAccessBundle("mcp-host-pattern");++ const res = await inject("POST", servicesUrl(bundle.id), {+ type: "mcp",+ name: "linear",+ serverUrl: "https://mcp.linear.app/mcp",+ transport: "sse",+ credential: { type: "bearer", value: "lin_api_secret" }+ });+ expect(res.statusCode).toBe(200);+ const { service } = JSON.parse(res.payload) as {+ service: { id: string; type: string; hostPattern: string; serverUrl: string; transport: string };+ };+ expect(service).toMatchObject({+ type: "mcp",+ hostPattern: "mcp.linear.app",+ serverUrl: "https://mcp.linear.app/mcp",+ transport: "sse"+ });+ expect(res.payload).not.toContain("lin_api_secret");++ const withPort = await createMcpService(bundle.id, "internal", "https://mcp.example.com:8443/mcp");+ expect(withPort.hostPattern).toBe("mcp.example.com:8443");++ const moved = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {+ type: "mcp",+ serverUrl: "https://mcp.linear.dev/mcp"+ });+ expect(moved.statusCode).toBe(200);+ expect(JSON.parse(moved.payload).service.hostPattern).toBe("mcp.linear.dev");+ });++ test("a field that belongs to the other type is refused by name, on create and update", async () => {+ const bundle = await createAccessBundle("mcp-wrong-fields");+ const mcp = {+ type: "mcp",+ name: "linear",+ serverUrl: "https://mcp.linear.app/mcp",+ transport: "streamable-http",+ credential: { type: "bearer", value: "token" }+ };++ const withHttpFields = await inject("POST", servicesUrl(bundle.id), {+ ...mcp,+ hostPattern: "mcp.linear.app",+ allowedMethods: ["GET"]+ });+ expect(withHttpFields.statusCode).toBe(400);+ expect(messageOf(withHttpFields)).toContain("An MCP service doesn't take 'hostPattern' or 'allowedMethods'.");++ const withBasic = await inject("POST", servicesUrl(bundle.id), {+ ...mcp,+ credential: { type: "basic", username: "user", password: "pass" }+ });+ expect(withBasic.statusCode).toBe(400);+ expect(messageOf(withBasic)).toContain("An MCP service can't use basic auth as its credential.");++ const httpWithServerUrl = await inject("POST", servicesUrl(bundle.id), {+ type: "http",+ name: "github",+ hostPattern: "api.github.com",+ serverUrl: "https://api.github.com/mcp",+ credential: { type: "bearer", value: "token" }+ });+ expect(httpWithServerUrl.statusCode).toBe(400);+ expect(messageOf(httpWithServerUrl)).toContain("An HTTP service doesn't take 'serverUrl'.");++ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");+ const patchedHostPattern = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {+ type: "mcp",+ hostPattern: "other.example.com"+ });+ expect(patchedHostPattern.statusCode).toBe(400);+ expect(messageOf(patchedHostPattern)).toContain("An MCP service doesn't take 'hostPattern'.");+ });++ test("a service's type can't be changed", async () => {+ const bundle = await createAccessBundle("mcp-type-change");+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");++ const url = `${servicesUrl(bundle.id)}/${service.id}`;+ const res = await inject("PATCH", url, { type: "http", name: "renamed" });+ expect(res.statusCode).toBe(400);+ expect(messageOf(res)).toContain("The service 'linear' is an MCP service, so send 'type': 'mcp'.");++ expect((await inject("PATCH", url, { name: "renamed" })).statusCode).toBe(422);+ expect((await inject("PATCH", url, { type: "mcp" })).statusCode).toBe(422);++ const stored = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);+ expect(stored.payload).toContain('"type":"mcp"');+ expect(stored.payload).not.toContain("renamed");+ });++ test("a service read back unchanged, minus its credential, is accepted as an update", async () => {+ const bundle = await createAccessBundle("read-back");+ const mcp = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");+ const http = await inject("POST", servicesUrl(bundle.id), {+ type: "http",+ name: "stripe",+ hostPattern: "api.stripe.com",+ credential: { type: "passthrough" }+ });+ expect(http.statusCode).toBe(200);++ type TReadService = Record<string, unknown> & { id: string; credential: unknown };+ const read = JSON.parse((await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).payload) as {+ accessBundle: { services: TReadService[] };+ };+ expect(read.accessBundle.services.map((service) => service.id).sort()).toEqual(+ [mcp.id, (http.json().service as { id: string }).id].sort()+ );++ await Promise.all(+ read.accessBundle.services.map(async ({ id, accessBundleId, credential, createdAt, updatedAt, ...fields }) => {+ const res = await inject("PATCH", `${servicesUrl(bundle.id)}/${id}`, fields);+ expect(res.statusCode).toBe(200);+ const { service } = res.json() as { service: TReadService };+ expect(service).toMatchObject(fields);+ })+ );+ });++ describe("credential refresh", async () => {+ // A real enrolled proxy on the real route, so the session and proxy checks run as they do in production.+ const proxyFor = async (bundle: { name: string }, proxyName: string) => {+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "1h" });+ expect(mint.statusCode).toBe(200);+ const { session } = JSON.parse(mint.payload) as { session: { token: string } };++ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: proxyName });+ expect(created.statusCode).toBe(200);- const { token } = JSON.parse(created.payload) as { token: string };- const login = await testServer.inject({- method: "POST",- url: "/api/v1/agent-vault/proxy/login",- body: { method: ResourceAuthMethodType.Token, token, rootCaCertificate: await createProxyCaPem() }- });- expect(login.statusCode).toBe(200);- const { accessToken } = JSON.parse(login.payload) as { accessToken: string };++ const { proxyToken: accessToken } = JSON.parse(created.payload) as { proxyToken: string };++ return (serviceId: string, hostPattern: string) =>+ testServer.inject({+ method: "POST",+ url: `/api/v1/agent-vault/proxy/services/${serviceId}/credential-refresh`,+ headers: { authorization: `Bearer ${accessToken}`, "x-infisical-agent-session": session.token },+ body: { hostPattern, rejectedTokenHash: "a".repeat(64) }+ });+ };++ test("a service outside the session is a 404, and one without OAuth is a 400", async () => {+ const bundle = await createAccessBundle("refresh-not-found");+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");+ const otherBundle = await createAccessBundle("refresh-other-bundle");+ const outside = await createMcpService(otherBundle.id, "linear", "https://mcp.linear.app/mcp");+ const refresh = await proxyFor(bundle, "refresh-not-found");++ const unknown = await refresh(crypto.randomUUID(), "mcp.linear.app");+ expect(unknown.statusCode).toBe(404);+ const otherSession = await refresh(outside.id, "mcp.linear.app");+ expect(otherSession.statusCode).toBe(404);++ const bearer = await refresh(service.id, "mcp.linear.app");+ expect(bearer.statusCode).toBe(400);+ expect(messageOf(bearer)).toBe(+ "The service 'linear' doesn't use OAuth, so Infisical can't refresh its credential."+ );+ });++ test("a host pattern the service no longer has is a 409, so no token goes to the old host", async () => {+ const bundle = await createAccessBundle("refresh-moved");+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");+ // Connecting OAuth needs a browser sign-in, so the row is switched to OAuth directly.+ await testDb("agent_vault_services")+ .where({ id: service.id })+ .update({+ credentialType: "oauth",+ credentialConfig: { status: "connected", accessTokenHash: "a".repeat(64) }+ });+ const refresh = await proxyFor(bundle, "refresh-moved");++ const res = await refresh(service.id, "mcp.old-linear.app");+ expect(res.statusCode).toBe(409);+ expect(messageOf(res)).toBe(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ });+ });+ });++ // The unit tests run these against a JS copy of the SQL. Only Postgres can show the compare, the jsonb merge and+ // the union happen in one UPDATE, against the row being written.+ describe("OAuth credential writes (postgres)", async () => {+ const serviceDAL = agentVaultServiceDALFactory(testDb as never);+ const SEALED = Buffer.from("sealed-credential-1");+ const TOKEN_HASH = "b".repeat(64);++ const oauthService = async (name: string, config: Record<string, unknown> = {}) => {+ const bundle = await createAccessBundle(name);+ const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "mcp",+ name,+ serverUrl: "https://mcp.linear.app/mcp",+ transport: "streamable-http",+ credential: { type: "bearer", value: "token" }+ });+ expect(res.statusCode).toBe(200);+ const { service } = JSON.parse(res.payload) as { service: { id: string } };+ // Connecting OAuth needs a browser sign-in, so the row is switched to OAuth directly.+ await testDb("agent_vault_services")+ .where({ id: service.id })+ .update({+ credentialType: "oauth",+ encryptedCredential: SEALED,+ credentialConfig: {+ status: "connected",+ accessTokenHash: TOKEN_HASH,+ grantedScopes: ["read"],+ requiredScopes: [],+ ...config+ }+ });+ return service.id;+ };++ const storedConfig = async (id: string) =>+ (await testDb("agent_vault_services").where({ id }).first()).credentialConfig as Record<string, unknown>;++ test("a member reads a service's OAuth setup but not the admin's sign-in state", async () => {+ const id = await oauthService("oauth-member-read", {+ issuer: "https://mcp.linear.app",+ expiresAt: "2030-01-01T00:00:00.000Z",+ authorizedAt: "2026-01-01T00:00:00.000Z",+ lastError: "Linear refused the refresh for [email protected]"+ });+ const { accessBundleId } = await testDb("agent_vault_services").where({ id }).first();+ const member = await createUaIdentity(`av-oauth-member-${Date.now()}`);+ type TBundleRead = { accessBundle: { services: { credential: Record<string, unknown> }[] } };++ try {+ expect(+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [member.id], role: "member" }))+ .statusCode+ ).toBe(200);+ expect(+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${accessBundleId}/members`, {+ machineIdentityIds: [member.id]+ })+ ).statusCode+ ).toBe(200);++ const reached = await member.asIdentity("GET", `/api/v1/agent-vault/access-bundles/${accessBundleId}`);+ expect(reached.statusCode).toBe(200);+ const { credential } = (JSON.parse(reached.payload) as TBundleRead).accessBundle.services[0];+ expect(credential).toEqual({+ type: "oauth",+ status: "connected",+ issuer: "https://mcp.linear.app",+ grantedScopes: ["read"],+ requiredScopes: []+ });+ expect(reached.payload).not.toContain("[email protected]");++ const asAdmin = JSON.parse(+ (await inject("GET", `/api/v1/agent-vault/access-bundles/${accessBundleId}`)).payload+ ) as TBundleRead;+ expect(asAdmin.accessBundle.services[0].credential).toMatchObject({+ expiresAt: "2030-01-01T00:00:00.000Z",+ authorizedAt: "2026-01-01T00:00:00.000Z",+ lastError: "Linear refused the refresh for [email protected]"+ });+ } finally {+ await deleteUaIdentity(member.id);+ }+ });++ test("compareAndSwapCredential writes only over the sealed credential it read, and merges just its keys", async () => {+ const id = await oauthService("cas-write");+ const swapped = await serviceDAL.compareAndSwapCredential({+ id,+ expectedEncryptedCredential: SEALED,+ encryptedCredential: Buffer.from("sealed-credential-2"),+ credentialConfigPatch: { accessTokenHash: "c".repeat(64), lastError: null }+ });+ expect(swapped?.credentialConfig).toMatchObject({ accessTokenHash: "c".repeat(64), grantedScopes: ["read"] });++ const stale = await serviceDAL.compareAndSwapCredential({+ id,+ expectedEncryptedCredential: SEALED,+ encryptedCredential: Buffer.from("sealed-credential-3"),+ credentialConfigPatch: { accessTokenHash: "d".repeat(64) }+ });+ expect(stale).toBeUndefined();+ const row = await testDb("agent_vault_services").where({ id }).first();+ expect(row.encryptedCredential.toString()).toBe("sealed-credential-2");+ expect(row.credentialConfig.accessTokenHash).toBe("c".repeat(64));+ });++ test("compareAndSwapCredential keeps needs-additional-scopes only when asked, judged on the stored row", async () => {+ const patch = { status: "connected", lastError: null };+ const kept = await oauthService("cas-keep-scopes", { status: "needs-additional-scopes", lastError: "old" });+ await serviceDAL.compareAndSwapCredential({+ id: kept,+ expectedEncryptedCredential: SEALED,+ credentialConfigPatch: patch,+ keepAdditionalScopesStatus: true+ });+ expect(await storedConfig(kept)).toMatchObject({ status: "needs-additional-scopes", lastError: null });++ const replaced = await oauthService("cas-replace-scopes", { status: "needs-additional-scopes" });+ await serviceDAL.compareAndSwapCredential({+ id: replaced,+ expectedEncryptedCredential: SEALED,+ credentialConfigPatch: patch+ });+ expect((await storedConfig(replaced)).status).toBe("connected");+ });++ test("addRequiredScopes unions in the UPDATE, so two reports at once both land", async () => {+ const id = await oauthService("scopes-concurrent");+ const report = (requiredScopes: string[]) =>+ serviceDAL.addRequiredScopes({+ id,+ expectedEncryptedCredential: SEALED,+ rejectedTokenHash: TOKEN_HASH,+ requiredScopes+ });++ await Promise.all([report(["admin"]), report(["write", "admin"])]);+ const config = await storedConfig(id);+ expect(config.status).toBe("needs-additional-scopes");+ expect([...(config.requiredScopes as string[])].sort()).toEqual(["admin", "write"]);+ });++ test("addRequiredScopes writes nothing for granted scopes, a replaced token, or a dead login", async () => {+ const id = await oauthService("scopes-refused");+ const report = (requiredScopes: string[], rejectedTokenHash = TOKEN_HASH) =>+ serviceDAL.addRequiredScopes({ id, expectedEncryptedCredential: SEALED, rejectedTokenHash, requiredScopes });++ expect(await report(["read"])).toBeUndefined();+ expect(await report(["admin"], "e".repeat(64))).toBeUndefined();++ const dead = await oauthService("scopes-dead-login", { status: "needs-reauthorization" });+ expect(+ await serviceDAL.addRequiredScopes({+ id: dead,+ expectedEncryptedCredential: SEALED,+ rejectedTokenHash: TOKEN_HASH,+ requiredScopes: ["admin"]+ })+ ).toBeUndefined();+ expect(await storedConfig(id)).toMatchObject({ status: "connected", requiredScopes: [] });+ });++ test("addRequiredScopes stops growing the list at the scope limit", async () => {+ const id = await oauthService("scopes-cap");+ await serviceDAL.addRequiredScopes({+ id,+ expectedEncryptedCredential: SEALED,+ rejectedTokenHash: TOKEN_HASH,+ requiredScopes: Array.from({ length: MAX_OAUTH_SCOPES + 5 }, (_, index) => `scope-${index}`)+ });+ expect((await storedConfig(id)).requiredScopes).toHaveLength(MAX_OAUTH_SCOPES);+ });+ });+describe("variables", async () => {const variablesUrl = "/api/v1/agent-vault/variables";const servicesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`;diff --cc backend/src/@types/fastify.d.tsindex ed6d7493e0,51a4c4e59b..b671cbbb21--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@@ -8,7 -8,7 +8,8 @@@ import { TAccessApprovalRequestServiceFimport { TAgentProxyCaServiceFactory } from "@app/ee/services/agent-proxy-ca/agent-proxy-ca-service";import { TAgentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";import { TAgentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";+import { TAgentVaultOauthServiceFactory } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";+ import { TAgentVaultPersonalValueServiceFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-service";import { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";@@@ -387,8 -387,8 +388,9 @@@ declare module "fastify"secretScanningV2ProjectResolver: TSecretScanningV2ProjectResolverFactory;agentVaultProjectResolver: TAgentVaultProjectResolverFactory;agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;+ agentVaultOauth: TAgentVaultOauthServiceFactory;agentVaultVariable: TAgentVaultVariableServiceFactory;+ agentVaultPersonalValue: TAgentVaultPersonalValueServiceFactory;agentVaultProxy: TAgentVaultProxyServiceFactory;agentVaultSession: TAgentVaultSessionServiceFactory;agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;diff --cc backend/src/db/sanitized-schema.yamlindex b202d1f64a,977cfc7884..2e03d367dc--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@@ -78,7 -89,7 +89,8 @@@ tables- credentialType- allowedMethods- allowedPathPrefixes+ - type+ - memberProvidedFields- createdAt- updatedAtdiff --cc backend/src/db/schemas/agent-vault-services.tsindex 68257b9616,a9b8ee45ab..17116975a7--- a/backend/src/db/schemas/agent-vault-services.ts+++ b/backend/src/db/schemas/agent-vault-services.ts@@@ -21,8 -21,7 +21,9 @@@ export const AgentVaultServicesSchemaupdatedAt: z.date(),allowedMethods: z.string().array().nullable().optional(),allowedPathPrefixes: z.string().array().nullable().optional(),+ type: z.string().default("http"),- config: z.unknown().nullable().optional()++ config: z.unknown().nullable().optional(),+ memberProvidedFields: z.string().array().nullable().optional()});export type TAgentVaultServices = z.infer<typeof AgentVaultServicesSchema>;diff --cc backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex becaab43a7,11e38e5522..e305b0a408--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts@@@ -20,17 -20,25 +20,18 @@@ import { PostHogEventTypes } from "@appimport { actorContext } from "./agent-vault-router-fns";import {AgentVaultActorRefSchema,- AgentVaultAllowedMethodsSchema,- AgentVaultAllowedPathPrefixesSchema,AgentVaultCreatedMemberSchema,- AgentVaultCredentialInputSchema,- AgentVaultCredentialUpdateSchema,- AgentVaultCustomHeadersInputSchema,- AgentVaultCustomHeadersUpdateSchema,- AgentVaultHostPatternSchema,+ AgentVaultCreateServiceBodySchema,- AgentVaultCredentialUpdateSchema,agentVaultListQuery,AgentVaultMemberIdsSchema,AgentVaultMemberRevokeIdsSchema,AgentVaultMemberSchema,AgentVaultNameSchema,+ AgentVaultPersonalValueInputSchema,+ AgentVaultPersonalValuesSchema,AgentVaultProductMemberSchema,AgentVaultServiceSchema,- AgentVaultSubstitutionsInputSchema,- AgentVaultSubstitutionsUpdateSchema+ AgentVaultUpdateServiceBodySchema} from "./agent-vault-schemas";const AccessBundleDescriptionSchema = z@@@ -321,12 -341,12 +329,17 @@@ export const registerAgentVaultAccessBuservice.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerName : undefined,headerPrefix:service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerPrefix : undefined,+ oauthIssuer:+ service.credential.type === AgentVaultCredentialType.OAuth ? service.credential.issuer : undefined,+ oauthScopes:+ service.credential.type === AgentVaultCredentialType.OAuth ? service.credential.grantedScopes : undefined,allowedMethods: service.allowedMethods,allowedPathPrefixes: service.allowedPathPrefixes,+ memberProvidedFields:- service.credential.type === AgentVaultCredentialType.Passthrough- ? undefined- : service.credential.memberProvidedFields,++ service.credential.type === AgentVaultCredentialType.Bearer ||++ service.credential.type === AgentVaultCredentialType.Basic++ ? service.credential.memberProvidedFields++ : undefined,customHeaderNames: service.customHeaders.map((header) => header.name),substitutionPlaceholders: service.substitutions.map((substitution) => substitution.placeholder),variableKeys: variableKeysOf(service)@@@ -374,14 -406,14 +387,15 @@@},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {- const { service, accessBundleName, update } = await server.services.agentVaultAccessBundle.updateService({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- accessBundleId: req.params.accessBundleId,- serviceId: req.params.serviceId,- ...req.body- });- const { service, accessBundleName, credentialReplaced } =++ const { service, accessBundleName, update, credentialReplaced } =+ await server.services.agentVaultAccessBundle.updateService({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ accessBundleId: req.params.accessBundleId,+ serviceId: req.params.serviceId,+ ...req.body+ });+ const isOauthAuthorized = req.body.credential?.type === AgentVaultCredentialType.OAuth;await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@@ -409,29 -437,26 +423,36 @@@req.body.credential?.type === AgentVaultCredentialType.Bearer? req.body.credential.headerPrefix: undefined,- allowedMethods: req.body.allowedMethods,- allowedPathPrefixes: req.body.allowedPathPrefixes,+ oauthIssuer:+ isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth+ ? service.credential.issuer+ : undefined,+ oauthScopes:+ isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth+ ? service.credential.grantedScopes+ : undefined,+ allowedMethods: update.allowedMethods,+ allowedPathPrefixes: update.allowedPathPrefixes,+ // The setting after the update, present whenever the update touched the credential.+ memberProvidedFields:- req.body.credential && service.credential.type !== AgentVaultCredentialType.Passthrough++ req.body.credential &&++ (service.credential.type === AgentVaultCredentialType.Bearer ||++ service.credential.type === AgentVaultCredentialType.Basic)+ ? service.credential.memberProvidedFields+ : undefined,customHeaderNames: req.body.customHeaders?.map((header) => header.name),// A row omitting a value keeps the stored secret, so sending one is what marks a rotation.// Without this a rotation and a no-op save write the same row.customHeadersReplaced: req.body.customHeaders?.filter((header) => header.value !== undefined).map((header) => header.name),- substitutionPlaceholders: req.body.substitutions?.map((substitution) => substitution.placeholder),- substitutionsReplaced: req.body.substitutions+ substitutionPlaceholders: update.substitutions?.map((substitution) => substitution.placeholder),+ substitutionsReplaced: update.substitutions?.filter((substitution) => substitution.value !== undefined).map((substitution) => substitution.placeholder),- credentialReplaced: isStoredSecretReplaced(req.body.credential),+ credentialReplaced,variableKeys:- req.body.credential || req.body.customHeaders || req.body.substitutions+ req.body.credential || req.body.customHeaders || update.substitutions? variableKeysOf(service): undefined}diff --cc backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex c04b510a7b,297571863f..9be6d07eb1--- 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@@@ -16,79 -6,55 +16,87 @@@ importAgentVaultSessionLogChunkCreateResponseSchema,AgentVaultSessionLogChunkCreateSchema} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-schemas";- import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";- import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";- import { logger } from "@app/lib/logger";+ import { UnauthorizedError } from "@app/lib/errors";import {+ agentVaultBootstrapLimit,+ agentVaultCredentialRefreshLimit,agentVaultHeartbeatLimit,agentVaultResolveLimit,- agentVaultSessionLogChunkLimit,- writeLimit+ agentVaultSessionLogChunkLimit} from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";- import { ActorType, AuthMode } from "@app/services/auth/auth-type";+ import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";+import { AgentVaultHostPatternSchema } from "./agent-vault-schemas";+const ProxyConfigSchema = z.object({trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),allowedHosts: z.string().nullable().describe(AGENT_VAULT.PROXY.allowedHosts),pollInterval: z.number().describe(AGENT_VAULT.PROXY.pollInterval)});+ const RootCaSchema = z+ .object({+ certificate: z.string().describe(AGENT_VAULT.PROXY.rootCaCertificatePem),+ privateKey: z.string().describe(AGENT_VAULT.PROXY.rootCaPrivateKey)+ })+ .describe(AGENT_VAULT.PROXY.rootCa);+const SESSION_HEADER = "x-infisical-agent-session";+const SessionHeaderSchema = z+ .object({+ [SESSION_HEADER]: z+ .string()+ .trim()+ .min(1)+ .max(128)+ .startsWith(AGENT_VAULT_SESSION_TOKEN_PREFIX)+ .describe(AGENT_VAULT.PROXY.sessionToken)+ })+ .passthrough();++// `source` and `expiresAt` are only on an OAuth credential. A proxy that predates them injects it as any bearer.+const ResolvedBearerCredentialSchema = z+ .object({+ type: z.literal(AgentVaultCredentialType.Bearer).describe(AGENT_VAULT.CREDENTIAL_REFRESH.credentialType),+ headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),+ headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix),+ value: z.string().describe(AGENT_VAULT.CREDENTIAL_REFRESH.value),+ source: z.literal(AgentVaultCredentialType.OAuth).optional().describe(AGENT_VAULT.CREDENTIAL_REFRESH.source),+ expiresAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthExpiresAt)+ })+ .describe(JSON.stringify({ title: "Bearer" }));++const RejectedTokenHashSchema = z+ .string()+ .length(64)+ .regex(new RE2(/^[0-9a-fA-F]{64}$/), "Must be the hex sha256 of the rejected access token");+export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvider) => {+ // POST, not GET: a proxy serving its own certificate authority reports it here, and that is recorded.server.route({method: "POST",- url: "/login",- config: { rateLimit: writeLimit },+ url: "/bootstrap",+ config: { rateLimit: agentVaultBootstrapLimit },schema: {hide: true,- operationId: "loginAgentVaultProxy",+ operationId: "bootstrapAgentVaultProxy",description:- "Proxy login. Body discriminates on `method`; token exchanges a one-time enrollment token for the proxy's access token.",+ "Start a proxy: returns its identity, settings and, unless it serves its own, the certificate authority",tags: [ApiDocsTags.AgentVaultProxies],- body: z.discriminatedUnion("method", [- z.object({- method: z.literal(ResourceAuthMethodType.Token),- token: z.string().trim().min(1).max(256).describe(AGENT_VAULT.PROXY.enrollmentToken),- rootCaCertificate: z.string().trim().min(1).max(16384).describe(AGENT_VAULT.PROXY.rootCaCertificate)- })- ]),+ body: z.object({+ servedCaCertificate: z+ .string()+ .trim()+ .min(1)+ .max(16384)+ .optional()+ .describe(AGENT_VAULT.PROXY.servedCaCertificate)+ }),response: {200: z.object({proxyId: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId),diff --cc backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex c4c0e53735,4fc1fef268..43fa864539--- 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@@@ -6,14 -6,14 +6,17 @@@ importAGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";import {+ AGENT_VAULT_MEMBER_PROVIDED_FIELDS,AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,AgentVaultMemberType,+ AgentVaultOauthStatus,+ AgentVaultServiceType,AgentVaultSubstitutionSurface,- AgentVaultVariableReferenceField+ AgentVaultVariableReferenceField,+ AgentVaultVariableScope,+ TAgentVaultMemberProvidedField} from "@app/ee/services/agent-vault/agent-vault-enums";import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix-schemas";@@@ -45,131 -44,191 +48,222 @@@ export const AgentVaultNameSchema = sluexport const AgentVaultHostPatternSchema = hostPatternSchema.describe(AGENT_VAULT.SERVICE.hostPattern);- const basicHalvesAreNotBothEmpty = (- data: { type: AgentVaultCredentialType; username?: string; password?: string },- ctx: z.RefinementCtx- ) => {- // Either half may be blank, but not both. The check cannot be an object-level refine, because- // discriminatedUnion options must be plain objects.- if (data.type !== AgentVaultCredentialType.Basic) return;- if (data.username === undefined || data.password === undefined) return;- if (data.username.length > 0 || data.password.length > 0) return;-- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["username"],- message: "A basic credential needs a username, a password, or both"- });+ const bearerMemberProvidedFieldsSchema = z+ .enum([AgentVaultVariableReferenceField.CredentialValue])+ .array()+ .max(1)+ .describe(AGENT_VAULT.SERVICE.bearerMemberProvidedFields);++ const basicMemberProvidedFieldsSchema = z+ .enum(AGENT_VAULT_MEMBER_PROVIDED_FIELDS)+ .array()+ .max(2)+ .describe(AGENT_VAULT.SERVICE.basicMemberProvidedFields);++ type TCredentialShape = {+ type: AgentVaultCredentialType;+ value?: string;+ username?: string;+ password?: string;+ memberProvidedFields?: TAgentVaultMemberProvidedField[];+ };++ // The member-provided field each admin credential field stands in for.+ const MEMBER_FIELD_OF_INPUT: Record<"value" | "username" | "password", TAgentVaultMemberProvidedField> = {+ value: AgentVaultVariableReferenceField.CredentialValue,+ username: AgentVaultVariableReferenceField.CredentialUsername,+ password: AgentVaultVariableReferenceField.CredentialValue};+ // Discriminated union options must be plain objects, so the checks that read two fields run on the union.+ const checkCredentialFields =+ ({ requireValues }: { requireValues: boolean }) =>+ (data: TCredentialShape, ctx: z.RefinementCtx) => {+ const memberProvided = new Set(data.memberProvidedFields ?? []);++ // A member-provided field has no admin value: each member sends their own.+ (["value", "username", "password"] as const).forEach((field) => {+ if (data[field] !== undefined && memberProvided.has(MEMBER_FIELD_OF_INPUT[field])) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: [field],+ message: `Leave '${field}' out: memberProvidedFields lists '${MEMBER_FIELD_OF_INPUT[field]}', so each member sets it.`+ });+ }+ });++ if (!requireValues) return;++ if (+ data.type === AgentVaultCredentialType.Bearer &&+ data.value === undefined &&+ !memberProvided.has(AgentVaultVariableReferenceField.CredentialValue)+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["value"],+ message: "A bearer credential needs a token. Set one, or leave the token to each member."+ });+ }++ // Either half may be blank, but not both, unless a member sets one of them.+ if (data.type === AgentVaultCredentialType.Basic && !memberProvided.size && !data.username && !data.password) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["username"],+ message: "A basic credential needs a username, a password, or both"+ });+ }+ };++ // Value fields are optional in the shape so a member-provided one can be left out; the refine requires the rest.-export const AgentVaultCredentialInputSchema = 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: acceptsVariableReferences(- z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- )- .optional()- .describe(AGENT_VAULT.SERVICE.value),- memberProvidedFields: bearerMemberProvidedFieldsSchema.optional()- })- .describe(JSON.stringify({ title: "Bearer" })),- z- .object({- type: z.literal(AgentVaultCredentialType.Basic),- username: acceptsVariableReferences(- z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- )- .optional()- .describe(AGENT_VAULT.SERVICE.username),- password: acceptsVariableReferences(- z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- )- .optional()- .describe(AGENT_VAULT.SERVICE.password),- memberProvidedFields: basicMemberProvidedFieldsSchema.optional()- })- .describe(JSON.stringify({ title: "Basic Auth" })),- z- .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })- .describe(JSON.stringify({ title: "Pass-through" }))- ])- .superRefine(checkCredentialFields({ requireValues: true }));+const bearerCredentialInput = z.object({+ type: z.literal(AgentVaultCredentialType.Bearer),+ headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),+ headerPrefix: agentVaultHeaderPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.headerPrefix),+ value: acceptsVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- ).describe(AGENT_VAULT.SERVICE.value)++ )++ .optional()++ .describe(AGENT_VAULT.SERVICE.value),++ memberProvidedFields: bearerMemberProvidedFieldsSchema.optional()+});+const basicCredentialInput = z.object({+ type: z.literal(AgentVaultCredentialType.Basic),+ username: acceptsVariableReferences(+ z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- ).describe(AGENT_VAULT.SERVICE.username),++ )++ .optional()++ .describe(AGENT_VAULT.SERVICE.username),+ password: acceptsVariableReferences(+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- ).describe(AGENT_VAULT.SERVICE.password)++ )++ .optional()++ .describe(AGENT_VAULT.SERVICE.password),++ memberProvidedFields: basicMemberProvidedFieldsSchema.optional()+});+const passthroughCredentialInput = z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) });+const oauthCredentialInput = z.object({+ type: z.literal(AgentVaultCredentialType.OAuth),+ authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.authorizationId)+});++const docsTitle = (title: string, hidden = false) => JSON.stringify({ title, ...(hidden ? { "x-hidden": true } : {}) });++// Only a user in the UI can complete an authorization, so the API docs never offer OAuth. The MCP schema also+// hides the types an MCP service can't use, but still accepts them so the service refuses them by name.+const credentialInputSchema = ({ mcp }: { mcp: boolean }) =>+ z+ .discriminatedUnion("type", [+ bearerCredentialInput.describe(docsTitle("Bearer")),+ basicCredentialInput.describe(docsTitle("Basic Auth", mcp)),+ passthroughCredentialInput.describe(docsTitle("Pass-through", mcp)),+ oauthCredentialInput.describe(docsTitle("OAuth", true))+ ])- .superRefine(basicHalvesAreNotBothEmpty);++ .superRefine(checkCredentialFields({ requireValues: true }));++export const AgentVaultCredentialInputSchema = credentialInputSchema({ mcp: false });+export const AgentVaultMcpCredentialInputSchema = credentialInputSchema({ mcp: true });// Not derived from the create schema: its `.default()`s would turn an omitted field into a reset on a PATCH.-export const AgentVaultCredentialUpdateSchema = z- .discriminatedUnion("type", [- z- .object({- type: z.literal(AgentVaultCredentialType.Bearer),- headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),- headerPrefix: agentVaultHeaderPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.headerPrefix),- value: acceptsVariableReferences(- z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- )- .optional()- .describe(AGENT_VAULT.SERVICE.updateValue),- memberProvidedFields: bearerMemberProvidedFieldsSchema.optional()- })- .describe(JSON.stringify({ title: "Bearer" })),- z- .object({- type: z.literal(AgentVaultCredentialType.Basic),- username: acceptsVariableReferences(- z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- )- .optional()- .describe(AGENT_VAULT.SERVICE.updateUsername),- password: acceptsVariableReferences(- z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- )- .optional()- .describe(AGENT_VAULT.SERVICE.updatePassword),- memberProvidedFields: basicMemberProvidedFieldsSchema.optional()- })- .describe(JSON.stringify({ title: "Basic Auth" })),- z- .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })- .describe(JSON.stringify({ title: "Pass-through" }))- ])- .superRefine((data, ctx) => {- checkCredentialFields({ requireValues: false })(data, ctx);- // A full basic update must still leave a half to send. A partial one is checked against what is stored.- if (- data.type === AgentVaultCredentialType.Basic &&- data.username !== undefined &&- data.password !== undefined &&- !data.memberProvidedFields?.length &&- !data.username &&- !data.password- ) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["username"],- message: "A basic credential needs a username, a password, or both"- });- }- });+const credentialUpdateSchema = ({ 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: acceptsVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ )+ .optional()- .describe(AGENT_VAULT.SERVICE.updateValue)++ .describe(AGENT_VAULT.SERVICE.updateValue),++ memberProvidedFields: bearerMemberProvidedFieldsSchema.optional()+ })+ .describe(docsTitle("Bearer")),+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Basic),+ username: acceptsVariableReferences(+ z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ )+ .optional()+ .describe(AGENT_VAULT.SERVICE.updateUsername),+ password: acceptsVariableReferences(+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ )+ .optional()- .describe(AGENT_VAULT.SERVICE.updatePassword)++ .describe(AGENT_VAULT.SERVICE.updatePassword),++ memberProvidedFields: basicMemberProvidedFieldsSchema.optional()+ })+ .describe(docsTitle("Basic Auth", mcp)),+ z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) }).describe(docsTitle("Pass-through", mcp)),+ z+ .object({+ type: z.literal(AgentVaultCredentialType.OAuth),+ authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.updateAuthorizationId)+ })+ .describe(docsTitle("OAuth", true))+ ])- .superRefine(basicHalvesAreNotBothEmpty);++ .superRefine((data, ctx) => {++ checkCredentialFields({ requireValues: false })(data, ctx);++ // A full basic update must still leave a half to send. A partial one is checked against what is stored.++ if (++ data.type === AgentVaultCredentialType.Basic &&++ data.username !== undefined &&++ data.password !== undefined &&++ !data.memberProvidedFields?.length &&++ !data.username &&++ !data.password++ ) {++ ctx.addIssue({++ code: z.ZodIssueCode.custom,++ path: ["username"],++ message: "A basic credential needs a username, a password, or both"++ });++ }++ });++export const AgentVaultCredentialUpdateSchema = credentialUpdateSchema({ mcp: false });+export const AgentVaultMcpCredentialUpdateSchema = credentialUpdateSchema({ mcp: true });export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [z.object({type: z.literal(AgentVaultCredentialType.Bearer),headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),- headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix)+ headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix),+ memberProvidedFields: z+ .enum([AgentVaultVariableReferenceField.CredentialValue])+ .array()+ .describe(AGENT_VAULT.SERVICE.memberProvidedFields)}).describe(JSON.stringify({ title: "Bearer" })),- z.object({ type: z.literal(AgentVaultCredentialType.Basic) }).describe(JSON.stringify({ title: "Basic Auth" })),+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Basic),+ memberProvidedFields: z+ .enum(AGENT_VAULT_MEMBER_PROVIDED_FIELDS)+ .array()+ .describe(AGENT_VAULT.SERVICE.memberProvidedFields)+ })+ .describe(JSON.stringify({ title: "Basic Auth" })),z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })- .describe(JSON.stringify({ title: "Pass-through" }))+ .describe(JSON.stringify({ title: "Pass-through" })),+ z+ .object({+ type: z.literal(AgentVaultCredentialType.OAuth),+ status: z.nativeEnum(AgentVaultOauthStatus).describe(AGENT_VAULT.SERVICE.oauthStatus),+ issuer: z.string().describe(AGENT_VAULT.SERVICE.oauthIssuer),+ grantedScopes: z.string().array().describe(AGENT_VAULT.SERVICE.oauthGrantedScopes),+ requiredScopes: z.string().array().describe(AGENT_VAULT.SERVICE.oauthRequiredScopes),+ expiresAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthExpiresAt),+ authorizedAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthAuthorizedAt),+ lastError: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthLastError)+ })+ .describe(JSON.stringify({ title: "OAuth" }))]);export const AgentVaultAllowedMethodsSchema = zdiff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex a47551ac65,f3d7768573..6ff4c38916--- 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@@@ -44,21 -41,12 +41,23 @@@ importAgentVaultHttpMethod,AgentVaultMemberType,AgentVaultResourceRole,+ AgentVaultServiceType,AgentVaultSubstitutionSurface,- AgentVaultVariableReferenceField+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField} from "../agent-vault/agent-vault-enums";- import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+ import { ownerOrNullOf } from "../agent-vault/agent-vault-owner-fns";+ import { getAgentVaultGrantedReachability, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import {+ assertCredentialTypeSupported,+ assertServiceFieldsSupported,+ buildServiceConfig,+ dropReadBackServiceFields,+ getAgentVaultServiceType,+ getServiceServerUrl,+ resolveServiceHostPattern,+ TAgentVaultServiceConfig+} from "../agent-vault/agent-vault-service-type-fns";import {findStoredVariableIds,findVariableKeys,@@@ -66,18 -54,22 +65,29 @@@toVariableReference} from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";+import {+ checkOauthClaimUnderLock,+ checkOauthServerUnderLock,+ 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 { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";+ import {+ clearPersonalValuesAfterRevoke,+ sameMemberProvidedFields+ } from "../agent-vault-personal-value/agent-vault-personal-value-fns";+ import { TAgentVaultPersonalValueServiceFactory } from "../agent-vault-personal-value/agent-vault-personal-value-service";import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";- import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";+ import {+ TAgentVaultAccessBundleActorRef,+ TAgentVaultAccessBundleDALFactory,+ TAgentVaultAccessBundleListRow+ } from "./agent-vault-access-bundle-dal";import {TAddMembersDTO,- TAgentVaultCredentialInput,+ TAgentVaultBasicMemberField,+ TAgentVaultBearerMemberField,TAgentVaultCredentialSummary,TAgentVaultCredentialUpdate,TAgentVaultVariableReferenceSummary,@@@ -320,103 -322,10 +345,24 @@@ export const agentVaultAccessBundleServconst getProjectCipher = (projectId: string) =>kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });- // `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret- // as passthrough, so the two are not interchangeable.- type TCredentialWrite = { config: TAgentVaultCredentialConfig; secret: Record<string, string> | null | undefined };-- const splitCredential = (credential: TAgentVaultCredentialInput): TCredentialWrite => {- switch (credential.type) {- case AgentVaultCredentialType.Bearer: {- const config = AgentVaultBearerConfigSchema.parse({- headerName: credential.headerName,- headerPrefix: credential.headerPrefix- });- return { config: { type: credential.type, ...config }, secret: { value: credential.value } };- }- case AgentVaultCredentialType.Basic: {- if (!credential.username && !credential.password) {- throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });- }- return {- config: { type: credential.type },- secret: { username: credential.username, password: credential.password }- };- }- // Its tokens come from a completed authorization, never from the request.- case AgentVaultCredentialType.OAuth:- throw new BadRequestError({ message: "An OAuth credential needs a completed authorization" });- default:- return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };- }- };-- const mergeCredential = (- credential: TAgentVaultCredentialUpdate,- stored: TAgentVaultServices,- storedSecret: Record<string, string> | null- ): TCredentialWrite => {- if (credential.type === AgentVaultCredentialType.OAuth) {- throw new BadRequestError({ message: "An OAuth credential needs a completed authorization" });- }- if (credential.type !== stored.credentialType) {- if (credential.type === AgentVaultCredentialType.Bearer && credential.value === undefined) {- throw new BadRequestError({- message:- "Provide a new token when changing the credential type to bearer. The stored secret belongs to the previous type"- });- }- return splitCredential(- credential.type === AgentVaultCredentialType.Basic- ? { type: credential.type, username: credential.username ?? "", password: credential.password ?? "" }- : (credential as TAgentVaultCredentialInput)- );- }-- const prev = (stored.credentialConfig ?? {}) as { headerName?: string; headerPrefix?: string };-- switch (credential.type) {- case AgentVaultCredentialType.Bearer:- return {- config: {- type: credential.type,- headerName: credential.headerName ?? prev.headerName ?? "Authorization",- headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""- },- secret: credential.value === undefined ? undefined : { value: credential.value }- };- case AgentVaultCredentialType.Basic: {- if (credential.username === undefined && credential.password === undefined) {- return { config: { type: credential.type }, secret: undefined };- }- const username = credential.username ?? storedSecret?.username ?? "";- const password = credential.password ?? storedSecret?.password ?? "";- if (!username && !password) {- throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });- }- return { config: { type: credential.type }, secret: { username, password } };- }- default:- return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };- }- };-const summarizeCredential = (service: TAgentVaultServices): TAgentVaultCredentialSummary => {const config = service.credentialConfig as Record<string, string>;+ const memberProvidedFields = service.memberProvidedFields ?? [];switch (service.credentialType as AgentVaultCredentialType) {+ // Nothing secret and nothing that identifies the token: no client, no token hash.+ case AgentVaultCredentialType.OAuth: {+ const oauth = service.credentialConfig as TAgentVaultOauthConfig;+ return {+ type: AgentVaultCredentialType.OAuth,+ status: oauth.status,+ issuer: oauth.issuer,+ grantedScopes: oauth.grantedScopes ?? [],+ requiredScopes: oauth.requiredScopes ?? [],+ expiresAt: oauth.expiresAt ?? null,+ authorizedAt: oauth.authorizedAt ?? null,+ lastError: oauth.lastError ?? null+ };+ }case AgentVaultCredentialType.Bearer:return {type: AgentVaultCredentialType.Bearer,@@@ -669,53 -575,6 +619,50 @@@}};+ // 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?: TAgentVaultCredentialInput | TAgentVaultCredentialUpdate- ) => {++ const assertOauthConnectedByUser = (ctx: TGetAccessBundleDTO["ctx"], credential?: TAgentVaultCredentialUpdate) => {+ if (credential?.type === AgentVaultCredentialType.OAuth && ctx.actor !== ActorType.USER) {+ throw new BadRequestError({ message: "OAuth services can only be connected by a user in the Infisical UI." });+ }+ };++ // The tokens come from an authorization the same user completed. Claiming it deletes it right before the write,+ // and a save that then fails puts it back, so it can be retried without authorizing again.+ const claimOauthCredential = async ({+ projectId,+ ctx,+ accessBundleId,+ serviceId,+ serverUrl,+ authorizationId,+ previousRequiredScopes+ }: {+ projectId: string;+ ctx: TGetAccessBundleDTO["ctx"];+ accessBundleId: string;+ serviceId?: string;+ serverUrl: string;+ authorizationId: string;+ previousRequiredScopes?: string[];+ }) => {+ const claim = await agentVaultOauthService.claimAuthorization({+ authorizationId,+ projectId,+ accessBundleId,+ serviceId,+ ctx,+ serverUrl+ });+ const build = (requiredScopes?: string[]) =>+ agentVaultOauthService.buildCredentialFromAuthorization(claim.record, { previousRequiredScopes: requiredScopes });+ try {+ return { claim, ...build(previousRequiredScopes), rebuild: build };+ } catch (err) {+ await claim.restore();+ throw err;+ }+ };+// A bundle the caller cannot reach is a 404, never a 403, which would confirm the id exists.const resolveReachableBundle = async ({ projectId, ctx, accessBundleId }: TGetAccessBundleDTO) => {const reachability = await getAgentVaultReachability({ permissionService, membershipDAL }, { projectId, ctx });@@@ -777,15 -701,12 +789,21 @@@substitutions.filter((substitution) => substitution.serviceId === service.id),variableReferences.filter((reference) => reference.serviceId === service.id));- if (canReadVariables) return projected;+ const status = statuses.find((entry) => entry.serviceId === service.id);+ const { credential } = projected;return {...projected,- variableReferences: undefined,- credential:- credential.type === AgentVaultCredentialType.OAuth- ? { ...credential, expiresAt: undefined, authorizedAt: undefined, lastError: undefined }- : credential- ...(canReadVariables ? {} : { variableReferences: undefined }),++ ...(canReadVariables++ ? {}++ : {++ variableReferences: undefined,++ credential:++ credential.type === AgentVaultCredentialType.OAuth++ ? { ...credential, expiresAt: undefined, authorizedAt: undefined, lastError: undefined }++ : credential++ }),+ // The caller's own values, null when the admin sets the whole credential.+ personalValues: status ? { isConfigured: status.isConfigured, fields: status.fields } : null};})};@@@ -955,12 -861,8 +976,13 @@@const store = (text: string) => toStoredVariableReferences(text, idOfKey);// Encrypt before the lock: KMS is a network call and the transaction has to stay short.- const { config, secret, memberProvidedFields } = splitCredential(storeCredentialReferences(credential, store));- assertCustomHeadersDoNotShadowCredential(config, customHeaders);+ const split =+ credential.type === AgentVaultCredentialType.OAuth+ ? null- : splitCredential(storeCredentialReferences(credential, store) as TAgentVaultCredentialInput);++ : splitCredential(storeCredentialReferences(credential, store));+ assertCustomHeadersDoNotShadowCredential(split ? split.config : { type: credential.type }, customHeaders);+ const secret = split?.secret ?? null;++ const memberProvidedFields = split?.memberProvidedFields ?? null;const { encryptor } = await getProjectCipher(rest.projectId);const seal = (value: string) => encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;@@@ -1017,8 -906,9 +1039,9 @@@allowedMethods: allowedMethods ?? null,allowedPathPrefixes: allowedPathPrefixes ?? null,credentialType: credential.type,- credentialConfig: config,+ credentialConfig,- encryptedCredential+ encryptedCredential,+ memberProvidedFields},tx);@@@ -1225,10 -1057,14 +1251,15 @@@let credentialUpdate = {};// Undefined leaves the sealed secret, and the references read off it, as they are.let writtenSecret: TCredentialWrite["secret"];+ let credentialReplaced = false;let effectiveCredentialConfig = service.credentialConfig as TAgentVaultCredentialConfig;- if (credential) {+ // A new OAuth authorization is claimed right before the write.+ if (credential && credential.type !== AgentVaultCredentialType.OAuth) {- const { config, secret } = mergeCredential(storeCredentialReferences(credential, store), service, storedSecret);+ const { config, secret, memberProvidedFields } = mergeCredential(+ storeCredentialReferences(credential, store),+ service,+ storedSecret+ );let encryptedCredential: Buffer | null | undefined;if (secret === null) encryptedCredential = null;if (secret) {@@@ -1283,95 -1121,11 +1316,102 @@@encryptedValue: seal(storedSubstitutionValues[index])}));- // Same lock as create, and below the credential work so no KMS call sits inside the transaction. The- // re-check only earns its place when the pattern actually changes.+ const oauth = oauthAuthorizationId+ ? await claimOauthCredential({+ projectId: rest.projectId,+ ctx: rest.ctx,+ accessBundleId: bundle.id,+ serviceId: service.id,+ serverUrl: getServiceServerUrl(serviceConfig ?? service.config)!,+ authorizationId: oauthAuthorizationId,+ previousRequiredScopes: storedOauth?.requiredScopes+ })+ : null;+ if (oauth) {+ credentialUpdate = {+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: oauth.config,- encryptedCredential: oauth.encryptedCredential++ encryptedCredential: oauth.encryptedCredential,++ memberProvidedFields: null+ };+ // Clears the old credential's variable references, since OAuth tokens never hold one.+ writtenSecret = null;++ credentialReplaced = true;+ effectiveCredentialConfig = oauth.config;+ }++ // Every rule about a save that committed between the read above and the bundle lock, run against the one row+ // read under the lock. That save may have moved the service, retyped or rotated its credential, or+ // reauthorized it, and writing over it from the first read would undo it. Pure, so it can't touch the database.+ const reconcileWithLockedRow = (locked: TAgentVaultServices) => {+ const lockedOauth =+ locked.credentialType === AgentVaultCredentialType.OAuth+ ? (locked.credentialConfig as TAgentVaultOauthConfig)+ : undefined;+ let lockedServiceConfig = serviceConfig;+ let lockedHostPattern = hostPattern;+ let lockedCredentialUpdate = credentialUpdate;+ let lockedCredentialConfig = locked.credentialConfig as TAgentVaultCredentialConfig;++ if (hasConfigUpdate) {+ lockedServiceConfig = buildServiceConfig(serviceType, configUpdate, locked.config);+ if (serviceType.deriveHostPattern) lockedHostPattern = deriveHostPattern(lockedServiceConfig);+ // An edit that keeps the tokens must still point at the server they were authorized for.+ if (lockedOauth && !oauth && (!credential || credential.type === AgentVaultCredentialType.OAuth)) {+ checkOauthServerUnderLock({+ requestedServerUrl: serverUrl,+ readServerUrl: storedServerUrl,+ effectiveServerUrl: getServiceServerUrl(lockedServiceConfig),+ lockedOauth+ });+ }+ }++ if (credential) {+ // The credential was merged against the first read, whose type decided how the request reads. Writing+ // over a newer one would set a half this request left out back to an older value.+ const secretChanged =+ storedSecret !== null && !locked.encryptedCredential?.equals(service.encryptedCredential!);- if (locked.credentialType !== service.credentialType || secretChanged) {++ if (++ locked.credentialType !== service.credentialType ||++ !sameMemberProvidedFields(locked.memberProvidedFields, service.memberProvidedFields) ||++ secretChanged++ ) {+ throw new ConflictError({ message: CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE });+ }+ lockedCredentialConfig = effectiveCredentialConfig;+ if (oauth && credential.type === AgentVaultCredentialType.OAuth) {+ // The claim checked the server URL of the first read; these tokens must never reach another host.+ const requiredScopes = checkOauthClaimUnderLock({+ authorizedServerUrl: oauth.claim.record.serverUrl,+ authorizedIssuer: oauth.claim.record.issuer,+ lockedServerUrl: getServiceServerUrl(lockedServiceConfig ?? locked.config),+ readOauth: storedOauth,+ lockedOauth+ });+ const rebuilt = oauth.rebuild(requiredScopes);+ lockedCredentialUpdate = {+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: rebuilt.config,- encryptedCredential: rebuilt.encryptedCredential++ encryptedCredential: rebuilt.encryptedCredential,++ memberProvidedFields: null+ };+ lockedCredentialConfig = rebuilt.config;+ }+ }++ return {+ serviceConfig: lockedServiceConfig,+ hostPattern: lockedHostPattern,+ credentialUpdate: lockedCredentialUpdate,+ credentialConfig: lockedCredentialConfig+ };+ };++ // Same lock as create, and below the credential work so no KMS call sits inside the transaction.const write = () =>agentVaultServiceDAL.transaction(async (tx) => {- const locked = await agentVaultAccessBundleDAL.lockByIdInProject(+ const lockedBundle = await agentVaultAccessBundleDAL.lockByIdInProject({ id: bundle.id, projectId: rest.projectId },tx);@@@ -1423,8 -1188,22 +1463,22 @@@},tx)- : service;+ : locked;+ // A saved value goes only when it no longer applies: a new credential type drops every one, and a field the+ // admin takes back drops that field's. A field members still provide keeps what they saved. The update above+ // wrote the service row, which is what a personal values save waits on.+ if (memberFieldsChanged) {+ if (credentialTypeChanged || !nextMemberFields?.length) {+ await agentVaultPersonalValueDAL.delete({ serviceId: service.id }, tx);+ } else {+ await agentVaultPersonalValueDAL.deleteForServiceExceptFields(+ { serviceId: service.id, keepFields: nextMemberFields },+ tx+ );+ }+ }+// Outside the lock, two concurrent PATCHes both pass the ownership check and the loser's writes no-op.const applyDiff = async <TRow extends { id: string; encryptedValue: Buffer }, TColumns>(dal: {@@@ -1572,14 -1350,7 +1626,15 @@@result.variableReferences),accessBundleName: bundle.name,+ update: {+ hostPattern: requestedHostPattern,+ serverUrl,+ transport,+ allowedMethods,+ allowedPathPrefixes,+ substitutions- }++ },+ credentialReplaced};};diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex b2321acf0e,6c27bf0733..dba68e7432--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts@@@ -11,35 -8,39 +11,53 @@@ import} from "../agent-vault/agent-vault-enums";import { TAgentVaultAccessBundleOrderBy } from "./agent-vault-access-bundle-dal";+ export type TAgentVaultBearerMemberField = AgentVaultVariableReferenceField.CredentialValue;+ export type TAgentVaultBasicMemberField =+ | AgentVaultVariableReferenceField.CredentialUsername+ | AgentVaultVariableReferenceField.CredentialValue;++ // A member-provided field never carries a value here: each member sends their own.export type TAgentVaultCredentialInput =- | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value: string }- | { type: AgentVaultCredentialType.Basic; username: string; password: string }+ | {+ type: AgentVaultCredentialType.Bearer;+ headerName?: string;+ headerPrefix?: string;+ value?: string;+ memberProvidedFields?: TAgentVaultBearerMemberField[];+ }+ | {+ type: AgentVaultCredentialType.Basic;+ username?: string;+ password?: string;+ memberProvidedFields?: TAgentVaultBasicMemberField[];+ }- | { type: AgentVaultCredentialType.Passthrough };+ | { type: AgentVaultCredentialType.Passthrough }+ | { type: AgentVaultCredentialType.OAuth; authorizationId: string };- export type TAgentVaultCredentialUpdate =- | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value?: string }- | { type: AgentVaultCredentialType.Basic; username?: string; password?: string }- | { type: AgentVaultCredentialType.Passthrough }- | { type: AgentVaultCredentialType.OAuth; authorizationId: string };+ export type TAgentVaultCredentialUpdate = TAgentVaultCredentialInput;+export type TAgentVaultOauthCredentialSummary = {+ type: AgentVaultCredentialType.OAuth;+ status: AgentVaultOauthStatus;+ issuer: string;+ grantedScopes: string[];+ requiredScopes: string[];+ // Left out for members: they describe the admin's sign-in, not the service's setup.+ expiresAt?: string | null;+ authorizedAt?: string | null;+ lastError?: string | null;+};+export type TAgentVaultCredentialSummary =- | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }- | { type: AgentVaultCredentialType.Basic }+ | {+ type: AgentVaultCredentialType.Bearer;+ headerName: string;+ headerPrefix: string;+ memberProvidedFields: TAgentVaultBearerMemberField[];+ }+ | { type: AgentVaultCredentialType.Basic; memberProvidedFields: TAgentVaultBasicMemberField[] }- | { type: AgentVaultCredentialType.Passthrough };+ | { type: AgentVaultCredentialType.Passthrough }+ | TAgentVaultOauthCredentialSummary;export type TAgentVaultVariableReferenceSummary = { variableId: string; key: string } & (| { field: AgentVaultVariableReferenceField.CredentialValue | AgentVaultVariableReferenceField.CredentialUsername }diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.tsindex 0000000000,6edfb5efc6..ecedfc1c0bmode 000000,100644..100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.ts@@@ -1,0 -1,241 +1,257 @@@+ import { TAgentVaultServices } from "@app/db/schemas";+ import { BadRequestError } from "@app/lib/errors";++ import {+ AgentVaultBearerConfigSchema,+ TAgentVaultCredentialConfig+ } from "../agent-vault/agent-vault-credential-schemas";+ import {+ AgentVaultCredentialType,+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField+ } from "../agent-vault/agent-vault-enums";+ import { sameMemberProvidedFields } from "../agent-vault-personal-value/agent-vault-personal-value-fns";+ import { TAgentVaultCredentialInput, TAgentVaultCredentialUpdate } from "./agent-vault-access-bundle-types";++ // `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret+ // as passthrough, so the two are not interchangeable. The secret holds only the fields the admin sets, so a+ // credential every member supplies in full stores none.+ export type TCredentialWrite = {+ config: TAgentVaultCredentialConfig;+ secret: Record<string, string> | null | undefined;+ memberProvidedFields: TAgentVaultMemberProvidedField[] | null;+ };++ const BASIC_HALVES = [+ [AgentVaultVariableReferenceField.CredentialUsername, "username"],+ [AgentVaultVariableReferenceField.CredentialValue, "password"]+ ] as const;++ type TBasicUpdate = Extract<TAgentVaultCredentialUpdate, { type: AgentVaultCredentialType.Basic }>;++ // A basic update rewrites the sealed secret when it sends a half or changes which halves are left to members.+ const rewritesBasicSecret = (credential: TBasicUpdate, memberFieldsChanged: boolean) =>+ credential.username !== undefined || credential.password !== undefined || memberFieldsChanged;++ // The admin halves a rewrite keeps from the sealed secret: not sent, and the admin's both before and after. A half+ // that was left to members has nothing sealed to keep.+ const keptBasicHalves = (+ credential: TBasicUpdate,+ nextMemberFields: readonly TAgentVaultMemberProvidedField[] | null,+ previousMemberFields: readonly TAgentVaultMemberProvidedField[]+ ) =>+ BASIC_HALVES.filter(+ ([field, key]) =>+ credential[key] === undefined && !nextMemberFields?.includes(field) && !previousMemberFields.includes(field)+ ).map(([, key]) => key);++ // Sending a value replaces the stored secret, and so does a write that drops a field the admin held: handing it to+ // members, or changing the type over a secret that was stored.+ export const isStoredSecretReplaced = (+ credential: TAgentVaultCredentialUpdate,+ stored: TAgentVaultServices,+ written: TCredentialWrite["secret"]+ ) => {+ if (written === undefined) return false;+ if (credential.type !== stored.credentialType) return Boolean(stored.encryptedCredential) || written !== null;- if (credential.type === AgentVaultCredentialType.Passthrough) return false;++ if (credential.type === AgentVaultCredentialType.Passthrough || credential.type === AgentVaultCredentialType.OAuth) {++ return false;++ }++ const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];+ const keyOfField: readonly (readonly [TAgentVaultMemberProvidedField, string])[] =+ credential.type === AgentVaultCredentialType.Bearer+ ? [[AgentVaultVariableReferenceField.CredentialValue, "value"]]+ : BASIC_HALVES;+ return keyOfField.some(+ ([field, key]) =>+ (credential as Record<string, unknown>)[key] !== undefined ||+ (!previousMemberFields.includes(field) && written?.[key] === undefined)+ );+ };+++const OAUTH_NEEDS_AUTHORIZATION_MESSAGE = "An OAuth credential needs a completed authorization";+++ export const BASIC_NEEDS_A_HALF_MESSAGE =+ "A basic credential needs a username, a password, or both. Set one, or leave one to each member.";++ // NULL, never an empty list, is what the column stores for a credential the admin sets in full.+ export const memberFieldsOf = (credential: TAgentVaultCredentialInput): TAgentVaultMemberProvidedField[] | null => {- if (credential.type === AgentVaultCredentialType.Passthrough) return null;++ if (credential.type === AgentVaultCredentialType.Passthrough || credential.type === AgentVaultCredentialType.OAuth) {++ return null;++ }+ const fields = [...new Set<TAgentVaultMemberProvidedField>(credential.memberProvidedFields ?? [])];+ return fields.length ? fields : null;+ };++ export const splitCredential = (credential: TAgentVaultCredentialInput): TCredentialWrite => {+ const memberProvidedFields = memberFieldsOf(credential);+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));++ switch (credential.type) {+ case AgentVaultCredentialType.Bearer: {+ const config = AgentVaultBearerConfigSchema.parse({+ headerName: credential.headerName,+ headerPrefix: credential.headerPrefix+ });+ if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {+ return { config: { type: credential.type, ...config }, secret: null, memberProvidedFields };+ }+ if (credential.value === undefined) {+ throw new BadRequestError({+ message: "A bearer credential needs a token. Set one, or leave the token to each member."+ });+ }+ return {+ config: { type: credential.type, ...config },+ secret: { value: credential.value },+ memberProvidedFields+ };+ }+ case AgentVaultCredentialType.Basic: {+ const secret = Object.fromEntries(+ (+ [+ [AgentVaultVariableReferenceField.CredentialUsername, "username", credential.username],+ [AgentVaultVariableReferenceField.CredentialValue, "password", credential.password]+ ] as const+ ).flatMap(([field, key, value]) => (isMemberProvided(field) ? [] : [[key, value ?? ""]]))+ ) as Record<string, string>;+ if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {+ throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });+ }+ return {+ config: { type: credential.type },+ secret: Object.keys(secret).length ? secret : null,+ memberProvidedFields+ };+ }++ // Its tokens come from a completed authorization, never from the request.++ case AgentVaultCredentialType.OAuth:++ throw new BadRequestError({ message: OAUTH_NEEDS_AUTHORIZATION_MESSAGE });+ default:+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };+ }+ };++ // The member-provided fields a PATCH ends with: an omitted list keeps the stored one.+ export const nextMemberFieldsOf = (credential: TAgentVaultCredentialUpdate, stored: TAgentVaultServices) => {- if (credential.type !== stored.credentialType || credential.type === AgentVaultCredentialType.Passthrough) {++ if (++ credential.type !== stored.credentialType ||++ credential.type === AgentVaultCredentialType.Passthrough ||++ credential.type === AgentVaultCredentialType.OAuth++ ) {+ return memberFieldsOf(credential);+ }+ if (credential.memberProvidedFields === undefined) {+ return (stored.memberProvidedFields as TAgentVaultMemberProvidedField[] | null | undefined) ?? null;+ }+ return memberFieldsOf(credential);+ };++ export const mergeCredential = (+ credential: TAgentVaultCredentialUpdate,+ stored: TAgentVaultServices,+ storedSecret: Record<string, string> | null+ ): TCredentialWrite => {++ if (credential.type === AgentVaultCredentialType.OAuth) {++ throw new BadRequestError({ message: OAUTH_NEEDS_AUTHORIZATION_MESSAGE });++ }+ if (credential.type !== stored.credentialType) {+ if (+ credential.type === AgentVaultCredentialType.Bearer &&+ credential.value === undefined &&+ !memberFieldsOf(credential)?.includes(AgentVaultVariableReferenceField.CredentialValue)+ ) {+ throw new BadRequestError({+ message:+ "Provide a new token when changing the credential type to bearer, or leave the token to each member. The stored secret belongs to the previous type"+ });+ }+ return splitCredential(credential);+ }++ const prev = (stored.credentialConfig ?? {}) as { headerName?: string; headerPrefix?: string };+ const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];+ const memberProvidedFields = nextMemberFieldsOf(credential, stored);+ const memberFieldsChanged = !sameMemberProvidedFields(memberProvidedFields, previousMemberFields);+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));++ // The schema only sees the member-provided list a request sends. One that leaves the list out keeps the stored+ // one, so a value for a field that list hands to members is refused here rather than dropped.+ const memberFieldOfKey: Record<string, TAgentVaultMemberProvidedField> =+ credential.type === AgentVaultCredentialType.Bearer+ ? { value: AgentVaultVariableReferenceField.CredentialValue }+ : {+ username: AgentVaultVariableReferenceField.CredentialUsername,+ password: AgentVaultVariableReferenceField.CredentialValue+ };+ const sentToMemberField = Object.entries(memberFieldOfKey).find(+ ([key, field]) => (credential as Record<string, unknown>)[key] !== undefined && isMemberProvided(field)+ );+ if (sentToMemberField) {+ throw new BadRequestError({+ message: `Leave '${sentToMemberField[0]}' out: '${sentToMemberField[1]}' is member provided, so each member sets it. To set it yourself, send memberProvidedFields without '${sentToMemberField[1]}'.`+ });+ }++ switch (credential.type) {+ case AgentVaultCredentialType.Bearer: {+ const config = {+ type: credential.type,+ headerName: credential.headerName ?? prev.headerName ?? "Authorization",+ headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""+ };+ if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {+ return { config, secret: memberFieldsChanged ? null : undefined, memberProvidedFields };+ }+ if (credential.value !== undefined) {+ return { config, secret: { value: credential.value }, memberProvidedFields };+ }+ if (memberFieldsChanged) {+ throw new BadRequestError({+ message: "Provide a token when you stop leaving it to each member. Nothing is stored for it yet."+ });+ }+ return { config, secret: undefined, memberProvidedFields };+ }+ case AgentVaultCredentialType.Basic: {+ if (!rewritesBasicSecret(credential, memberFieldsChanged)) {+ return { config: { type: credential.type }, secret: undefined, memberProvidedFields };+ }+ // A half taken back from members has nothing sealed to keep, so it starts empty.+ const kept = new Set<string>(keptBasicHalves(credential, memberProvidedFields, previousMemberFields));+ const secret = Object.fromEntries(+ BASIC_HALVES.flatMap(([field, key]) => {+ if (isMemberProvided(field)) return [];+ const sent = credential[key];+ if (sent !== undefined) return [[key, sent]];+ return [[key, kept.has(key) ? (storedSecret?.[key] ?? "") : ""]];+ })+ ) as Record<string, string>;+ if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {+ throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });+ }+ return {+ config: { type: credential.type },+ secret: Object.keys(secret).length ? secret : null,+ memberProvidedFields+ };+ }+ default:+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };+ }+ };++ // Whether an update's write keeps an admin half it left out, which it can only read from the sealed secret.+ export const needsStoredSecretFor = (credential: TAgentVaultCredentialUpdate, service: TAgentVaultServices) => {+ if (credential.type !== AgentVaultCredentialType.Basic) return false;+ if (service.credentialType !== AgentVaultCredentialType.Basic || !service.encryptedCredential) return false;+ const previousMemberFields = (service.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];+ const nextMemberFields = nextMemberFieldsOf(credential, service);+ const memberFieldsChanged = !sameMemberProvidedFields(nextMemberFields, previousMemberFields);+ return (+ rewritesBasicSecret(credential, memberFieldsChanged) &&+ keptBasicHalves(credential, nextMemberFields, previousMemberFields).length > 0+ );+ };diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.tsindex c3e1043bed,a1b3e32d05..ec4d07df9a--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts@@@ -35,113 -45,53 +48,157 @@@ export const agentVaultServiceDALFactor}};+ // A scope report or token refresh is a single UPDATE that only checks the sealed credential, so a save that read+ // the row without this lock could write over one that committed in between.+ const lockByIdInAccessBundle = async (+ { id, accessBundleId }: { id: string; accessBundleId: string },+ tx: Knex+ ): Promise<TAgentVaultServices | undefined> => {+ try {+ return await tx(TableName.AgentVaultService).where({ id, accessBundleId }).forUpdate().first();+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock agent vault service" });+ }+ };++ const findByIdPrimary = async (id: string, tx?: Knex): Promise<TAgentVaultServices | undefined> => {+ try {+ return await (tx || db)(TableName.AgentVaultService).where({ id }).first();+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault service" });+ }+ };++ // A refresh writes only if the sealed credential is still the one it read, so an admin reauthorizing in+ // between keeps the newer tokens. The config is a jsonb merge, so it only touches the keys it names.+ // `keepAdditionalScopesStatus` is decided against the row being written, not the one the caller read: a scope report+ // leaves the sealed credential alone, so it passes the compare, and its status must not be overwritten.+ const compareAndSwapCredential = async (+ {+ id,+ expectedEncryptedCredential,+ encryptedCredential,+ credentialConfigPatch,+ keepAdditionalScopesStatus+ }: {+ id: string;+ expectedEncryptedCredential: Buffer;+ encryptedCredential?: Buffer;+ credentialConfigPatch: Record<string, unknown>;+ keepAdditionalScopesStatus?: boolean;+ },+ tx?: Knex+ ): Promise<Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined> => {+ try {+ const patch = JSON.stringify(credentialConfigPatch);+ const credentialConfig = keepAdditionalScopesStatus+ ? db.raw(+ `CASE WHEN "credentialConfig"->>'status' = ? THEN COALESCE("credentialConfig", '{}'::jsonb) || (?::jsonb - 'status') ELSE COALESCE("credentialConfig", '{}'::jsonb) || ?::jsonb END`,+ [AgentVaultOauthStatus.NeedsAdditionalScopes, patch, patch]+ )+ : db.raw(`COALESCE("credentialConfig", '{}'::jsonb) || ?::jsonb`, [patch]);+ const [row] = await (tx || db)(TableName.AgentVaultService)+ .where({ id, encryptedCredential: expectedEncryptedCredential })+ .update({+ ...(encryptedCredential ? { encryptedCredential } : {}),+ credentialConfig+ })+ .returning(["id", "hostPattern", "config", "credentialConfig"]);+ return row as Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Update agent vault service credential" });+ }+ };++ // The union is taken in the UPDATE, against the row being written: two reports for the same token both pass a+ // compare on the sealed credential, so a union computed from what each one read would let the last erase the other.+ // Servers usually list every scope a call needs, so scopes already granted are skipped, and a report naming only+ // those writes nothing. The list stops growing at MAX_OAUTH_SCOPES, since this row is read on every resolve.+ const addRequiredScopes = async (+ {+ id,+ expectedEncryptedCredential,+ rejectedTokenHash,+ requiredScopes+ }: { id: string; expectedEncryptedCredential: Buffer; rejectedTokenHash: string; requiredScopes: string[] },+ tx?: Knex+ ): Promise<Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined> => {+ try {+ const stored = `COALESCE("credentialConfig"->'requiredScopes', '[]'::jsonb)`;+ const granted = `COALESCE("credentialConfig"->'grantedScopes', '[]'::jsonb)`;+ const reported = JSON.stringify([...new Set(requiredScopes)]);+ const [row] = await (tx || db)(TableName.AgentVaultService)+ .where({ id, encryptedCredential: expectedEncryptedCredential, credentialType: AgentVaultCredentialType.OAuth })+ .whereRaw(`"credentialConfig"->>'accessTokenHash' = ?`, [rejectedTokenHash])+ .whereRaw(`"credentialConfig"->>'status' IS DISTINCT FROM ?`, [AgentVaultOauthStatus.NeedsReauthorization])+ .whereRaw(+ `EXISTS (SELECT 1 FROM jsonb_array_elements_text(?::jsonb) AS reported(scope) WHERE NOT ${granted} @> jsonb_build_array(reported.scope))`,+ [reported]+ )+ .update({+ credentialConfig: db.raw(+ `COALESCE("credentialConfig", '{}'::jsonb) || jsonb_build_object('status', ?::text, 'requiredScopes', ${stored} || COALESCE((SELECT jsonb_agg(added.scope ORDER BY added.ord) FROM (SELECT reported.scope, reported.ord, row_number() OVER (ORDER BY reported.ord) AS position FROM jsonb_array_elements_text(?::jsonb) WITH ORDINALITY AS reported(scope, ord) WHERE NOT ${stored} @> jsonb_build_array(reported.scope) AND NOT ${granted} @> jsonb_build_array(reported.scope)) AS added WHERE added.position <= ?::int - jsonb_array_length(${stored})), '[]'::jsonb))`,+ [AgentVaultOauthStatus.NeedsAdditionalScopes, reported, MAX_OAUTH_SCOPES]+ )+ })+ .returning(["id", "hostPattern", "config", "credentialConfig"]);+ return row as Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Add agent vault service required scopes" });+ }+ };++ // Reads the primary even without a tx, like findByIdInAccessBundle.+ const findByIdInProject = async (+ { id, projectId }: { id: string; projectId: string },+ tx?: Knex+ ): Promise<(TAgentVaultServices & { accessBundleName: string }) | undefined> => {+ try {+ return (await (tx || db)(TableName.AgentVaultService)+ .join(+ TableName.AgentVaultAccessBundle,+ `${TableName.AgentVaultService}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ )+ .where(`${TableName.AgentVaultService}.id`, id)+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)+ .first(+ `${TableName.AgentVaultService}.*`,+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName")+ )) as (TAgentVaultServices & { accessBundleName: string }) | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault service in project" });+ }+ };++ // A personal values save holds this until it commits. A service update writes the row, so it waits for the+ // save, and a save that starts after the update reads the fields the update left.+ const lockForPersonalValues = async (+ id: string,+ tx: Knex+ ): Promise<Pick<TAgentVaultServices, "id" | "credentialType" | "memberProvidedFields"> | undefined> => {+ try {+ return (await tx(TableName.AgentVaultService)+ .where({ id })+ .forShare()+ .first("id", "credentialType", "memberProvidedFields")) as+ | Pick<TAgentVaultServices, "id" | "credentialType" | "memberProvidedFields">+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock agent vault service for personal values" });+ }+ };+return {...orm,findByAccessBundleId,+ lockByAccessBundleId,findByIdInAccessBundle,+ lockByIdInAccessBundle,+ findByIdPrimary,+ findByIdInProject,- lockForPersonalValues++ lockForPersonalValues,+ compareAndSwapCredential,+ addRequiredScopes};};diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsindex e15095d33e,0000000000..7e4eac796fmode 100644,000000..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@@@ -1,284 -1,0 +1,294 @@@+import { createMongoAbility } from "@casl/ability";+import { describe, expect, test, vi } from "vitest";++import {+ ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { ConflictError } from "@app/lib/errors";++import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";++import {+ AgentVaultCredentialType,+ AgentVaultOauthStatus,+ AgentVaultServiceType+} from "../agent-vault/agent-vault-enums";+import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "../agent-vault-oauth/agent-vault-oauth-service";+import { TRefreshServiceTokenDTO } from "../agent-vault-oauth/agent-vault-oauth-types";+import { agentVaultProxyServiceFactory } from "./agent-vault-proxy-service";+import { TResolveServiceRow } from "./agent-vault-resolve-dal";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }+}));++vi.mock("@app/services/object-storage/object-storage-default-fns", () => ({++ isDefaultStorageConfigured: () => false++}));++const PROJECT_ID = "11111111-1111-4111-8111-111111111111";+const SERVICE_ID = "33333333-3333-4333-8333-333333333333";+const SERVER_URL = "https://mcp.linear.app/mcp";++const serviceRow = (overrides: Partial<TResolveServiceRow> = {}): TResolveServiceRow => ({+ id: SERVICE_ID,+ name: "linear",+ accessBundleName: "bundle",+ type: AgentVaultServiceType.Mcp,+ hostPattern: "mcp.linear.app",+ config: { serverUrl: SERVER_URL, transport: "streamable-http" },+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: {+ status: AgentVaultOauthStatus.Connected,+ // Inside the refresh horizon, so resolve refreshes it.+ expiresAt: new Date(Date.now() + 10_000).toISOString()+ },+ encryptedCredential: Buffer.from(JSON.stringify({ accessToken: "snapshot-access" })),+ allowedMethods: null,+ allowedPathPrefixes: null,++ memberProvidedFields: null,+ position: 0,+ ...overrides+});+++const sessionLogConfig = {++ id: "logs-config",++ projectId: PROJECT_ID,++ enabled: false,++ storageType: ObjectStorageType.Default,++ createdAt: new Date(),++ updatedAt: new Date()++};+++const setup = (+ refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>,+ rows = [serviceRow()],+ variables: { id: string; encryptedValue: Buffer }[] = []+) => {+ const refreshServiceToken = vi.fn(refresh);+ const reportMissingScopes = vi.fn(async () => {});+ const service = agentVaultProxyServiceFactory({+ agentVaultProxyDAL: {+ findByIdWithOrg: async () => ({ projectId: PROJECT_ID, orgId: "org-1", pollInterval: 60 })+ } as never,+ agentVaultResolveDAL: { findResolvableServices: async () => rows },+ agentVaultServiceCustomHeaderDAL: { findByServiceIds: async () => [] },+ agentVaultServiceSubstitutionDAL: { findByServiceIds: async () => [] },+ agentVaultVariableDAL: { findValuesForResolve: async () => variables },++ agentVaultPersonalValueDAL: { findForResolve: async () => [] },+ agentVaultSessionDAL: {+ findByTokenHash: async () =>+ ({ id: "session-1", projectId: PROJECT_ID, userId: "user-1", revokedAt: null, expiresAt: null }) as never+ },+ agentVaultSessionLogConfigDAL: {- findOne: async () => ({- id: "logs-config",- projectId: PROJECT_ID,- enabled: false,- createdAt: new Date(),- updatedAt: new Date()- })++ findOne: async () => sessionLogConfig,++ findByProjectIdFromPrimary: async () => sessionLogConfig+ },+ membershipDAL: { findResourceMembershipsForActor: async () => [] },+ orgDAL: { findEffectiveOrgMembership: async () => ({ isActive: true }) as never },+ permissionService: {+ getProjectPermission: async () =>+ ({+ permission: createMongoAbility([+ {+ action: ProjectPermissionAgentVaultSessionActions.Read,+ subject: ProjectPermissionSub.AgentVaultSessions+ }+ ]),+ hasRole: () => true,+ memberships: []+ }) as never+ },+ kmsService: {+ createCipherPairWithDataKey: async () =>+ ({ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob }) as never+ },+ licenseService: {} as never,+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {+ refreshServiceToken: refreshServiceToken as never,+ reportMissingScopes: reportMissingScopes as never+ }+ });+ return { service, refreshServiceToken, reportMissingScopes };+};++const refreshed = {+ credential: {+ type: "bearer",+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "refreshed-access",+ source: "oauth",+ expiresAt: null+ },+ status: AgentVaultOauthStatus.Connected+};++const refreshArgs = {+ proxyId: "proxy-1",+ orgId: "org-1",+ sessionToken: "token",+ serviceId: SERVICE_ID,+ rejectedTokenHash: "a".repeat(64)+};++describe("credential refresh", () => {+ test("a host pattern that no longer matches the service is a 409, before any refresh", async () => {+ const { service, refreshServiceToken } = setup(async () => refreshed);+ const result = service.refreshCredential({ ...refreshArgs, hostPattern: "old.example.com" });+ await expect(result).rejects.toThrow(ConflictError);+ await expect(result).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ expect(refreshServiceToken).not.toHaveBeenCalled();+ });++ test("a matching host pattern is passed on, so the refresh re-checks it on the rows it reads", async () => {+ const { service, refreshServiceToken } = setup(async () => refreshed);+ await expect(service.refreshCredential({ ...refreshArgs, hostPattern: "mcp.linear.app" })).resolves.toEqual(+ refreshed+ );+ expect(refreshServiceToken.mock.calls[0][0].destination).toEqual({ hostPattern: "mcp.linear.app" });+ });+});++describe("missing scopes report", () => {+ test("a host pattern that no longer matches the service is a 409, before anything is recorded", async () => {+ const { service, reportMissingScopes } = setup(async () => refreshed);+ const result = service.reportMissingScopes({+ ...refreshArgs,+ hostPattern: "old.example.com",+ requiredScopes: ["admin"]+ });+ await expect(result).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ expect(reportMissingScopes).not.toHaveBeenCalled();+ });++ test("records the scopes against the rejected token without refreshing", async () => {+ const { service, refreshServiceToken, reportMissingScopes } = setup(async () => refreshed);+ await service.reportMissingScopes({+ ...refreshArgs,+ rejectedTokenHash: "A".repeat(64),+ hostPattern: "mcp.linear.app",+ requiredScopes: ["admin"]+ });+ expect(reportMissingScopes).toHaveBeenCalledWith({+ serviceId: SERVICE_ID,+ rejectedTokenHash: "a".repeat(64),+ requiredScopes: ["admin"],+ hostPattern: "mcp.linear.app"+ });+ expect(refreshServiceToken).not.toHaveBeenCalled();+ });+});++describe("resolve's lazy refresh", () => {+ const resolve = (service: ReturnType<typeof setup>["service"]) =>+ service.resolveSession({ proxyId: "proxy-1", orgId: "org-1", sessionToken: "token", hasSessionLogKey: false });++ test("pins the refresh to the snapshot's host and server URL, and sends what it returns", async () => {+ const { service, refreshServiceToken } = setup(async () => refreshed);+ const { services } = await resolve(service);+ expect(refreshServiceToken.mock.calls[0][0].destination).toEqual({+ hostPattern: "mcp.linear.app",+ serverUrl: SERVER_URL+ });+ expect(services[0]).toMatchObject({ hostPattern: "mcp.linear.app", credential: { value: "refreshed-access" } });+ });++ test("a service that moved during the refresh keeps the snapshot's host with the snapshot's own token", async () => {+ const { service } = setup(async () => {+ throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });+ });+ const { services } = await resolve(service);+ expect(services[0]).toMatchObject({+ hostPattern: "mcp.linear.app",+ credential: { type: "bearer", value: "snapshot-access", source: "oauth" }+ });+ });++ test("waits at most 4 seconds for a refresh, then sends the stored token", async () => {+ vi.useFakeTimers();+ try {+ const { service } = setup(() => new Promise(() => {}));+ let settled = false;+ const result = resolve(service).finally(() => {+ settled = true;+ });+ await vi.advanceTimersByTimeAsync(3_999);+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ const { services } = await result;+ expect(services[0].credential).toMatchObject({ value: "snapshot-access" });+ } finally {+ vi.useRealTimers();+ }+ });++ test("a service that needs reauthorization isn't refreshed, even when its token is about to expire", async () => {+ const { service, refreshServiceToken } = setup(+ async () => refreshed,+ [+ serviceRow({+ credentialConfig: {+ status: AgentVaultOauthStatus.NeedsReauthorization,+ expiresAt: new Date(Date.now() + 10_000).toISOString()+ }+ })+ ]+ );+ const { services } = await resolve(service);+ expect(refreshServiceToken).not.toHaveBeenCalled();+ expect(services[0].credential).toMatchObject({ value: "snapshot-access" });+ });++ test("a variable reference inside an OAuth token is sent as is, while a Bearer token's is expanded", async () => {+ const variableId = "44444444-4444-4444-8444-444444444444";+ const reference = `{{${variableId}}}`;+ const { service } = setup(+ async () => refreshed,+ [+ serviceRow({+ credentialConfig: { status: AgentVaultOauthStatus.Connected, expiresAt: null },+ encryptedCredential: Buffer.from(JSON.stringify({ accessToken: `oauth-${reference}` }))+ }),+ serviceRow({+ id: "55555555-5555-4555-8555-555555555555",+ type: AgentVaultServiceType.Http,+ hostPattern: "api.example.com",+ config: null,+ credentialType: AgentVaultCredentialType.Bearer,+ credentialConfig: { headerName: "Authorization", headerPrefix: "Bearer" },+ encryptedCredential: Buffer.from(JSON.stringify({ value: `bearer-${reference}` }))+ })+ ],+ [{ id: variableId, encryptedValue: Buffer.from(JSON.stringify({ value: "expanded" })) }]+ );+ const { services } = await resolve(service);+ expect(services[0].credential).toMatchObject({ value: `oauth-${reference}` });+ expect(services[1].credential).toMatchObject({ value: "bearer-expanded" });+ });++ test("an OAuth token is always sent as Authorization: Bearer, whatever its config holds", async () => {+ const { service } = setup(+ async () => refreshed,+ [+ serviceRow({+ credentialConfig: {+ headerName: "X-Api-Key",+ headerPrefix: "Token",+ status: AgentVaultOauthStatus.Connected,+ expiresAt: null+ }+ })+ ]+ );+ const { services } = await resolve(service);+ expect(services[0].credential).toEqual({+ type: "bearer",+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "snapshot-access",+ source: "oauth",+ expiresAt: null+ });+ });+});diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 65fffe9fa7,8767065d20..756d8ff553--- 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@@@ -26,21 -25,16 +26,25 @@@ import { TOrgDALFactory } from "@app/seimport { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import {AgentVaultCredentialType,+ AgentVaultOauthStatus,+ AgentVaultServiceType,- AgentVaultTrafficPolicy+ AgentVaultTrafficPolicy,+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField} from "../agent-vault/agent-vault-enums";+ import { TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";+import { getServiceServerUrl } from "../agent-vault/agent-vault-service-type-fns";import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";+import {+ AGENT_VAULT_SERVICE_MOVED_MESSAGE,+ TAgentVaultOauthServiceFactory+} from "../agent-vault-oauth/agent-vault-oauth-service";+import { toResolvedOauthCredential } from "../agent-vault-oauth/agent-vault-oauth-token-fns";+import { TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";+ import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";import { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";@@@ -62,9 -60,7 +70,9 @@@ importTHeartbeatDTO,TListProxiesDTO,TProxyByIdDTO,+ TProxyRootCa,+ TRefreshCredentialDTO,+ TReportMissingScopesDTO,TResolvedService,TResolveSessionDTO,TUpdateProxyDTO@@@ -91,11 -86,7 +100,8 @@@ type TAgentVaultProxyServiceFactoryDeppermissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;licenseService: TSessionLogLicenseService;- resourceAuthMethodService: Pick<- TResourceAuthMethodServiceFactory,- "initAtCreate" | "mintToken" | "loginWithToken" | "revokeAccess"- >;+ resourceAuthMethodService: Pick<TResourceAuthMethodServiceFactory, "initAtCreate" | "revokeAccess">;+ agentVaultOauthService: Pick<TAgentVaultOauthServiceFactory, "refreshServiceToken" | "reportMissingScopes">;};export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;@@@ -449,12 -530,105 +550,112 @@@ export const agentVaultProxyServiceFactreturn expanded;};+ /**+ * A member-provided field comes from what the session's actor saved for the service, expanded against their own+ * personal variables only, after the admin's fields were expanded against the global ones: a value is never+ * expanded twice. A service whose actor hasn't set every field the admin leaves to them goes out flagged and+ * without a credential, so the proxy refuses it instead of sending a half-built one.+ */+ const $applyPersonalValues = async ({+ sessionId,+ projectId,+ owner,+ rows,+ services,+ decryptValue,+ decryptJson+ }: {+ sessionId: string;+ projectId: string;+ owner: TAgentVaultOwner;+ rows: TResolveServiceRow[];+ services: TResolvedService[];+ decryptValue: (encryptedValue: Buffer) => string;+ decryptJson: (encrypted: Buffer) => unknown;+ }): Promise<TResolvedService[]> => {+ const rowById = new Map(rows.map((row) => [row.id, row]));+ const memberFieldsOf = (serviceId: string) =>+ (rowById.get(serviceId)?.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];++ const serviceIds = services.filter((service) => memberFieldsOf(service.id).length).map((service) => service.id);+ if (!serviceIds.length) return services;++ // Stored text per service, then per field, with personal variable references still as ids.+ const stored = new Map<string, Map<string, string>>();+ (await agentVaultPersonalValueDAL.findForResolve({ serviceIds, owner })).forEach((row) => {+ const fields = stored.get(row.serviceId) ?? new Map<string, string>();+ fields.set(row.field, (decryptJson(row.encryptedValue) as { value: string }).value);+ stored.set(row.serviceId, fields);+ });++ const variableIds = [+ ...new Set([...stored.values()].flatMap((fields) => [...fields.values()].flatMap(findStoredVariableIds)))+ ];+ const { valueOfFor, unresolvedServiceIds } = createVariableLookup(+ await agentVaultVariableDAL.findValuesForResolve({ variableIds, projectId, owner }),+ decryptValue+ );++ const resolved = services.map((service): TResolvedService => {+ const memberFields = memberFieldsOf(service.id);+ if (!memberFields.length) return service;++ const fields = stored.get(service.id);+ if (!fields || memberFields.some((field) => !fields.has(field))) {- return { ...service, credential: { type: "passthrough" }, personalValuesMissing: true };++ return { ...service, credential: { type: AgentVaultCredentialType.Passthrough }, personalValuesMissing: true };+ }++ const valueOf = valueOfFor(service.id);+ const personalValue = (field: TAgentVaultMemberProvidedField) =>+ expandStoredVariableReferences(fields.get(field) ?? "", valueOf);++ const row = rowById.get(service.id)!;+ const config = (row.credentialConfig ?? {}) as Record<string, string>;+ if (row.credentialType === AgentVaultCredentialType.Bearer) {+ return {+ ...service,+ credential: {- type: "bearer",++ type: AgentVaultCredentialType.Bearer,+ headerName: config.headerName,+ headerPrefix: config.headerPrefix,+ value: personalValue(AgentVaultVariableReferenceField.CredentialValue)+ }+ };+ }+- const adminHalves = service.credential.type === "basic" ? service.credential : { username: "", password: "" };++ const adminHalves =++ service.credential.type === AgentVaultCredentialType.Basic++ ? service.credential++ : { username: "", password: "" };+ return {+ ...service,+ credential: {- type: "basic",++ type: AgentVaultCredentialType.Basic,+ // Trimmed for the same reason as an admin's username a variable fills in.+ username: memberFields.includes(AgentVaultVariableReferenceField.CredentialUsername)+ ? personalValue(AgentVaultVariableReferenceField.CredentialUsername).trim()+ : adminHalves.username,+ password: memberFields.includes(AgentVaultVariableReferenceField.CredentialValue)+ ? personalValue(AgentVaultVariableReferenceField.CredentialValue)+ : adminHalves.password+ }+ };+ });++ if (unresolvedServiceIds.size) {+ logger.error(+ `agentVaultResolve: stored personal variable reference with no variable [sessionId=${sessionId}] [serviceIds=${[...unresolvedServiceIds].join(",")}]`+ );+ }+ return resolved;+ };+- /** The only endpoint that decrypts a credential. The proxy's JWT authorizes; the session token is a selector. */- const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {+ // Shared by resolve and credential refresh, so a refresh can never reach a service resolve would not.+ const $authorizeSession = async ({+ proxyId,+ orgId,+ sessionToken+ }: Pick<TResolveSessionDTO, "proxyId" | "orgId" | "sessionToken">) => {const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));if (!session) throw new NotFoundError({ message: "Session not found" });@@@ -768,10 -824,8 +981,10 @@@updateProxy,deleteProxy,revokeProxyAccess,- enroll,+ bootstrap,heartbeat,- resolveSession+ resolveSession,+ refreshCredential,+ reportMissingScopes};};diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex dc906f8629,30192695b7..82c7326408--- 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@@@ -78,17 -65,12 +84,20 @@@ export type TResolvedService =allowedMethods: string[] | null;allowedPathPrefixes: string[] | null;credential:- | { type: "bearer"; headerName: string; headerPrefix: string; value: string }- | { type: "basic"; username: string; password: string }- | { type: "passthrough" };+ | {+ type: AgentVaultCredentialType.Bearer;+ headerName: string;+ headerPrefix: string;+ value: string;+ // Set only for an OAuth credential, which the proxy may ask to refresh.+ source?: AgentVaultCredentialType.OAuth;+ expiresAt?: string | null;+ }+ | { type: AgentVaultCredentialType.Basic; username: string; password: string }+ | { type: AgentVaultCredentialType.Passthrough };customHeaders: { name: string; prefix: string; value: string }[];substitutions: { placeholder: string; surfaces: string[]; value: string }[];+ // The service takes part of its credential from each member and the session's actor has not set their values,+ // so the proxy refuses its requests rather than sending them without one.+ personalValuesMissing: boolean;};diff --cc backend/src/ee/services/agent-vault/AGENTS.mdindex 56c94d93dc,f3e9dde214..36db842040--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@@ -18,12 -18,12 +18,13 @@@ never in anything the agent holds```agent-vault/ shared: enums, host grammar, conflict detection, reachabilityagent-vault-access-bundle/ bundles, services, credential encryption, grants- agent-vault-variable/ product-wide variables and the reads behind Used By+ agent-vault-variable/ global and personal variables and the reads behind Used Byagent-vault-member/ product membership (list, add, role, remove)+ agent-vault-personal-value/ each actor's own values for the fields a service leaves to membersagent-vault-session/ mint, revoke, list, getagent-vault-project/ the per-org project's lazy bootstrap and resolver- agent-vault-proxy/ login (enrollment), heartbeat, resolve, credential refresh-agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve++agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve, credential refresh+agent-vault-oauth/ OAuth for MCP services: discovery, client registration, authorizations, refreshagent-vault-session-log/ storage settings, chunk ingest, playback```@@@ -248,96 -332,27 +334,103 @@@ referenceleaves it alone. `$decryptCredential` reads NULL as passthrough, so a bearer row that lost its secret wouldsilently stop attaching a credential.+## OAuth credentials++`agent-vault-oauth/`. MCP services only. Infisical is the OAuth client and does discovery, registration, the+code exchange and refresh; the proxy only ever receives the access token.++- **The tokens live on the service row**, like every other credential: the non-secret half (endpoints, client,+ scopes, status, expiry, token hash) in `credentialConfig`, `{ accessToken, refreshToken, clientSecret }` sealed+ in `encryptedCredential`. Each service has its own client, used only with the issuer it was registered at.+ Reauthorizing registers a fresh client, since the server may have dropped the old one and the sign-in would then+ die on its page; only a client entered by hand is kept, and the stored one is the fallback when registration+ fails. Scopes carry over only at the same issuer.+- **Refresh writes the row, which no other credential does, so it races admin edits.** A refresh is a+ compare-and-swap on `encryptedCredential` and a jsonb merge of only the token keys, so an admin who reauthorized+ meanwhile keeps the newer tokens. An admin edit that keeps the tokens never writes `credentialConfig`, so it+ can't write back token fields a refresh changed. A scope report (`missing-scopes`, its own route because it never+ refreshes) changes only the config, so it passes that compare; the refresh's UPDATE keeps `needs-additional-scopes` in SQL rather than in the WHERE, since+ losing the write would drop a rotated refresh token. For the same reason two scope reports can't be told apart by+ the compare, so the report unions `requiredScopes` in its UPDATE (`addRequiredScopes`), never from what it read.+- **A token only goes where the service still points.** `credential-refresh` and `missing-scopes` take the host+ pattern the proxy cached and answer 409 once the service has moved; resolve's lazy refresh is pinned to the host and server URL of+ the snapshot it answers with, and falls back to that snapshot's own token. Both are checked on every row a token+ comes from, since a move can land mid-refresh. A reauthorizing save re-checks the authorization's server URL+ under the bundle lock, and a reauthorization committed since its first read wins with a 409 (a refresh doesn't+ count: it keeps `authorizedAt`). Any other edit that keeps the tokens re-checks under the lock that the server URL+ it writes is the one `credentialConfig.serverUrl` records (set at every authorization), so it can't restore an+ old URL over a reauthorization for another server. `updateService` reads the service once under the lock and+ runs every one of these checks against that row (`reconcileWithLockedRow`); add a new one there, not as another+ read.+- **No network call inside a transaction.** Discovery, registration, the exchange and refresh all run before any+ write. Refresh serializes per service on a Redis lock, not a row lock.+- **A pending authorization is Redis only** (10 minutes), with the PKCE verifier and tokens sealed by the project+ cipher. Only its creator can read or complete it (anyone else gets a 404), so an authorize link sent to someone+ else can't capture their account. It is single use: a save validates it, then claims it by deleting the Redis+ record, and only the save whose delete removed it proceeds. A save that fails after the claim puts the exact+ stored value back with its remaining TTL, so it can be retried; nothing runs after commit.+- **Resolve sends an OAuth token in the bearer shape** with `source: "oauth"`, so a proxy that predates OAuth+ injects it unchanged. The header is always `Authorization: Bearer` (the MCP authorization spec), so an OAuth+ credential stores no header name or prefix and its input is only `authorizationId`. Resolve refreshes a token that expires before the next poll; the proxy calls+ `credential-refresh` after an upstream 401. A failing provider never fails resolve for other services: it costs+ that service a stale token and a `lastError`. A refresh error that means the login is dead (`invalid_grant`, a+ dropped client, providers' own revoked or expired refresh token codes: `DEAD_LOGIN_ERROR_CODES`) moves the service+ to needs reauthorization, so it isn't retried every poll. Any token type but a proof-of-possession one (DPoP, MAC,+ PoP) is sent as a bearer token, since servers may name their own (Slack's is `user`).+- **Both proxy calls answer well inside the proxy's 15 second timeout.** Resolve waits 4 seconds in total for its+ refreshes and sends the stored token for any still running, which finish in the background. Token requests (the+ `invalid_target` retry included) share one 7 second budget. Resolve's refresh waits about 3 seconds for another's+ lock; the proxy's refresh after a 401 waits about 10, so it outlasts the holder and gets the new token rather than+ the rejected one. Either then answers with what is stored, and a waiter whose holder failed spends only the time+ left before 13 seconds on its own request. Keep that under the proxy's timeout.+- **Neither refreshes nor resolve are audited.** Connect and reauthorize are recorded by the service create and+ update events, which carry `oauthIssuer` and `oauthScopes`.+- **Non-conforming servers are supported through fallbacks**, each recorded in `compatibility`. A fallback may+ relax what a server must advertise, never a check that stops mix-up or token theft: the issuer must match (a+ trailing slash aside), the protected resource must be the server's own origin, and `iss` is checked whenever it+ arrives.+- **Every scope is an RFC 6749 scope-token** (`isOauthScopeToken`): the proxy's reports are refused otherwise, and+ scopes from metadata, challenges and token responses that aren't are dropped. A space would split the `scope`+ parameter and a NUL fails the jsonb write. A granted `scope` splits on spaces only, since a comma is legal inside a+ token; GitHub-style `repo,gist` splits on commas only when every part was requested (`scope-comma-separated`).+- **Error text never contains a token.** Provider text is bounded and stripped before it reaches `lastError` or a+ response, and outbound URLs are logged through `sanitizeUrlForLog`.+- **Provider data never throws or fails a write.** Every provider string that can reach a message, a log,+ `lastError` or an authorization's `error` goes through `normalizeProviderText`, and `writeStatus` normalizes+ `lastError` again. Values stored as sent (client ID, endpoint URLs, tokens) must be printable ASCII, and+ `expires_in` outside 1 second to 1 year counts as no expiry.+- **Token requests are never retried by the HTTP client.** Codes are one-use and refresh tokens can rotate. Only+ the explicit `invalid_target` fallback retries them, inside the same request deadline.+- **Known gap: scopes only grow.** Reauthorizing at the same issuer asks for every granted and required scope, so+ a scope an agent's call reported (`missing-scopes`) sticks for good. There is no way to drop one requested scope+ or reset to the server's defaults short of deleting the service; a follow-up should add both.+- **Known gap: a Bearer token MCP service only gets the 401 rewrite.** The proxy turns its upstream 401 into a+ 502 so the agent doesn't start its own sign-in, but a `403 insufficient_scope` reaches the agent unchanged, as+ for HTTP services, and an MCP client may start its own OAuth on it (the TypeScript SDK's `onInsufficientScope`+ defaults to `reauthorize`).+## Session logs-Metadata only (method, host, path, status, decision), never bodies, headers or the query string. The agent is+Metadata only (method, host, path, status, decision). Bodies, headers and the query string are never stored;+for an MCP service the proxy reads only the JSON-RPC method and tool name of each call from the body. The agent ishostile input: nothing it sends may erase or hide its own records, so the proxy logs every request it drops.- - **Bytes go proxy to the customer's bucket to the browser, and S3 is the index.** Infisical stores nothing per- chunk and never seals or opens one. A chunk is `{prefix}/{projectId}/{sessionId}/{rev}_{chunkId}.{proxyId}.json.enc`- holding `IV ‖ ciphertext ‖ tag`; `rev` counts the chunk id's time down, because S3 lists names ascending only.+ - **Bytes go proxy to the bucket to the browser, and S3 is the index.** Infisical stores nothing per chunk and never+ seals or opens one. The bucket is default storage (the instance's, `OBJECT_STORAGE_S3_*`) or external storage (the+ customer's, through an AWS connection); both go through the shared layer in `services/object-storage/`, which builds+ `{prefix}/orgs/{orgId}/agent-vault/sessions/{sessionId}/logs/{rev}_{chunkId}.{proxyId}.json.enc` holding+ `IV ‖ ciphertext ‖ tag`. `rev` counts the chunk id's time down, because S3 lists names ascending only.+ - **Effective settings come from `toEffectiveSessionLogConfig`**, reached through `getEffectiveSessionLogConfig`+ unless the caller already holds the row. No row plus an instance bucket means on in default storage; no instance+ bucket means a saved `default` row reads as nothing (the row is kept). Writes upsert on `projectId`, because a row+ can exist while the effective settings are null.- **PAM session recording is a separate product.** The overlap with `pam-session-recording` is deliberate; don'tshare code with it.- - **Keys.** Mint wraps a per-session log key with the project data key, even while session logs are off, and- puts `sha256(sessionId|v1)` in front because the KMS wrap takes no context. Unwrap only through- `openSessionLogKey`, so a key copied onto another row is refused. A key that won't open turns logs off for- that session on resolve: session logs must never break brokering.+ - **Keys.** Mint wraps a per-session log key with `kmsService.wrapKey` (label `{sessionId}|v1`), even while session+ logs are off. The layout, `sha256(label) || key` under the project data key, must not change: a session can have+ no expiry, so a key wrapped by older code may still need to open. Unwrap only through `openSessionLogKey` or+ `unwrapSessionLogKey` (`agent-vault-session-log-secrets.ts`), so a key copied onto another row is refused. A key+ that won't open turns logs off for that session on resolve: session logs must never break brokering.- **The AAD is `sha256("{sessionId}|{chunkId}|v1")`**, pinned by one vector in the CLI's`session_log_crypto_test.go` and `sessionLogDecrypt.test.ts`. Chunk ids are lowercase UUIDv7s because thebrowser rebuilds the AAD from the id in the object name. A change here is a change in all three places.diff --cc backend/src/keystore/keystore.tsindex 53f067dfd9,fbe25ecb29..8b5233c60e--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@@ -171,11 -177,8 +177,13 @@@ export const KeyStorePrefixes =AgentVaultDefaultProject: (orgId: string) => `agent-vault-default-project:${orgId}` as const,// The live view's Redis stream for a session: the newest chunk file names, with their bucket and size.AgentVaultSessionLogFeed: (sessionId: string) => `agent-vault-session-log-feed:${sessionId}` as const,+ AgentVaultOauthAuthorization: (authorizationId: string) =>+ `agent-vault-oauth-authorization:${authorizationId}` as const,+ AgentVaultOauthAuthorizationCompleteLock: (authorizationId: string) =>+ `agent-vault-oauth-authorization:${authorizationId}:complete` as const,+ AgentVaultOauthRefreshLock: (serviceId: string) => `agent-vault-oauth-refresh-lock:${serviceId}` as const,+ // Bytes an org has been allowed to upload to object storage on one UTC day (YYYY-MM-DD).+ ObjectStorageDailyBytes: (orgId: string, day: string) => `object-storage:daily-bytes:${orgId}:${day}` as const,CertDashboardStats: (projectId: string) => `cert-dashboard-stats:${projectId}` as const,OrgSecretScanningFindingsCount: (orgId: string) => `org-secret-scanning-findings-count:${orgId}` as const,diff --cc backend/src/lib/api-docs/constants.tsindex 6cc2c5cb98,ed68a5cbbb..289677e455--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@@ -4551,48 -4563,40 +4586,77 @@@ export const AGENT_VAULT =referenceField:"Which value uses the variable: credential-value (a bearer token or a basic password), credential-username, custom-header or substitution.",referenceCustomHeaderId: "The custom header whose value uses the variable.",- referenceSubstitutionId: "The substitution whose value uses the variable."+ referenceSubstitutionId: "The substitution whose value uses the variable.",+ bearerMemberProvidedFields:+ "Leave the token to each member: send `credential-value` here and no `value`. Every member sets their own, and a session uses the token of whoever it belongs to. Omit on update to keep the current setting; send an empty list to set the token yourself again, which then needs a `value`. Changing this clears every member's saved values for the service.",+ basicMemberProvidedFields:+ "The halves of the basic credential each member sets for themselves: `credential-username`, `credential-value` (the password) or both. Send no value for a half listed here. A session uses the values of whoever it belongs to. Omit on update to keep the current setting. Adding a half keeps what members saved, and taking one back deletes only that half's values. Changing the credential type deletes every member's values for the service.",+ memberProvidedFields:+ "The credential fields each member sets for themselves: credential-value (a bearer token or a basic password) and credential-username. Empty when the admin sets the whole credential."+ },+ PERSONAL_VALUE: {+ credentialType:+ "The credential type you expect the service to have. If it no longer matches, the request fails with a 409.",+ personalValues:+ "Your personal values for the service, or null if the service leaves no fields to its members. Only you can see these, and a stored value never comes back.",+ isConfigured:+ "Whether you have set every value this service requires from you. Until you do, the proxy refuses this service's requests from your sessions.",+ fields: "Each value the service requires from you, and whether you have set it.",+ field:+ "Which value: credential-value (a bearer token or a basic password) or credential-username (a basic username).",+ isSet: "Whether you have set this value.",+ updatedAt: "When you last set this value, or null if you haven't.",+ variableReferences: "Your personal variables that this value uses.",+ values:+ "The values to set, at most one per field the service leaves to its members. A field you leave out keeps its saved value, so after a field becomes member provided you only need to send that one.",+ value: `The value. Can use up to ${AGENT_VAULT_MAX_REFERENCES_PER_FIELD} references to your personal variables, written as \`{{KEY}}\`. Never returned once saved.`},+ OAUTH: {+ authorization: "The OAuth authorization, or null when an OAuth client must be registered first.",+ authorizationId: "The ID of the OAuth authorization.",+ accessBundleId: "The access bundle the service is in, or will be created in.",+ serverUrl: "The MCP server's URL. Must match the server URL of the service the authorization is saved to.",+ serviceId:+ "The ID of the MCP service to reauthorize. Leave it out when connecting a new service. When set, the sign-in asks for the scopes the service already has, and can only be saved to that service.",+ clientId:+ "The client ID of your own OAuth app, for a server that doesn't support dynamic client registration. Register the app with the redirect URI `<your Infisical URL>/agent-vault/oauth/callback`.",+ clientSecret: "The client secret of your own OAuth app, if it has one.",+ registration:+ "Send `dynamic` to register a new client with the server, even when the service being reauthorized uses your own OAuth app.",+ registrationRequired:+ "True when the server can't register Infisical as a client by itself, or refused to. Send `clientId` (and `clientSecret`) of your own OAuth app.",+ redirectUri:+ "The redirect URI Infisical sends to the authorization server. Register your own OAuth app with this exact value.",+ oauthAdvertised:+ "False when the MCP server answered but sent no OAuth challenge and serves no OAuth metadata. The server URL may be wrong; a server that does use OAuth can still be connected with your own client ID and secret.",+ status: "`pending` until the authorization server redirects back, then `authorized` or `failed`.",+ error: "Why the authorization failed, when it did.",+ scopes: "The scopes requested, or once authorized, the scopes granted.",+ authorizeUrl: "Open this URL in the browser to sign in to the authorization server.",+ state: "The `state` value from the redirect.",+ code: "The `code` value from the redirect.",+ iss: "The `iss` value from the redirect, when the authorization server sends one.",+ callbackError: "The `error` value from the redirect, when the authorization server sends one instead of a code.",+ callbackErrorDescription: "The `error_description` value from the redirect."+ },+ CREDENTIAL_REFRESH: {+ hostPattern: "The host pattern cached by the proxy for this service. A changed pattern returns 409.",+ rejectedTokenHash: "The hex SHA-256 hash of the access token the MCP server rejected.",+ requiredScopes: "The scopes requested by an insufficient_scope challenge from the MCP server.",+ credential: "The current bearer credential for the service.",+ credentialType: "The credential shape the proxy injects into requests.",+ value: "The access token to attach to requests. Never expose it to the agent.",+ source: "Set to oauth when the proxy can request an OAuth token refresh."+ },VARIABLE: {variableId: "The ID of the variable.",- key: "The name services use to refer to the variable, as `{{KEY}}`. Starts with a letter and uses only upper case letters, numbers and underscores.",+ scope:+ "global for a variable admins set up for services, or personal for one of your own, which only your personal values can use and only you can see. Personal keys are unique among your own variables.",+ listScope:+ "Which variables to list: global, which needs the admin role, or personal for your own. Omit to list everything you can see: your own personal variables, plus the global ones if you're an admin. Nobody can list another member's personal variables.",+ createScope:+ "global creates a variable services can use, which needs the admin role. personal creates one of your own, which only your personal values can use.",+ key: "The name values use to refer to the variable, as `{{KEY}}`. Starts with a letter and uses only upper case letters, numbers and underscores.",value: "The value the proxy puts in place of each `{{KEY}}`.",updateValue: "The value the proxy puts in place of each `{{KEY}}`. Omit to keep the stored value.",revealedValue: "The variable's value.",diff --cc backend/src/server/routes/index.tsindex 90bdcc7bfc,e14d0b8053..7087153573--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@@ -32,7 -32,11 +32,12 @@@ import { agentVaultServiceSubstitutionDimport { agentVaultServiceVariableReferenceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal";import { agentVaultMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-member-dal";import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";+import { agentVaultOauthServiceFactory } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";+ import {+ agentVaultPersonalValueDALFactory,+ agentVaultPersonalValueReferenceDALFactory+ } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal";+ import { agentVaultPersonalValueServiceFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-service";import { agentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";import { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";@@@ -2002,18 -2043,21 +2044,30 @@@ export const registerRoutes = asyncconst agentVaultResolveDAL = agentVaultResolveDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);+ const agentVaultOauthService = agentVaultOauthServiceFactory({+ keyStore,+ kmsService,+ agentVaultServiceDAL,+ agentVaultAccessBundleDAL,+ permissionService,+ membershipDAL+ });+const agentVaultVariableService = agentVaultVariableServiceFactory({agentVaultVariableDAL,+ agentVaultPersonalValueDAL,+ membershipDAL,+ permissionService,+ kmsService+ });++ const agentVaultPersonalValueService = agentVaultPersonalValueServiceFactory({+ agentVaultPersonalValueDAL,+ agentVaultPersonalValueReferenceDAL,+ agentVaultVariableDAL,+ agentVaultServiceDAL,permissionService,+ membershipDAL,kmsService});@@@ -4719,8 -4807,8 +4819,9 @@@pamProjectResolver,agentVaultProjectResolver,agentVaultAccessBundle: agentVaultAccessBundleService,+ agentVaultOauth: agentVaultOauthService,agentVaultVariable: agentVaultVariableService,+ agentVaultPersonalValue: agentVaultPersonalValueService,agentVaultProxy: agentVaultProxyService,agentVaultSession: agentVaultSessionService,agentVaultSessionLog: agentVaultSessionLogService,diff --cc docs/documentation/platform/agent-vault/access-bundles.mdxindex b80f222b62,51c5b47326..4770dbb966--- a/docs/documentation/platform/agent-vault/access-bundles.mdx+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx@@@ -55,4 -55,32 +55,32 @@@ To allow a user, group, or machine iden### Revoke access- To revoke access from a user, group, or machine identity, open the bundle and select **Options** > **Manage Access**. Find them with the search box, open their actions menu, and select **Revoke Access**. If any of their agents are running, those agents lose the bundle's credentials within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).+ To revoke access from a user, group, or machine identity, open the bundle and select **Options** > **Manage Access**. Find them with the search box, open their actions menu, and select **Revoke Access**. If any of their agents are running, those agents lose the bundle's credentials within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).++ ## Set up your personal values+-Some services ask you for part of their credential, such as your own API key (see [member-provided values](/documentation/platform/agent-vault/services#member-provided-values)). Until you set up your personal values for one of these services, your sessions can't use it, and the service shows **Requires Setup**. This applies to admins too.++Some services ask you for part of their credential, such as your own API key (see [member-provided values](/documentation/platform/agent-vault/http-apis#member-provided-values)). Until you set up your personal values for one of these services, your sessions can't use it, and the service shows **Requires Setup**. This applies to admins too.++ To set up your personal values:++ <Steps>+ <Step>+ In Agent Vault, go to **Access Bundles** and select the access bundle.+ </Step>+ <Step>+ Select **Requires Setup** next to the service, or open the service's actions menu and select **Set Up My Personal Values**.+ </Step>+ <Step>+ Enter each value. To use one of your [personal variables](/documentation/platform/agent-vault/variables#personal-variables), type `{{` or select the arrow at the end of the field, then pick a variable from the list.+ </Step>+ <Step>+ Select **Save**. The service shows **Configured**.+ </Step>+ </Steps>++ Infisical never shows your personal values to anyone else, admins included.++ - To change your personal values, open the service's actions menu, select **Update My Personal Values**, and enter the values you want to change+ - To delete your personal values, select **Remove** in the same dialog, then select **Remove Personal Values**++ A machine identity sets up its personal values with [the set personal values endpoint](/api-reference/endpoints/agent-vault-services/set-personal-values), and keeps its own personal variables with [the create variable endpoint](/api-reference/endpoints/agent-vault-variables/create).diff --cc docs/documentation/platform/agent-vault/http-apis.mdxindex 0292f48bdc,0000000000..9e799f2e54mode 100644,000000..100644--- a/docs/documentation/platform/agent-vault/http-apis.mdx+++ b/docs/documentation/platform/agent-vault/http-apis.mdx@@@ -1,240 -1,0 +1,269 @@@+---+title: "HTTP APIs"+description: "External APIs that an AI agent can securely call during a session."+---++An HTTP service is a [service](/documentation/platform/agent-vault/services) for one external API that an agent can access during a [session](/documentation/platform/agent-vault/sessions). Each HTTP service defines the external API’s [host URL](#host-patterns), its [authentication method](#credential-types), and a real credential to attach when forwarding requests from the agent.++<Tip>+An HTTP service can also limit which [HTTP methods and paths](#methods-and-paths) the agent can use, [add custom headers](#custom-headers) to each request, and [replace placeholder values](#substitutions) the agent sends with real ones.+</Tip>++## Add an HTTP service++To add an HTTP service to an access bundle:++<Steps>+ <Step>+ In Agent Vault, go to **Access Bundles**. Select your access bundle, then select **Add Service**.+ </Step>+ <Step>+ On the **Choose a template** panel, pick the template for the API you want to reach, or select **Custom HTTP API** to configure the host and header yourself.++ <Frame>+ <img src="/images/platform/agent-vault/service-template-picker.png" alt="The Choose a template panel with Custom, OpenAI, Anthropic, Slack, GitHub, and Google Workspace" />+ </Frame>+ </Step>+ <Step>+ Follow the steps and paste your credentials in the **Credential** section.++ To use a value that several services share, type `{{` in a [field that accepts variables](/documentation/platform/agent-vault/variables#use-a-variable-in-a-service) and select a variable from the list that opens.+ </Step>+ <Step>+ Select **Add Service**. The service appears in the bundle's list.+ </Step>+</Steps>++## Credential types++When configuring a service, you have the option to set its credential type. This determines what the proxy attaches to outbound requests.++<Tip>+If you're configuring a service with a template, you can usually leave the credential type set to the default.+</Tip>++### Bearer++The proxy attaches one header in the format `<header name>: <prefix> <value>`, which defaults to `Authorization: Bearer <value>`.++Bearer is the right choice for most APIs. If the API expects a bare key instead of a `Bearer`-prefixed one, change the header name to `X-API-Key` and clear the prefix.++### Basic++The proxy attaches the header `Authorization: Basic <base64 of username:password>`. Either the username or the password can be left blank.++Basic is the right choice for APIs behind HTTP basic authentication, including ones that put the entire key in the username field.++### Pass-through++The proxy attaches no credential. Unless the service adds [custom headers](#custom-headers) or [substitutions](#substitutions), the proxy forwards the agent's request to the API unchanged.++Pass-through is the right choice when the proxy's strict [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy) would otherwise block the host. It lets the request reach the API without attaching a credential.++<Note>+For **Bearer** and **Basic** services, if the agent's request already carries a header with the same name as the one the service sends, the proxy replaces it with the service's credential.+</Note>+++## Member-provided values++++By default, you set the whole credential and every session uses it. If each member should call the API with their own token or login, such as a personal API key, you can make that part of the credential member provided. Each member then [sets a personal value](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), and a session uses the personal value of the member who created the session.++++You can make these credential fields member provided:++++- **Token** in a [Bearer](#bearer) credential++- **Username**, **Password**, or both in a [Basic](#basic) credential++++To make a field member provided:++++<Steps>++ <Step>++ In Agent Vault, go to **Access Bundles** and select the access bundle. Open the service's actions menu and select **Edit**, then go to the **Credential** step.++ </Step>++ <Step>++ Next to the field, turn on **Member provided**.++ </Step>++ <Step>++ Select **Continue**, then select **Save**.++ </Step>++</Steps>++++<Warning>++If you change the credential type, each member has to set up their personal values for the service again.++</Warning>++++Until a member sets up their personal values, the proxy refuses their sessions' requests to the service with a `403` response. Requests to the bundle's other services still go through.+++## Host patterns++When configuring a service, you have the option to set which host patterns it matches. A host pattern controls which outbound requests get the service's credential attached.++<Tip>+For security reasons, we recommend keeping host patterns as narrow as the API allows. If you're configuring a service with a template, you can usually leave the host set to the default.+</Tip>++### Multiple hosts++A single pattern can cover multiple hosts by listing them, separated by commas:++```text+api.github.com, uploads.github.com+```++### Default port++A host without a port specified only matches requests to the standard HTTPS port `443`:++```+api.github.com+```++This pattern matches `api.github.com:443`, but not `api.github.com:80` or `api.github.com:8080`.++### Non-standard ports++To match a port other than `443`, include it in the host:++```text+internal-api.example.com:8443+```++### Plaintext hosts++A service works the same way over plain HTTP as it does over HTTPS. The proxy attaches the credential, the custom headers, and the substitutions either way. Use a plaintext host for an API on your own network that doesn't serve HTTPS.++Leave the `http://` scheme off the host, and name the port instead:++```text+internal-api.example.com:8080+```++If you don't name the port, the host will only match [port `443`](#default-port):++<Warning>+The proxy sends the credential to a plaintext host unencrypted, so anyone who can read traffic between the proxy and the API can read the credential. Only use plaintext hosts on a network you trust.+</Warning>++### Wildcards++Wildcards match exactly one label. The pattern below matches `api.atlassian.net`, but not `a.b.atlassian.net` or `atlassian.net`.++```text+*.atlassian.net+```++## Host conflicts++Two services within an access bundle can't cover the same host with the same pattern. For example, if you have a service that defines its host as `api.github.com` and you try to create a second service with that same host, Infisical will stop you from saving the second service.++However, two services can match the same host if they define the host pattern differently. When the agent makes a request to that host, the request will match the service that defines the host more explicitly. For example:++- One service defines its host as `api.github.com`+- Another service defines it as `*.github.com`++In the above example, requests to `api.github.com` are handled by the first service.++<Warning>+The proxy applies only the more specific service's [methods and paths](#methods-and-paths). This means that if the `api.github.com` service allows only `GET`, the proxy refuses a `POST` to `api.github.com`, even if that same `POST` request would succeed through `*.github.com`.+</Warning>++<Note>+Different access bundles can cover the same host with different credentials, since an agent only gets the credential from the access bundle its session is scoped to.+</Note>++## Methods and paths++By default, a service allows every HTTP method and every path on its hosts. When configuring a service, you have the option to narrow it to only the methods and paths your agent needs.++<Frame>+ <img src="/images/platform/agent-vault/service-details.png" alt="The Details step of a GitHub service, allowing GET and POST on the path prefixes /repos and /search" />+</Frame>++### Methods++On the **Details** step, clear **All Methods** and select the HTTP methods the service allows. For example, if a service allows only `GET` and `HEAD`, the proxy refuses a `POST` or `DELETE` request before the request leaves your network.++### Paths++On the **Details** step's **Paths** field, enter each path prefix the service allows. A path prefix matches whole segments, so `/repos` covers `/repos/octo/hello` but not `/repositories`. Write the path exactly as it appears in the URL.++<Note>+If a service has path prefixes, the proxy also refuses any path that different servers would resolve differently, such as one containing `..` or an encoded slash. Ordinary paths still work, including ones with a space or a non-ASCII character such as `/repos/owner/repo/contents/café.md`.+</Note>++### Refused requests++If a request breaks either rule, the proxy refuses the request with a 403. The message names the service and the method or path it doesn't allow:++```text+HTTP/1.1 403 Forbidden++service "github" does not allow POST: blocked by service policy+```++```text+HTTP/1.1 403 Forbidden++service "github" does not allow path "/admin": blocked by service policy+```++## Custom headers++Some APIs need a header alongside the credential, such as an organization ID or an API version. On the **Credential** step, under **Advanced Options**, select **Add Custom Header** and enter a name, an optional prefix, and a value. The proxy attaches it to every request to that service, whatever credential type the service uses.++<Frame>+ <img src="/images/platform/agent-vault/service-advanced-options.png" alt="The Credential step with an API version custom header and a substitution that swaps the agent's placeholder for the real token, matched in the header" />+</Frame>++Infisical won't save a custom header with the same name as the credential's header, because the proxy would overwrite it with the credential. Infisical also won't save a custom header that the proxy sets itself, such as `Host`, `Content-Length`, or `Connection`.++<Tip>+A custom header's value can include a [substitution](#substitutions) placeholder. If that substitution has **Headers** selected under **Replace In**, the proxy replaces the placeholder with the real value, so several headers can reuse one secret.+</Tip>++## Substitutions++Instead of attaching headers to an agent's request, you can configure your service to use substitution instead.++With a substitution, you give the agent a placeholder instead of the real credential, such as a fake API token. The agent sends the placeholder in its requests, and the proxy replaces it with the real value before forwarding each request. For example, if you set the agent's GitHub token to `__GITHUB_PAT__`, the agent sends:++```text+Authorization: Bearer __GITHUB_PAT__+```++GitHub receives the real token, and the agent never holds it.++We recommend using substitutions when your agent's tool won't run without a token of its own, or when the API expects the credential outside a header, such as in the URL path or the query string.++<Info>+Substitutions work with every credential type, including pass-through.+</Info>++### Add a substitution++<Steps>+ <Step>+ On the **Credential** step, expand **Advanced Options** and select **Add Substitution**.+ </Step>+ <Step>+ Enter the placeholder your agent sends in **Replace**, and the real value in **With**.++ <Tip>+ The proxy replaces every occurrence of the placeholder, so pick one that won't appear anywhere else in the request.+ </Tip>+ </Step>+ <Step>+ Under **Replace In**, select where the proxy looks for the placeholder: **URL Path**, **Query String**, **Headers**, or **Body**.+ </Step>+ <Step>+ In the agent's environment or configuration, set the credential to the placeholder, such as `GITHUB_TOKEN=__GITHUB_PAT__`. Infisical doesn't set the placeholder for you.++ <Tip>+ Some tools check a token's format before they send it. If the agent's tool does, make the placeholder match the format of the real key, such as `ghp_` followed by 36 characters for a GitHub token.+ </Tip>+ </Step>+</Steps>++### Encoding and body limits++- **Slashes in the URL path:** The proxy sends a `/` in the real value as `%2F`, so a GitLab project like `group/project` stays one path segment and still passes the service's [path prefixes](#paths)+- **Large or compressed bodies:** The proxy doesn't replace placeholders in a body larger than 10 MB or compressed with `Content-Encoding` (it forwards the body unchanged and logs a warning that names the service)diff --cc docs/documentation/platform/agent-vault/plan-your-setup.mdxindex 9739327d9a,df2aae0fe2..90e94ab00c--- a/docs/documentation/platform/agent-vault/plan-your-setup.mdx+++ b/docs/documentation/platform/agent-vault/plan-your-setup.mdx@@@ -161,7 -161,7 +161,7 @@@ Configure the following options to get</AgentVaultSetupStep><AgentVaultSetupStep step="forward">- The [real credential](/documentation/platform/agent-vault/http-apis#credential-types) is added to the request at the proxy, so it never passes through the agent. If you've [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs), the request appears in the session's logs.- The [real credential](/documentation/platform/agent-vault/services#credential-types) is added to the request at the proxy, so it never passes through the agent. The request appears in the session's [logs](/documentation/platform/agent-vault/session-logs).++ The [real credential](/documentation/platform/agent-vault/http-apis#credential-types) is added to the request at the proxy, so it never passes through the agent. The request appears in the session's [logs](/documentation/platform/agent-vault/session-logs).The proxy only attaches credentials for the services in the access bundle. Requests to any other host go out without a credential, unless the proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy) blocks them.</AgentVaultSetupStep>@@@ -214,8 -214,8 +214,8 @@@ Follow these pages in order</AgentVaultSetupBranch><AgentVaultSetupBranch building="scheduled,platform">- <li>[Create an access bundle](/documentation/platform/agent-vault/access-bundles#create-an-access-bundle), with a service for each API the agent calls</li>+ <li>[Create an access bundle](/documentation/platform/agent-vault/access-bundles#create-an-access-bundle), with a service for each external system the agent uses</li>- <li>[Enroll a proxy](/documentation/platform/agent-vault/proxies#create-and-enroll-a-proxy), and run it with Docker or systemd so that it keeps running between jobs</li>+ <li>[Create a proxy](/documentation/platform/agent-vault/proxies#create-a-proxy-and-start-it), and run it with Docker, Kubernetes, or systemd so that it keeps running between jobs</li></AgentVaultSetupBranch><AgentVaultSetupBranch building="scheduled" runs="none,computer,server"><li>[Create sessions with the CLI](/documentation/platform/agent-vault/sessions-cli): set up a machine identity, then run the agent from cron or systemd</li>diff --cc docs/documentation/platform/agent-vault/proxies.mdxindex 4e73a4b12f,fcb9d0d74a..c87816e445--- a/docs/documentation/platform/agent-vault/proxies.mdx+++ b/docs/documentation/platform/agent-vault/proxies.mdx@@@ -143,8 -183,9 +183,9 @@@ no service covers host "internal.examplThe proxy also returns a 403 for:-- A request to a port the service's [host pattern](/documentation/platform/agent-vault/services#host-patterns) doesn't name, such as `example.com:8443` for a service on `example.com`, which only covers port `443`-- A request that breaks the service's [method or path rules](/documentation/platform/agent-vault/services#methods-and-paths), under either traffic policy+- A request to a port the service's [host pattern](/documentation/platform/agent-vault/http-apis#host-patterns) doesn't name, such as `example.com:8443` for a service on `example.com`, which only covers port `443`+- A request that breaks the service's [method or path rules](/documentation/platform/agent-vault/http-apis#methods-and-paths), under either traffic policy+ - A request to a service that needs the session owner's [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), before they set them up### Exceptionsdiff --cc docs/documentation/platform/agent-vault/session-logs.mdxindex 9253aebafd,a71535fc92..7af4bf8fc5--- a/docs/documentation/platform/agent-vault/session-logs.mdx+++ b/docs/documentation/platform/agent-vault/session-logs.mdx@@@ -8,118 -8,9 +8,9 @@@ import SelfHostedInstance from "/snippeimport CreateIamRole from "/snippets/app-connections/aws/create-iam-role.mdx";import AgentVaultSessionLogsCorsRule from "/snippets/app-connections/aws/agent-vault-session-logs-cors-rule.mdx";- <Info>- Session logs are a paid feature.-- If you're using Infisical Cloud, they're available under the **Enterprise Tier**. If you're self-hosting Infisical, contact [email protected] to purchase an enterprise license to use them.- </Info>--A session log is a record of every request an agent makes during a [session](/documentation/platform/agent-vault/sessions): the method, host, path, status code, and whether the proxy attached a credential. The [proxy](/documentation/platform/agent-vault/proxies) adds every request it receives to the session log, including requests to hosts that no [access bundle](/documentation/platform/agent-vault/access-bundles) covers.+A session log is a record of every request an agent makes during a [session](/documentation/platform/agent-vault/sessions): the method, host, path, status code, whether the proxy attached a credential, and for an [MCP server](/documentation/platform/agent-vault/mcp-servers), the tool the agent called. The [proxy](/documentation/platform/agent-vault/proxies) adds every request it receives to the session log, including requests to hosts that no [access bundle](/documentation/platform/agent-vault/access-bundles) covers.- The proxy encrypts the records before they leave your network and uploads them to an Amazon S3 bucket you own.-- ## Setting up session logs-- Infisical reaches your bucket through an [AWS app connection](/integrations/app-connections/aws/), which signs in to AWS by assuming an IAM role you create.-- You'll switch between Infisical and AWS during setup: Infisical generates the AWS policy for your bucket, you set up the bucket and role in AWS, and then you create the connection in Infisical with the role's ARN.-- ### Prerequisites-- - The [Admin role](/documentation/platform/agent-vault/access-control) in Agent Vault- - An [Amazon S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) to store the records in- - Permission in AWS to edit the bucket's CORS configuration, create IAM roles, and attach policies to them-- ### Step 1: Start in Infisical-- <Steps>- <Step>- In Agent Vault, go to **Administration** > **Settings** and select **Set Up Session Logs**.- </Step>- <Step>- Enter the **Region** and **Bucket** of your S3 bucket.- </Step>- <Step>- Optionally, enter a **Key Prefix** to store session logs under one path in a bucket you also use for other data.- </Step>- <Step>- Select **View AWS Setup**. Infisical shows an **IAM policy** with your bucket and key prefix already filled in, so you can paste it into AWS as it is.- </Step>- </Steps>-- Leave the **Session Logs** dialog open. You'll fill in **AWS Connection** in [Step 3](#step-3-finish-in-infisical), after you create the role it uses. Open AWS in another browser tab.-- ### Step 2: Set up in AWS-- #### Add a CORS rule to the bucket-- Your browser downloads session logs directly from your bucket, so the bucket has to accept requests from Infisical. Add a CORS rule for Infisical to the bucket.-- <Steps>- <AgentVaultSessionLogsCorsRule />- </Steps>-- #### Create an IAM role for Infisical-- <Note>- If you already have an AWS app connection you want to use, skip to [Attach the IAM policy](#attach-the-iam-policy).- </Note>-- Infisical assumes this role to write session logs to the bucket.-- <SelfHostedInstance />-- <Steps>- <CreateIamRole externalId="organization" />- </Steps>-- #### Attach the IAM policy-- Attach the **IAM policy** from [Step 1](#step-1-start-in-infisical) to the IAM role, or to the role or user your existing connection signs in as.-- <Steps>- <Step>- In the IAM console, open the role or user. On the **Permissions** tab, select **Add permissions** > **Create inline policy**, switch to the **JSON** editor, and paste the policy.- </Step>- <Step>- Select **Next**, enter a **Policy name**, then select **Create policy**.- </Step>- <Step>- If you created a new role, copy its **ARN** from the **Summary** section.-- - </Step>- </Steps>-- ### Step 3: Finish in Infisical-- Go back to the **Session Logs** dialog.-- <Steps>- <Step>- Under **AWS Connection**, select **Create New Connection**.-- <Note>- If you already have an AWS app connection you want to use, select it here instead. Then, select **Save** and skip the remaining steps.- </Note>- </Step>- <Step>- Enter a **Name**, keep the **Assume Role (Recommended)** method, paste the role's ARN into **Role ARN**, and select **Connect to AWS**. Infisical creates the connection in Agent Vault and selects it.- </Step>- <Step>- Select **Save**.- </Step>- </Steps>-- <Frame>- <img src="/images/platform/agent-vault/session-logs-setup.png" alt="The Session Logs dialog with Enable turned on and an AWS connection, region, bucket, and key prefix filled in" />- </Frame>-- When you save, Infisical checks that the bucket exists and that the IAM user or role can write to it. If either check fails, Infisical shows the error and doesn't save the settings. If your browser can't read from the bucket, the **Session Logs** card shows a warning after you save.-- <Check>- You've successfully set up session logs within Agent Vault.- </Check>+ The proxy encrypts the records before they leave your network, and Infisical stores them for you. If you self-host Infisical, your server administrator [sets up where Infisical stores them](/self-hosting/guides/session-log-storage).## Viewing session logs@@@ -248,24 -123,136 +139,147 @@@ The outcome is one of four| **Blocked** | The proxy refused the request, for one of the reasons in [Blocked requests](/documentation/platform/agent-vault/proxies#blocked-requests) || **Error** | The proxy couldn't reach the destination host |-Request and response bodies, headers, and query strings aren't recorded.+Request and response bodies, headers, and query strings aren't recorded. For a request to an MCP server, the proxy reads only the method and tool name of each call from the request body.++### MCP tool calls++If a request matched an MCP service, its row shows an **MCP** badge and the call the agent made, in place of the path:++- For a tool call, the tool's name, such as `create_issue`+- For any other call, the method, such as `initialize` or `tools/list`++The proxy never records a tool's arguments or results.++If the agent sent several calls in one request, the row shows the first one. If the proxy can't read the calls, such as from a compressed body, the row shows the request path.+ ## Storing session logs in your own S3 bucket++ To keep session logs longer than 30 days, or in your own AWS account, store them in an Amazon S3 bucket you own. This is called external storage.++ <Info>+ External storage is a paid feature.++ If you're using Infisical Cloud, it's available under the **Enterprise Tier**. If you're self-hosting Infisical, contact [email protected] to purchase an enterprise license to use it.+ </Info>++ Infisical reaches your bucket through an [AWS app connection](/integrations/app-connections/aws/), which signs in to AWS by assuming an IAM role you create.++ You'll switch between Infisical and AWS during setup: Infisical generates the AWS policy for your bucket, you set up the bucket and role in AWS, and then you create the connection in Infisical with the role's ARN.++ ### Prerequisites++ - The [Admin role](/documentation/platform/agent-vault/access-control) in Agent Vault+ - An [Amazon S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) to store the records in+ - Permission in AWS to edit the bucket's CORS configuration, create IAM roles, and attach policies to them++ ### Step 1: Start in Infisical++ <Steps>+ <Step>+ In Agent Vault, go to **Administration** > **Settings** and select **Configure** or **Set Up Session Logs** on the **Session Logs** card.+ </Step>+ <Step>+ Turn on **Enable**, then under **Storage**, select **External storage**.+ </Step>+ <Step>+ Enter the **Region** and **Bucket** of your S3 bucket.+ </Step>+ <Step>+ Optionally, enter a **Key Prefix** to store session logs under one path in a bucket you also use for other data.+ </Step>+ <Step>+ Select **View AWS Setup**. Infisical shows an **IAM policy** with your bucket and key prefix already filled in, so you can paste it into AWS as it is.+ </Step>+ </Steps>++ Leave the **Session Logs** dialog open. You'll fill in **AWS Connection** in [Step 3](#step-3-finish-in-infisical), after you create the role it uses. Open AWS in another browser tab.++ ### Step 2: Set up in AWS++ #### Add a CORS rule to the bucket++ Your browser downloads session logs directly from your bucket, so the bucket has to accept requests from Infisical. Add a CORS rule for Infisical to the bucket.++ <Steps>+ <AgentVaultSessionLogsCorsRule />+ </Steps>++ #### Create an IAM role for Infisical++ <Note>+ If you already have an AWS app connection you want to use, skip to [Attach the IAM policy](#attach-the-iam-policy).+ </Note>++ Infisical assumes this role to write session logs to the bucket.++ <SelfHostedInstance />++ <Steps>+ <CreateIamRole externalId="organization" />+ </Steps>++ #### Attach the IAM policy++ Attach the **IAM policy** from [Step 1](#step-1-start-in-infisical) to the IAM role, or to the role or user your existing connection signs in as.++ <Steps>+ <Step>+ In the IAM console, open the role or user. On the **Permissions** tab, select **Add permissions** > **Create inline policy**, switch to the **JSON** editor, and paste the policy.+ </Step>+ <Step>+ Select **Next**, enter a **Policy name**, then select **Create policy**.+ </Step>+ <Step>+ If you created a new role, copy its **ARN** from the **Summary** section.++ + </Step>+ </Steps>++ ### Step 3: Finish in Infisical++ Go back to the **Session Logs** dialog.++ <Steps>+ <Step>+ Under **AWS Connection**, select **Create New Connection**.++ <Note>+ If you already have an AWS app connection you want to use, select it here instead. Then, select **Save** and skip the remaining steps.+ </Note>+ </Step>+ <Step>+ Enter a **Name**, keep the **Assume Role (Recommended)** method, paste the role's ARN into **Role ARN**, and select **Connect to AWS**. Infisical creates the connection in Agent Vault and selects it.+ </Step>+ <Step>+ Select **Save**.+ </Step>+ </Steps>++ <Frame>+ <img src="/images/platform/agent-vault/session-logs-setup.png" alt="The Session Logs dialog with Enable turned on and an AWS connection, region, bucket, and key prefix filled in" />+ </Frame>++ When you save, Infisical checks that the bucket exists and that the IAM user or role can write to it. If either check fails, Infisical shows the error and doesn't save the settings. If your browser can't read from the bucket, the **Session Logs** card shows a warning after you save.++ <Check>+ You've successfully set up external storage for session logs.+ </Check>+## Managing session logs+ ### Turning session logs off++ Session logs are on unless an admin turns them off. To stop recording, turn off **Enable** in the **Session Logs** dialog and select **Save**.++ Turning session logs off also hides the logs already recorded:++ - With default storage, turning session logs back on shows those logs again, as long as they're less than 30 days old+ - With external storage, Infisical forgets the bucket and its AWS connection (to see the logs again, set up the same bucket and key prefix)+### Connections- Session logs use one AWS connection at a time, which you select in the **Session Logs** dialog.+ If you use external storage, session logs use one AWS connection at a time, which you select in the **Session Logs** dialog.To update the connection's AWS credentials, open the menu next to **Configure** on the **Session Logs** card and select **Edit AWS Credentials**. If the connection belongs to your organization, update its credentials under **Integrations** in your organization instead.diff --cc docs/documentation/platform/agent-vault/sessions-cli.mdxindex d0857397fc,15d6e117d9..5557719315--- a/docs/documentation/platform/agent-vault/sessions-cli.mdx+++ b/docs/documentation/platform/agent-vault/sessions-cli.mdx@@@ -179,6 -179,9 +179,9 @@@ After the agent runs, go to **Sessions*<Accordion title="The agent loses access to APIs partway through a run">If the agent's requests start failing with a 403 from the proxy, such as `CONNECT tunnel failed, response 403`, the session expired before the agent finished. Set a longer `--ttl`.</Accordion>+ <Accordion title="Requests to a service fail with "needs your personal values"">- The service [takes part of its credential from each member](/documentation/platform/agent-vault/services#member-provided-values), and whoever the session belongs to hasn't set up their personal values for it yet. A user sets them up under **Access Bundles**: select the bundle named in the message, then [set up the personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values). A machine identity sets them up with [the set personal values endpoint](/api-reference/endpoints/agent-vault-services/set-personal-values). Once they're saved, the proxy picks them up within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).++ The service [takes part of its credential from each member](/documentation/platform/agent-vault/http-apis#member-provided-values), and whoever the session belongs to hasn't set up their personal values for it yet. A user sets them up under **Access Bundles**: select the bundle named in the message, then [set up the personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values). A machine identity sets them up with [the set personal values endpoint](/api-reference/endpoints/agent-vault-services/set-personal-values). Once they're saved, the proxy picks them up within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).+ </Accordion><Accordion title="A session stays Active after the agent stopped">The CLI couldn't revoke the session, for example because the machine shut down or the process was killed with `SIGKILL`. [Revoke the session](/documentation/platform/agent-vault/sessions#revoke-a-session) on the **Sessions** page, or let it expire at the end of its `--ttl`.</Accordion>diff --cc docs/snippets/agent-vault/QuickstartBody.mdxindex 36d34e61c1,55b7908e08..755e7793f1--- a/docs/snippets/agent-vault/QuickstartBody.mdx+++ b/docs/snippets/agent-vault/QuickstartBody.mdx@@@ -63,12 -63,12 +63,12 @@@ First, create an [access bundle](/docum</Steps><Tip>- You can repeat these steps to add as many more services as you like to the access bundle.+ You can repeat these steps to add as many more services as you like to the access bundle. To give the agent a remote MCP server, such as Linear's or Notion's, [add an MCP server](/documentation/platform/agent-vault/mcp-servers#add-an-mcp-server).</Tip>- ### Enroll a proxy+ ### Create a proxy- Next, enroll a [proxy](/documentation/platform/agent-vault/proxies) to intercept API calls from your agent.+ Next, create a [proxy](/documentation/platform/agent-vault/proxies) to intercept API calls from your agent.<Steps><Step>diff --cc frontend/src/components/agent-vault/service-sheet/CredentialFields.tsxindex 27e0e9501d,56fcece513..a3066639f1--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx@@@ -30,7 -49,7 +49,8 @@@ import { ReferenceHighlights } from "./import { SendsPreview } from "./SendsPreview";import {CREDENTIAL_LABELS,+ FORM_FIELD_OF_CREDENTIAL_FIELD,+ HTTP_CREDENTIAL_TYPES,TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";@@@ -234,12 -269,81 +270,82 @@@ export const SecretInput = <TName exten);};+ const MEMBER_FIELDS_OF_TYPE: Record<AgentVaultCredentialType, TAgentVaultMemberProvidedField[]> = {+ [AgentVaultCredentialType.Bearer]: [AgentVaultVariableReferenceField.CredentialValue],+ [AgentVaultCredentialType.Basic]: [+ AgentVaultVariableReferenceField.CredentialUsername,+ AgentVaultVariableReferenceField.CredentialValue+ ],- [AgentVaultCredentialType.Passthrough]: []++ [AgentVaultCredentialType.Passthrough]: [],++ [AgentVaultCredentialType.OAuth]: []+ };++ const MemberProvidedToggle = ({+ label,+ isOn,+ onChange+ }: {+ label: string;+ isOn: boolean;+ onChange: (isOn: boolean) => void;+ }) => {+ const id = useId();+ return (+ <div className="flex items-center gap-1.5">+ <HoverCard openDelay={150} closeDelay={150}>+ <HoverCardTrigger asChild>+ <InfoIcon+ aria-label={`About member-provided ${label.toLowerCase()}s`}+ className="size-3.5 text-muted"+ />+ </HoverCardTrigger>+ <HoverCardContent className="w-80">+ <p>Choose who sets the {label.toLowerCase()} the proxy sends for this service.</p>+ <ul className="mt-2 flex list-disc flex-col gap-1 pl-4">+ <li>Off: you set the {label.toLowerCase()} here, and every session uses it.</li>+ <li>+ On: each member sets their own from the access bundle page, and a session uses the{" "}+ {label.toLowerCase()} of whoever started it.+ </li>+ </ul>+ <a+ href={AgentVaultDocsUrls.memberProvidedValues}+ target="_blank"+ rel="noopener noreferrer"+ className="mt-2 inline-flex items-center gap-1 underline underline-offset-2 hover:text-foreground"+ >+ Learn more+ <ExternalLinkIcon className="size-3" />+ </a>+ </HoverCardContent>+ </HoverCard>+ <FieldLabel htmlFor={id}>Member provided</FieldLabel>+ <Toggle id={id} size="sm" variant="av" checked={isOn} onCheckedChange={onChange} />+ </div>+ );+ };++ const MemberProvidedInput = ({ label }: { label: string }) => (+ <InputGroup>+ <InputGroupAddon>+ <LockIcon />+ </InputGroupAddon>+ <InputGroupInput+ disabled+ aria-label={`${label}, set by each member`}+ placeholder="Member provided"+ />+ </InputGroup>+ );+type Props = {storedType?: AgentVaultCredentialType;+ /** The fields that were member-provided when the sheet opened, which have no stored value behind them. */+ storedMemberFields?: TAgentVaultMemberProvidedField[];};- export const CredentialFields = ({ storedType }: Props) => {- const { control, watch, setValue } = useFormContext<TServiceForm>();+ export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props) => {+ const { control, watch, setValue, clearErrors } = useFormContext<TServiceForm>();const { storedKeys } = useServiceVariables();const credentialType = watch("credentialType");const secret = watch("secret");diff --cc frontend/src/components/agent-vault/service-sheet/ReviewFields.tsxindex cb2c926dc2,86b8267652..4dce664f7f--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx@@@ -8,8 -8,11 +8,13 @@@ importDetailLabel,DetailValue} from "@app/components/v3";- import { AgentVaultCredentialType, AgentVaultServiceType } from "@app/hooks/api/agentVault";+ import {+ AgentVaultCredentialType,++ AgentVaultServiceType,+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField+ } from "@app/hooks/api/agentVault";+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";import {CREDENTIAL_LABELS,@@@ -30,10 -32,11 +36,13 @@@ const credentialPreview = (form:}): string | null => {if (form.credentialType === AgentVaultCredentialType.Passthrough) return null;if (form.credentialType === AgentVaultCredentialType.Basic) return `Authorization: Basic ${MASK}`;+ if (form.credentialType === AgentVaultCredentialType.OAuth)+ return `Authorization: Bearer ${MASK}`;const prefix = form.headerPrefix ? `${form.headerPrefix} ` : "";- return `${form.headerName || "Authorization"}: ${prefix}${MASK}`;+ const value = form.memberProvidedFields.includes(AgentVaultVariableReferenceField.CredentialValue)+ ? "<member value>"+ : MASK;+ return `${form.headerName || "Authorization"}: ${prefix}${value}`;};const alignColumns = (rows: string[][]) => {@@@ -50,10 -53,12 +59,13 @@@type Props = {isUpdate: boolean;+ service?: TAgentVaultService | null;+ storedType?: AgentVaultCredentialType;+ /** The fields that were member-provided when the sheet opened, which have no stored value behind them. */+ storedMemberFields?: TAgentVaultMemberProvidedField[];};- export const ReviewFields = ({ isUpdate, service }: Props) => {-export const ReviewFields = ({ isUpdate, storedType, storedMemberFields = [] }: Props) => {++export const ReviewFields = ({ isUpdate, service, storedType, storedMemberFields = [] }: Props) => {const { watch } = useFormContext<TServiceForm>();const form = watch();@@@ -153,13 -140,17 +174,17 @@@{isBasic && (<Detail><DetailLabel>Username</DetailLabel>- <DetailValue>{outcome(form.username, true)}</DetailValue>+ <DetailValue>+ {outcome(form.username, true, AgentVaultVariableReferenceField.CredentialUsername)}+ </DetailValue></Detail>)}- {form.credentialType !== AgentVaultCredentialType.Passthrough && (+ {form.credentialType !== AgentVaultCredentialType.Passthrough && !isOAuth && (<Detail><DetailLabel>{secretLabel}</DetailLabel>- <DetailValue>{outcome(form.secret, isBasic)}</DetailValue>+ <DetailValue>+ {outcome(form.secret, isBasic, AgentVaultVariableReferenceField.CredentialValue)}+ </DetailValue></Detail>)}</div>diff --cc frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex 12dc1dc13e,a89b0ebe23..3d0bd67afe--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@@ -42,10 -26,8 +42,11 @@@ import { findVariableReferences, VARIABimport { useDebounce, useDiscardChangesGuard, useWizardSteps } from "@app/hooks";import {AgentVaultCredentialType,+ AgentVaultMcpTransport,+ AgentVaultServiceType,AgentVaultVariableReferenceField,+ SERVICE_SAVE_HANDLED_ERROR_CODES,+ TAgentVaultMemberProvidedField,useAgentVaultVariableKeyStatus,useCreateAgentVaultService,useUpdateAgentVaultService@@@ -70,11 -49,10 +71,12 @@@ importbuildServiceSchema,displayHostPattern,HTTP_METHODS,- isAllMethods,+ isOAuthAuthorizationMissing,+ MCP_SERVICE_STEP_FIELDS,SERVICE_STEP_FIELDS,+ SERVICE_TYPE_LABELS,ServiceStep,+ storedMemberFields,TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";@@@ -99,12 -74,7 +101,13 @@@ const BLANK_SERVICE_FORM: TServiceFormheaderPrefix: "Bearer",username: "",secret: "",+ oauthAuthorizationId: "",+ oauthAuthorizedUrl: "",+ oauthScopes: [],+ oauthAuthorizationRejection: "",+ oauthClientId: "",+ oauthClientSecret: "",+ memberProvidedFields: [],methods: [...HTTP_METHODS],pathPrefixes: [],customHeaders: [],@@@ -439,29 -297,13 +442,33 @@@ export const ServiceSheet = (setStep(0);setTemplate(null);+ setOpenItem(service?.type === AgentVaultServiceType.Mcp ? "" : ADVANCED_ITEM);- if (service) {+ if (service?.type === AgentVaultServiceType.Mcp) {+ const { credential } = service;+ const isBearer = credential.type === AgentVaultCredentialType.Bearer;+ reset({+ ...BLANK_MCP_SERVICE_FORM,+ name: service.name,+ serverUrl: service.serverUrl,+ transport: service.transport,+ credentialType: isBearer ? AgentVaultCredentialType.Bearer : AgentVaultCredentialType.OAuth,+ headerName: isBearer ? credential.headerName : "Authorization",+ headerPrefix: isBearer ? credential.headerPrefix : "Bearer",+ secret: isBearer ? UNCHANGED_SECRET : "",+ customHeaders: service.customHeaders.map((header) => ({+ id: header.id,+ name: header.name,+ prefix: header.prefix,+ value: UNCHANGED_SECRET+ }))+ });+ } else if (service) {const { credential } = service;+ const memberProvidedFields = storedMemberFields(service);+ // A member-provided field has no stored value, so it starts empty rather than as "unchanged".+ const storedValue = (field: TAgentVaultMemberProvidedField) =>+ memberProvidedFields.includes(field) ? "" : UNCHANGED_SECRET;reset({...BLANK_SERVICE_FORM,name: service.name,@@@ -809,38 -692,24 +823,46 @@@<p className="mt-1 text-sm text-muted">{current.subtitle}</p></div>- {current.step === ServiceStep.Details && <DetailsFields />}- {current.step === ServiceStep.Credential && (+ {current.step === ServiceStep.Details && (+ <div className="flex flex-col gap-5">+ {prefillHost && !isUpdate && (+ <PrefillTypeField+ value={isMcp ? AgentVaultServiceType.Mcp : AgentVaultServiceType.Http}+ onChange={switchPrefillType}+ />+ )}+ {isMcp ? <McpDetailsFields /> : <DetailsFields />}+ </div>+ )}+ {current.step === ServiceStep.Credential && isMcp && (+ <ServiceVariablesContext.Provider value={serviceVariables}>+ <McpCredentialFields+ accessBundleId={accessBundleId}+ service={service}+ openItem={openItem}+ onOpenChange={setOpenItem}+ onSignInChange={setIsSigningIn}+ />+ </ServiceVariablesContext.Provider>+ )}+ {current.step === ServiceStep.Credential && !isMcp && (<ServiceVariablesContext.Provider value={serviceVariables}><div className="flex flex-col gap-5">- <CredentialFields storedType={service?.credential.type} />+ <CredentialFields+ storedType={service?.credential.type}+ storedMemberFields={storedMemberFields(service)}+ /><TransformationsFields openItem={openItem} onOpenChange={setOpenItem} /></div></ServiceVariablesContext.Provider>)}{current.step === ServiceStep.Review && (- <ReviewFields isUpdate={isUpdate} service={service} />+ <ReviewFields+ isUpdate={isUpdate}++ service={service}+ storedType={service?.credential.type}+ storedMemberFields={storedMemberFields(service)}+ />)}</div>diff --cc frontend/src/components/agent-vault/service-sheet/serviceRequest.test.tsindex 2669c1fb05,0000000000..ec07b38a97mode 100644,000000..100644--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts@@@ -1,258 -1,0 +1,272 @@@+import { describe, expect, it } from "vitest";++import {+ AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultMcpTransport,+ AgentVaultServiceType,+ AgentVaultSubstitutionSurface+} from "@app/hooks/api/agentVault";++import { buildCreateServiceRequest, buildUpdateServiceRequest } from "./serviceRequest";+import { HTTP_METHODS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";++const SERVER_URL = "https://mcp.linear.app/mcp";++const form = (overrides: Partial<TServiceForm> = {}): TServiceForm => ({+ serviceType: AgentVaultServiceType.Http,+ name: "stripe",+ serverUrl: "",+ transport: AgentVaultMcpTransport.StreamableHttp,+ hosts: ["api.stripe.com"],+ hostDraft: "",+ pathDraft: "",+ credentialType: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",+ username: "",+ secret: "sk_test",+ oauthAuthorizationId: "",+ oauthAuthorizedUrl: "",+ oauthScopes: [],++ memberProvidedFields: [],+ methods: [...HTTP_METHODS],+ pathPrefixes: [],+ customHeaders: [],+ substitutions: [],+ ...overrides+});++const mcpForm = (overrides: Partial<TServiceForm> = {}) =>+ form({+ serviceType: AgentVaultServiceType.Mcp,+ name: "linear-mcp",+ serverUrl: ` ${SERVER_URL} `,+ hosts: [],+ credentialType: AgentVaultCredentialType.OAuth,+ secret: "",+ ...overrides+ });++describe("buildCreateServiceRequest", () => {+ it("builds an HTTP service with its policy and transformations", () => {+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ form({+ hosts: ["api.stripe.com", "files.stripe.com"],+ methods: [AgentVaultHttpMethod.Get],+ pathPrefixes: ["/v1"],+ headerName: "",+ customHeaders: [{ name: "X-Org", prefix: "", value: "acme" }],+ substitutions: [+ {+ placeholder: "ACCOUNT",+ value: "acct_1",+ surfaces: [AgentVaultSubstitutionSurface.Path]+ }+ ]+ })+ )+ ).toEqual({+ accessBundleId: "bundle-1",+ type: AgentVaultServiceType.Http,+ name: "stripe",+ hostPattern: "api.stripe.com,files.stripe.com",+ allowedMethods: [AgentVaultHttpMethod.Get],+ allowedPathPrefixes: ["/v1"],+ credential: {+ type: AgentVaultCredentialType.Bearer,+ headerName: undefined,+ headerPrefix: "Bearer",- value: "sk_test"++ value: "sk_test",++ memberProvidedFields: []+ },+ customHeaders: [{ name: "X-Org", prefix: "", value: "acme" }],+ substitutions: [+ { placeholder: "ACCOUNT", value: "acct_1", surfaces: [AgentVaultSubstitutionSurface.Path] }+ ]+ });+ });++ it("sends null for every method and no path prefixes", () => {+ const request = buildCreateServiceRequest("bundle-1", form());+ expect(request).toMatchObject({ allowedMethods: null, allowedPathPrefixes: null });+ });++ it("builds basic and pass-through credentials", () => {+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ form({ credentialType: AgentVaultCredentialType.Basic, username: "me", secret: "pw" })+ ).credential- ).toEqual({ type: AgentVaultCredentialType.Basic, username: "me", password: "pw" });++ ).toEqual({++ type: AgentVaultCredentialType.Basic,++ username: "me",++ password: "pw",++ memberProvidedFields: []++ });+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ form({ credentialType: AgentVaultCredentialType.Passthrough })+ ).credential+ ).toEqual({ type: AgentVaultCredentialType.Passthrough });+ });++ it("builds an MCP service with the authorization made for its URL", () => {+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ mcpForm({+ oauthAuthorizationId: "auth-1",+ oauthAuthorizedUrl: SERVER_URL,+ oauthClientId: "client-id",+ oauthClientSecret: "client-secret"+ })+ )+ ).toEqual({+ accessBundleId: "bundle-1",+ type: AgentVaultServiceType.Mcp,+ name: "linear-mcp",+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ customHeaders: [],+ credential: { type: AgentVaultCredentialType.OAuth, authorizationId: "auth-1" }+ });+ });++ it("sends an empty authorization when it was made for another URL", () => {+ const request = buildCreateServiceRequest(+ "bundle-1",+ mcpForm({ oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: "https://other.example/mcp" })+ );+ expect(request.credential).toMatchObject({ authorizationId: "" });+ });++ it("builds an MCP bearer credential", () => {+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ mcpForm({ credentialType: AgentVaultCredentialType.Bearer, secret: "lin_api" })+ ).credential+ ).toEqual({+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "lin_api"+ });+ });+});++describe("buildUpdateServiceRequest", () => {+ it("omits untouched secrets and keeps row ids", () => {+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ form({+ secret: UNCHANGED_SECRET,+ customHeaders: [{ id: "h-1", name: "X-Org", prefix: "", value: UNCHANGED_SECRET }],+ substitutions: [+ {+ id: "s-1",+ placeholder: "ACCOUNT",+ value: UNCHANGED_SECRET,+ surfaces: [AgentVaultSubstitutionSurface.Path]+ }+ ]+ })+ )+ ).toEqual({+ accessBundleId: "bundle-1",+ serviceId: "service-1",+ type: AgentVaultServiceType.Http,+ name: "stripe",+ hostPattern: "api.stripe.com",+ allowedMethods: null,+ allowedPathPrefixes: null,+ credential: {+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",- value: undefined++ value: undefined,++ memberProvidedFields: []+ },+ customHeaders: [{ id: "h-1", name: "X-Org", prefix: "" }],+ substitutions: [+ { id: "s-1", placeholder: "ACCOUNT", surfaces: [AgentVaultSubstitutionSurface.Path] }+ ]+ });+ });++ it("omits an empty bearer token but sends an emptied basic half", () => {+ expect(+ buildUpdateServiceRequest("bundle-1", "service-1", form({ secret: "", headerName: "" }))+ .credential+ ).toEqual({+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",- value: undefined++ value: undefined,++ memberProvidedFields: []+ });+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ form({+ credentialType: AgentVaultCredentialType.Basic,+ username: UNCHANGED_SECRET,+ secret: ""+ })+ ).credential- ).toEqual({ type: AgentVaultCredentialType.Basic, username: undefined, password: "" });++ ).toEqual({++ type: AgentVaultCredentialType.Basic,++ username: undefined,++ password: "",++ memberProvidedFields: []++ });+ });++ it("leaves the OAuth credential out unless a new authorization matches the URL", () => {+ expect(buildUpdateServiceRequest("bundle-1", "service-1", mcpForm())).toEqual({+ accessBundleId: "bundle-1",+ serviceId: "service-1",+ type: AgentVaultServiceType.Mcp,+ name: "linear-mcp",+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ customHeaders: []+ });+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ mcpForm({ oauthAuthorizationId: "auth-2", oauthAuthorizedUrl: "https://other.example/mcp" })+ )+ ).not.toHaveProperty("credential");+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ mcpForm({ oauthAuthorizationId: "auth-2", oauthAuthorizedUrl: SERVER_URL })+ ).credential+ ).toEqual({ type: AgentVaultCredentialType.OAuth, authorizationId: "auth-2" });+ });++ it("never sends a header name or prefix for OAuth", () => {+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ mcpForm({+ headerName: "X-Api-Key",+ headerPrefix: "Token",+ oauthAuthorizationId: "auth-2",+ oauthAuthorizedUrl: SERVER_URL+ })+ ).credential+ ).toEqual({ type: AgentVaultCredentialType.OAuth, authorizationId: "auth-2" });+ });+});diff --cc frontend/src/components/agent-vault/service-sheet/serviceRequest.tsindex 95affd0c6c,0000000000..877864fdfdmode 100644,000000..100644--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts@@@ -1,148 -1,0 +1,191 @@@- import { AgentVaultCredentialType, AgentVaultServiceType } from "@app/hooks/api/agentVault";++import {++ AgentVaultCredentialType,++ AgentVaultServiceType,++ AgentVaultVariableReferenceField,++ TAgentVaultMemberProvidedField++} from "@app/hooks/api/agentVault";+import {+ TAgentVaultCredentialInput,+ TAgentVaultCredentialUpdate,+ TCreateAgentVaultServiceDTO,+ TUpdateAgentVaultServiceDTO+} from "@app/hooks/api/agentVault/types";++import {+ isAllMethods,+ newOAuthAuthorizationId,+ TServiceForm,+ UNCHANGED_SECRET+} from "./serviceSchema";++const bearerCredential = (data: TServiceForm) => ({+ type: AgentVaultCredentialType.Bearer as const,+ headerName: data.headerName || undefined,+ headerPrefix: data.headerPrefix ?? "",+ value: data.secret ?? ""+});+++const memberFieldsOf = (data: TServiceForm) => {++ const isMemberProvided = (field: TAgentVaultMemberProvidedField) =>++ data.memberProvidedFields.includes(field);++ return {++ bearer: isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)++ ? [AgentVaultVariableReferenceField.CredentialValue as const]++ : [],++ basic: (++ [++ AgentVaultVariableReferenceField.CredentialUsername,++ AgentVaultVariableReferenceField.CredentialValue++ ] as TAgentVaultMemberProvidedField[]++ ).filter(isMemberProvided),++ isMemberProvided++ };++};++++// A member-provided field is sent without a value: each member sets their own.+const buildHttpCredential = (data: TServiceForm): TAgentVaultCredentialInput => {++ const { bearer, basic, isMemberProvided } = memberFieldsOf(data);+ if (data.credentialType === AgentVaultCredentialType.Passthrough) {+ return { type: AgentVaultCredentialType.Passthrough };+ }+ if (data.credentialType === AgentVaultCredentialType.Basic) {+ return {+ type: AgentVaultCredentialType.Basic,- username: data.username ?? "",- password: data.secret ?? ""++ username: isMemberProvided(AgentVaultVariableReferenceField.CredentialUsername)++ ? undefined++ : (data.username ?? ""),++ password: isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)++ ? undefined++ : (data.secret ?? ""),++ memberProvidedFields: basic+ };+ }- return bearerCredential(data);++ return {++ ...bearerCredential(data),++ value: bearer.length ? undefined : (data.secret ?? ""),++ memberProvidedFields: bearer++ };+};++// A field left at the sentinel is omitted so the stored value is kept. A bearer token can never be+// empty, so an empty one is omitted too, where an empty Basic half clears that half.+const buildHttpCredentialPatch = (data: TServiceForm): TAgentVaultCredentialUpdate => {++ const { bearer, basic, isMemberProvided } = memberFieldsOf(data);+ if (data.credentialType === AgentVaultCredentialType.Passthrough) {+ return { type: AgentVaultCredentialType.Passthrough };+ }+ const isSecretUntouched = data.secret === UNCHANGED_SECRET;++ if (data.credentialType === AgentVaultCredentialType.Basic) {+ return {+ type: AgentVaultCredentialType.Basic,- username: data.username === UNCHANGED_SECRET ? undefined : (data.username ?? ""),- password: isSecretUntouched ? undefined : (data.secret ?? "")++ username:++ isMemberProvided(AgentVaultVariableReferenceField.CredentialUsername) ||++ data.username === UNCHANGED_SECRET++ ? undefined++ : (data.username ?? ""),++ password:++ isMemberProvided(AgentVaultVariableReferenceField.CredentialValue) || isSecretUntouched++ ? undefined++ : (data.secret ?? ""),++ memberProvidedFields: basic+ };+ }+ return {+ type: AgentVaultCredentialType.Bearer,+ headerName: data.headerName || "Authorization",+ headerPrefix: data.headerPrefix ?? "",- value: isSecretUntouched || !data.secret ? undefined : data.secret++ value: bearer.length || isSecretUntouched || !data.secret ? undefined : data.secret,++ memberProvidedFields: bearer+ };+};++const buildMcpCredential = (data: TServiceForm) =>+ data.credentialType === AgentVaultCredentialType.OAuth+ ? {+ type: AgentVaultCredentialType.OAuth as const,+ authorizationId: newOAuthAuthorizationId(data) ?? ""+ }+ : bearerCredential(data);++// An OAuth credential has nothing to change without a new authorization made for the current URL, so+// it is left out and the stored tokens stay.+const buildMcpCredentialPatch = (data: TServiceForm): TAgentVaultCredentialUpdate | undefined => {+ if (data.credentialType !== AgentVaultCredentialType.OAuth) return buildHttpCredentialPatch(data);+ const authorizationId = newOAuthAuthorizationId(data);+ return authorizationId ? { type: AgentVaultCredentialType.OAuth, authorizationId } : undefined;+};++const withCredential = (credential: TAgentVaultCredentialUpdate | undefined) =>+ credential ? { credential } : {};++const buildCustomHeaders = (data: TServiceForm) =>+ data.customHeaders.map((header) => ({+ ...(header.id ? { id: header.id } : {}),+ name: header.name,+ prefix: header.prefix,+ ...(header.value === UNCHANGED_SECRET ? {} : { value: header.value })+ }));++const buildSubstitutions = (data: TServiceForm) =>+ data.substitutions.map((substitution) => ({+ ...(substitution.id ? { id: substitution.id } : {}),+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces,+ ...(substitution.value === UNCHANGED_SECRET ? {} : { value: substitution.value })+ }));++const buildHttpFields = (data: TServiceForm) => ({+ name: data.name,+ hostPattern: data.hosts.join(","),+ allowedMethods: isAllMethods(data.methods) ? null : data.methods,+ allowedPathPrefixes: data.pathPrefixes.length ? data.pathPrefixes : null,+ customHeaders: buildCustomHeaders(data),+ substitutions: buildSubstitutions(data)+});++const buildMcpFields = (data: TServiceForm) => ({+ name: data.name,+ serverUrl: data.serverUrl.trim(),+ transport: data.transport,+ customHeaders: buildCustomHeaders(data)+});++export const buildCreateServiceRequest = (+ accessBundleId: string,+ data: TServiceForm+): TCreateAgentVaultServiceDTO =>+ data.serviceType === AgentVaultServiceType.Mcp+ ? {+ accessBundleId,+ type: AgentVaultServiceType.Mcp,+ ...buildMcpFields(data),+ credential: buildMcpCredential(data)+ }+ : {+ accessBundleId,+ type: AgentVaultServiceType.Http,+ ...buildHttpFields(data),+ credential: buildHttpCredential(data)+ };++export const buildUpdateServiceRequest = (+ accessBundleId: string,+ serviceId: string,+ data: TServiceForm+): TUpdateAgentVaultServiceDTO =>+ data.serviceType === AgentVaultServiceType.Mcp+ ? {+ accessBundleId,+ serviceId,+ type: AgentVaultServiceType.Mcp,+ ...buildMcpFields(data),+ ...withCredential(buildMcpCredentialPatch(data))+ }+ : {+ accessBundleId,+ serviceId,+ type: AgentVaultServiceType.Http,+ ...buildHttpFields(data),+ credential: buildHttpCredentialPatch(data)+ };diff --cc frontend/src/components/agent-vault/service-sheet/serviceSchema.test.tsindex 40f3eddf5b,0000000000..b6231ad8acmode 100644,000000..100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts@@@ -1,320 -1,0 +1,322 @@@+import { describe, expect, it } from "vitest";++import {+ AgentVaultCredentialType,+ AgentVaultMcpTransport,+ AgentVaultOauthStatus,+ AgentVaultServiceType+} from "@app/hooks/api/agentVault";+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";++import {+ buildServiceSchema,+ isOAuthAuthorizationMissing,+ newOAuthAuthorizationId,+ OAUTH_CLIENT_VARIABLES_MESSAGE,+ oauthStatusLabel,+ serverUrlError,+ storedOAuthCredential,+ TServiceForm+} from "./serviceSchema";++const SERVER_URL = "https://mcp.linear.app/mcp";++const mcpForm = (overrides: Partial<TServiceForm> = {}): TServiceForm => ({+ serviceType: AgentVaultServiceType.Mcp,+ name: "linear-mcp",+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ hosts: [],+ hostDraft: "",+ pathDraft: "",+ credentialType: AgentVaultCredentialType.OAuth,+ headerName: "Authorization",+ headerPrefix: "Bearer",+ username: "",+ secret: "",+ oauthAuthorizationId: "",+ oauthAuthorizedUrl: "",+ oauthScopes: [],++ memberProvidedFields: [],+ methods: [],+ pathPrefixes: [],+ customHeaders: [],+ substitutions: [],+ ...overrides+});++const storedOAuthService = (serverUrl = SERVER_URL) =>+ ({+ id: "service-1",+ accessBundleId: "bundle-1",+ name: "linear-mcp",+ hostPattern: "mcp.linear.app",+ type: AgentVaultServiceType.Mcp,+ serverUrl,+ transport: AgentVaultMcpTransport.StreamableHttp,+ allowedMethods: null,+ allowedPathPrefixes: null,+ credential: {+ type: AgentVaultCredentialType.OAuth,+ status: AgentVaultOauthStatus.NeedsReauthorization,+ issuer: "https://mcp.linear.app",+ grantedScopes: ["read"],+ requiredScopes: [],+ expiresAt: null,+ authorizedAt: null,+ lastError: null+ },+ customHeaders: [],+ substitutions: [],+ createdAt: "2026-10-15T00:00:00.000Z",+ updatedAt: "2026-10-15T00:00:00.000Z"+ }) satisfies TAgentVaultService;++describe("serverUrlError", () => {+ it("rejects a query string", () => {+ expect(serverUrlError("https://mcp.example.com/mcp?token=abc")).toMatch(/query string/);+ expect(serverUrlError("https://*.example.com/mcp")).toMatch(/not a wildcard/);+ });++ it("accepts a plain server URL", () => {+ expect(serverUrlError(SERVER_URL)).toBeNull();+ });+});++describe("isOAuthAuthorizationMissing", () => {+ it("requires an authorization for a new OAuth service", () => {+ expect(isOAuthAuthorizationMissing(mcpForm())).toBe(true);+ });++ it("is satisfied by an authorization made for the current server URL", () => {+ expect(+ isOAuthAuthorizationMissing(+ mcpForm({ oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL })+ )+ ).toBe(false);+ });++ it("asks again once the server URL changes after authorizing", () => {+ expect(+ isOAuthAuthorizationMissing(+ mcpForm({+ serverUrl: "https://mcp.notion.com/mcp",+ oauthAuthorizationId: "auth-1",+ oauthAuthorizedUrl: SERVER_URL+ })+ )+ ).toBe(true);+ });++ it("keeps a stored authorization while the server URL is unchanged", () => {+ expect(isOAuthAuthorizationMissing(mcpForm(), storedOAuthService())).toBe(false);+ expect(+ isOAuthAuthorizationMissing(+ mcpForm({ serverUrl: "https://mcp.linear.app/v2" }),+ storedOAuthService()+ )+ ).toBe(true);+ });++ it("ignores bearer credentials", () => {+ expect(+ isOAuthAuthorizationMissing(mcpForm({ credentialType: AgentVaultCredentialType.Bearer }))+ ).toBe(false);+ });+});++describe("newOAuthAuthorizationId", () => {+ it("returns the authorization made for the current server URL", () => {+ expect(+ newOAuthAuthorizationId(+ mcpForm({+ serverUrl: ` ${SERVER_URL} `,+ oauthAuthorizationId: "auth-1",+ oauthAuthorizedUrl: SERVER_URL+ })+ )+ ).toBe("auth-1");+ });++ it("drops an authorization made for another server URL", () => {+ expect(+ newOAuthAuthorizationId(+ mcpForm({+ serverUrl: "https://mcp.notion.com/mcp",+ oauthAuthorizationId: "auth-1",+ oauthAuthorizedUrl: SERVER_URL+ })+ )+ ).toBeUndefined();+ });++ it("returns nothing before authorizing", () => {+ expect(newOAuthAuthorizationId(mcpForm())).toBeUndefined();+ });+});++describe("storedOAuthCredential", () => {+ it("returns the stored credential while the server URL matches", () => {+ const service = storedOAuthService();+ expect(storedOAuthCredential(service, ` ${SERVER_URL} `)).toBe(service.credential);+ });++ it("returns null once the server URL changes", () => {+ expect(storedOAuthCredential(storedOAuthService(), "https://mcp.linear.app/v2")).toBeNull();+ });++ it("returns null for a bearer service or no service", () => {+ const bearer = {+ ...storedOAuthService(),+ credential: {+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",- headerPrefix: "Bearer"++ headerPrefix: "Bearer",++ memberProvidedFields: []+ }+ } satisfies TAgentVaultService;+ expect(storedOAuthCredential(bearer, SERVER_URL)).toBeNull();+ expect(storedOAuthCredential(undefined, SERVER_URL)).toBeNull();+ });+});++describe("oauthStatusLabel", () => {+ const authorized = { oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL };++ it("labels a new authorization", () => {+ expect(oauthStatusLabel(mcpForm(authorized))).toBe("Authorized");+ expect(oauthStatusLabel(mcpForm(authorized), storedOAuthService())).toBe("Reauthorized");+ });++ it("falls back to the stored status, then to not authorized", () => {+ expect(oauthStatusLabel(mcpForm(), storedOAuthService())).toBe("Needs Reauthorization");+ expect(oauthStatusLabel(mcpForm())).toBe("Not authorized");+ });++ it("calls a working stored authorization Authorized, the word the card uses", () => {+ const service = storedOAuthService();+ const working = {+ ...service,+ credential: { ...service.credential, status: AgentVaultOauthStatus.Connected }+ } as TAgentVaultService;+ expect(oauthStatusLabel(mcpForm(), working)).toBe("Authorized");+ });+});++describe("buildServiceSchema with OAuth", () => {+ it("blocks an unauthorized OAuth service on the authorization field only", () => {+ const result = buildServiceSchema().safeParse(mcpForm());+ expect(result.success).toBe(false);+ const paths = result.error?.issues.map((issue) => issue.path.join(".")) ?? [];+ expect(paths).toEqual(["oauthAuthorizationId"]);+ });++ it("accepts an authorized OAuth service without a token", () => {+ const result = buildServiceSchema().safeParse(+ mcpForm({ oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL })+ );+ expect(result.success).toBe(true);+ });++ it("validates manual client credentials in the service form", () => {+ const result = buildServiceSchema(storedOAuthService()).safeParse(+ mcpForm({ oauthClientId: "x".repeat(2049), oauthClientSecret: "x".repeat(4097) })+ );+ expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual([+ "oauthClientId",+ "oauthClientSecret"+ ]);+ });++ it("refuses a variable reference in the client ID or secret, which are sent as typed", () => {+ const result = buildServiceSchema(storedOAuthService()).safeParse(+ mcpForm({+ oauthClientId: "{{GITHUB_CLIENT_ID}}",+ oauthClientSecret: "{{GITHUB_CLIENT_SECRET}}"+ })+ );+ expect(result.error?.issues.map(({ path, message }) => [path.join("."), message])).toEqual([+ ["oauthClientId", OAUTH_CLIENT_VARIABLES_MESSAGE],+ ["oauthClientSecret", OAUTH_CLIENT_VARIABLES_MESSAGE]+ ]);+ });++ it("refuses a client ID or secret the API would refuse, such as one with a pasted smart quote", () => {+ const result = buildServiceSchema(storedOAuthService()).safeParse(+ mcpForm({ oauthClientId: "\u201cclient-1\u201d", oauthClientSecret: "line\nbreak" })+ );+ expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual([+ "oauthClientId",+ "oauthClientSecret"+ ]);+ });++ it("ignores leftover client values once the service switches to a bearer token", () => {+ const result = buildServiceSchema(storedOAuthService()).safeParse(+ mcpForm({+ credentialType: AgentVaultCredentialType.Bearer,+ secret: "token",+ oauthClientId: "{{GITHUB_CLIENT_ID}}",+ oauthClientSecret: "\u201csecret\u201d"+ })+ );+ expect(result.success).toBe(true);+ });++ it("refuses to save an existing service whose new authorization expired, until it is reauthorized or kept", () => {+ const schema = buildServiceSchema(storedOAuthService());+ const expired = schema.safeParse(+ mcpForm({+ oauthAuthorizationRejection: "This authorization expired before the service was saved."+ })+ );+ expect(expired.error?.issues.map(({ path, message }) => [path.join("."), message])).toEqual([+ ["oauthAuthorizationId", "This authorization expired before the service was saved."]+ ]);++ expect(schema.safeParse(mcpForm({ oauthAuthorizationRejection: "" })).success).toBe(true);+ expect(+ schema.safeParse(+ mcpForm({+ oauthAuthorizationRejection: "This authorization expired before the service was saved.",+ oauthAuthorizationId: "auth-2",+ oauthAuthorizedUrl: SERVER_URL+ })+ ).success+ ).toBe(true);+ });++ it("ignores the bearer header fields and reserves Authorization for the token", () => {+ const authorized = { oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL };+ expect(+ buildServiceSchema().safeParse(mcpForm({ ...authorized, headerName: "Host" })).success+ ).toBe(true);+ expect(+ buildServiceSchema().safeParse(+ mcpForm({ ...authorized, headerName: "X Api Key", headerPrefix: "p".repeat(65) })+ ).success+ ).toBe(true);+ const bearer = buildServiceSchema().safeParse(+ mcpForm({+ credentialType: AgentVaultCredentialType.Bearer,+ secret: "token",+ headerName: "X Api Key",+ headerPrefix: "p".repeat(65)+ })+ );+ expect(bearer.error?.issues.map((issue) => issue.path.join("."))).toEqual([+ "headerName",+ "headerPrefix"+ ]);+ const clash = buildServiceSchema().safeParse(+ mcpForm({+ ...authorized,+ headerName: "X-Api-Key",+ customHeaders: [{ name: "Authorization", prefix: "", value: "v" }]+ })+ );+ expect(clash.error?.issues.map((issue) => issue.path.join("."))).toEqual([+ "customHeaders.0.name"+ ]);+ });+});diff --cc frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 1b8afa1e98,1a9d426e53..cf5873ff57--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@@ -6,15 -6,11 +6,17 @@@ import { variableReferenceError } fromimport {AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,+ AgentVaultOauthStatus,+ AgentVaultServiceType,- AgentVaultSubstitutionSurface+ AgentVaultSubstitutionSurface,+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField} from "@app/hooks/api/agentVault";-import { TAgentVaultService } from "@app/hooks/api/agentVault/types";+import {+ TAgentVaultOauthCredentialSummary,+ TAgentVaultService+} from "@app/hooks/api/agentVault/types";import { slugSchema } from "@app/lib/schemas";/**@@@ -30,6 -26,26 +32,28 @@@ export const displayHostPattern = (host.map((host) => host.trim().replace(/:443$/, "")).join(", ");+ /**+ * The form field that holds each member-provided field's admin value. credential-value is a bearer token or a basic+ * password, which share the form's `secret`.+ */+ export const FORM_FIELD_OF_CREDENTIAL_FIELD: Record<+ TAgentVaultMemberProvidedField,+ "secret" | "username"+ > = {+ [AgentVaultVariableReferenceField.CredentialValue]: "secret",+ [AgentVaultVariableReferenceField.CredentialUsername]: "username"+ };++ /** The member-provided fields a service had when the sheet opened. None stand behind a stored value. */+ export const storedMemberFields = (+ service?: TAgentVaultService | null+ ): TAgentVaultMemberProvidedField[] =>- service && service.credential.type !== AgentVaultCredentialType.Passthrough++ service &&++ (service.credential.type === AgentVaultCredentialType.Bearer ||++ service.credential.type === AgentVaultCredentialType.Basic)+ ? service.credential.memberProvidedFields+ : [];+export const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {[AgentVaultCredentialType.Bearer]: "Bearer",[AgentVaultCredentialType.Basic]: "Basic Auth",@@@ -267,21 -144,25 +292,28 @@@ export const buildServiceSchema =hostDraft: z.string(),pathDraft: z.string(),credentialType: z.nativeEnum(AgentVaultCredentialType),- headerName: z- .string()- .trim()- .max(128)- .regex(- /^[A-Za-z0-9!#$%&'*+.^_`|~-]*$/,- "A header name can't contain spaces or colons. Use letters, digits and dashes, as in X-API-Key."- )- .optional(),- headerPrefix: z.string().trim().max(64).optional(),+ // Checked in superRefine, only while Bearer is selected: switching away hides these fields but keeps them.+ headerName: z.string().trim().optional(),+ headerPrefix: z.string().trim().optional(),username: z.string().trim().max(256).optional(),secret: z.string().max(8192).optional(),+ oauthAuthorizationId: z.string(),+ // The server URL the authorization was made for, so editing the URL afterwards asks for a new one.+ oauthAuthorizedUrl: z.string(),+ oauthScopes: z.array(z.string()),+ // Why a new authorization was dropped (expired, or refused on save). While set, the stored login doesn't+ // count, so the save can't quietly keep the old one.+ oauthAuthorizationRejection: z.string().optional(),+ // Checked in the refine below, only while OAuth is selected: switching to Bearer keeps these values.+ oauthClientId: z.string().optional(),+ oauthClientSecret: z.string().optional(),+ // Each member sets these for themselves, so the form holds no value for them.+ memberProvidedFields: z.array(+ z.enum([+ AgentVaultVariableReferenceField.CredentialValue,+ AgentVaultVariableReferenceField.CredentialUsername+ ])+ ),methods: z.array(z.nativeEnum(AgentVaultHttpMethod)),pathPrefixes: z.array(z.string())@@@ -532,13 -339,19 +564,23 @@@if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, path, message });};+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) =>+ data.memberProvidedFields.includes(field);+ const isSecretMemberProvided = isMemberProvided(+ AgentVaultVariableReferenceField.CredentialValue+ );+ const isUsernameMemberProvided = isMemberProvided(+ AgentVaultVariableReferenceField.CredentialUsername+ );+- if (data.credentialType !== AgentVaultCredentialType.Passthrough && !isSecretMemberProvided) {+ if (+ data.credentialType !== AgentVaultCredentialType.Passthrough &&- data.credentialType !== AgentVaultCredentialType.OAuth++ data.credentialType !== AgentVaultCredentialType.OAuth &&++ !isSecretMemberProvided+ ) {addReferenceIssue(data.secret, ["secret"]);}- if (data.credentialType === AgentVaultCredentialType.Basic) {+ if (data.credentialType === AgentVaultCredentialType.Basic && !isUsernameMemberProvided) {addReferenceIssue(data.username, ["username"]);}data.customHeaders.forEach((header, index) =>diff --cc frontend/src/components/agent-vault/service-sheet/stepMeta.tsindex 1c30930786,de84f58948..a913c10e75--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts@@@ -15,23 -15,11 +15,23 @@@ type StepMeta =rightTip?: string;};+const VARIABLE_TIP =- "To use a variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place.";++ "To use a global variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place. For a member-provided field, each member sets their own value, and can use their personal variables there.";++const TEMPLATE_STEP: StepMeta = { step: ServiceStep.Template, name: "Template" };++const REVIEW_STEP: StepMeta = {+ step: ServiceStep.Review,+ name: "Review",+ shortDescription: "Confirm and add",+ title: "Review",+ subtitle: "Check everything before you save. You can change it later.",+ rightLabel: "REVIEW",+ rightDescription: "Review your settings before saving."+};+export const SERVICE_STEPS: StepMeta[] = [- {- step: ServiceStep.Template,- name: "Template"- },+ TEMPLATE_STEP,{step: ServiceStep.Details,name: "Details",diff --cc frontend/src/hooks/api/agentVault/mutations.tsxindex 26e7545014,00ebdd0842..70ee8cf3b5--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@@ -14,18 -15,15 +15,19 @@@ importTAgentVaultGrantedMember,TAgentVaultMemberWriteResult,TAgentVaultMintedSession,+ TAgentVaultOauthAuthorization,+ TAgentVaultPersonalValues,TAgentVaultProxy,TAgentVaultProxySettingsDTO,+ TAgentVaultProxyWithToken,TAgentVaultService,- TAgentVaultSessionLogSettings,+ TAgentVaultSessionLogSettingsState,TAgentVaultVariable,TAgentVaultWrittenMember,+ TCompleteAgentVaultOauthAuthorizationDTO,TCreateAgentVaultAccessBundleDTO,+ TCreateAgentVaultOauthAuthorizationDTO,+ TCreateAgentVaultOauthAuthorizationResponse,TCreateAgentVaultServiceDTO,TCreateAgentVaultSessionDTO,TCreateAgentVaultVariableDTO,@@@ -463,31 -465,55 +473,84 @@@ export const useRevealAgentVaultVariabl}});+export const useCreateAgentVaultOauthAuthorization = () =>+ useMutation({+ // The Authorize card shows every failure in place, discovery and registration ones naming the server.+ meta: { skipErrorToast: true },+ mutationFn: async (params: TCreateAgentVaultOauthAuthorizationDTO) => {+ const { data } = await apiRequest.post<TCreateAgentVaultOauthAuthorizationResponse>(+ "/api/v1/agent-vault/oauth/authorizations",+ params+ );+ return data;+ }+ });++export const useCompleteAgentVaultOauthAuthorization = () =>+ useMutation({+ // The callback page shows every outcome itself.+ meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError, ApiErrorTypes.NotFoundError] },+ mutationFn: async ({+ authorizationId,+ ...params+ }: TCompleteAgentVaultOauthAuthorizationDTO) => {+ const { data } = await apiRequest.post<{ authorization: TAgentVaultOauthAuthorization }>(+ `/api/v1/agent-vault/oauth/authorizations/${encodeURIComponent(authorizationId)}/complete`,+ params+ );+ return data.authorization;+ }+ });+++ // The status shows on the bundle read and the bundle list, and Used By on personal variables follows the references.+ const invalidatePersonalValues = (+ queryClient: ReturnType<typeof useQueryClient>,+ orgId: string,+ accessBundleId: string+ ) =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundle(orgId, accessBundleId) }),+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(orgId) }),+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(orgId) })+ ]);++ export const useSetAgentVaultPersonalValues = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({+ accessBundleId,+ serviceId,+ ...params+ }: TSetAgentVaultPersonalValuesDTO) => {+ const { data } = await apiRequest.patch<{ personalValues: TAgentVaultPersonalValues }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}/personal-values`,+ params+ );+ return data.personalValues;+ },+ onSuccess: (_, { accessBundleId }) =>+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId),+ // The service changed under the dialog, so its copy is stale: reload it before the member saves again.+ onError: (error, { accessBundleId }) => {+ if (axios.isAxiosError(error) && error.response?.status === 409) {+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId).catch(() => undefined);+ }+ }+ });+ };++ export const useDeleteAgentVaultPersonalValues = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ accessBundleId, serviceId }: TDeleteAgentVaultPersonalValuesDTO) => {+ const { data } = await apiRequest.delete<{ personalValues: TAgentVaultPersonalValues }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}/personal-values`+ );+ return data.personalValues;+ },+ onSuccess: (_, { accessBundleId }) =>+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId)+ });+ };diff --cc frontend/src/hooks/api/agentVault/queries.tsxindex f3bea5018c,61afbfcae8..e738de6d42--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@@ -6,7 -6,7 +6,11 @@@ import { apiRequest } from "@app/configimport { useOrganization } from "@app/context";import { VARIABLE_KEY_MAX_LENGTH, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";- import { AgentVaultMemberType, AgentVaultOauthAuthorizationStatus } from "./enums";-import { AgentVaultMemberType, AgentVaultVariableScope } from "./enums";++import {++ AgentVaultMemberType,++ AgentVaultOauthAuthorizationStatus,++ AgentVaultVariableScope++} from "./enums";import {createSessionLogChunkCache,decryptSessionLogPage,diff --cc frontend/src/hooks/api/agentVault/types.tsindex 62478978b5,e515df2d6c..d8fe98b73f--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@@ -1,62 -1,53 +1,77 @@@import {AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,AgentVaultMemberType,+ AgentVaultOauthAuthorizationStatus,+ AgentVaultOauthStatus,+ AgentVaultServiceType,AgentVaultSessionLogDecision,+ AgentVaultSessionLogStorageType,AgentVaultSessionScope,AgentVaultSessionStatus,AgentVaultSubstitutionSurface,AgentVaultTrafficPolicy,- AgentVaultVariableReferenceField+ AgentVaultVariableReferenceField,+ AgentVaultVariableScope} from "./enums";+ /** A field an admin can leave to each member: a bearer token or basic password, or a basic username. */+ export type TAgentVaultMemberProvidedField =+ | AgentVaultVariableReferenceField.CredentialValue+ | AgentVaultVariableReferenceField.CredentialUsername;++export type TAgentVaultOauthCredentialSummary = {+ type: AgentVaultCredentialType.OAuth;+ status: AgentVaultOauthStatus;+ issuer: string;+ grantedScopes: string[];+ requiredScopes: string[];+ // Left out for Agent Vault members.+ expiresAt?: string | null;+ authorizedAt?: string | null;+ lastError?: string | null;+};+- export type TAgentVaultCredentialSummary =- | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }- | { type: AgentVaultCredentialType.Basic }- | { type: AgentVaultCredentialType.Passthrough }- | TAgentVaultOauthCredentialSummary;+ export type TAgentVaultBearerMemberField = AgentVaultVariableReferenceField.CredentialValue;+ export type TAgentVaultBasicMemberField = TAgentVaultMemberProvidedField;- export type TAgentVaultCredentialInput =+ export type TAgentVaultCredentialSummary =| {type: AgentVaultCredentialType.Bearer;- headerName?: string;- headerPrefix?: string;- value: string;+ headerName: string;+ headerPrefix: string;+ memberProvidedFields: TAgentVaultBearerMemberField[];}- | { type: AgentVaultCredentialType.Basic; username: string; password: string }- | { type: AgentVaultCredentialType.Passthrough };+ | { type: AgentVaultCredentialType.Basic; memberProvidedFields: TAgentVaultBasicMemberField[] }- | { type: AgentVaultCredentialType.Passthrough };++ | { type: AgentVaultCredentialType.Passthrough }++ | TAgentVaultOauthCredentialSummary;++export type TAgentVaultOauthCredentialInput = {+ type: AgentVaultCredentialType.OAuth;+ authorizationId: string;+};- export type TAgentVaultCredentialUpdate =+ // A member-provided field is sent without a value: each member sets their own.+ export type TAgentVaultCredentialInput =| {type: AgentVaultCredentialType.Bearer;headerName?: string;headerPrefix?: string;value?: string;+ memberProvidedFields?: TAgentVaultBearerMemberField[];}- | { type: AgentVaultCredentialType.Basic; username?: string; password?: string }- | { type: AgentVaultCredentialType.Passthrough }+ | {+ type: AgentVaultCredentialType.Basic;+ username?: string;+ password?: string;+ memberProvidedFields?: TAgentVaultBasicMemberField[];+ }+ | { type: AgentVaultCredentialType.Passthrough };+-export type TAgentVaultCredentialUpdate = TAgentVaultCredentialInput;++export type TAgentVaultCredentialUpdate =++ | TAgentVaultCredentialInput+ | TAgentVaultOauthCredentialInput;export type TAgentVaultCustomHeaderSummary = { id: string; name: string; prefix: string };diff --cc frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsxindex 23d4fec525,2e9b89c3d4..70bdf16dc8--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx@@@ -109,16 -99,14 +114,23 @@@ const HostsCell = ({ hostPattern }: { h);};+const TargetCell = ({ service }: { service: TAgentVaultService }) =>+ service.type === AgentVaultServiceType.Mcp ? (+ <span className="block max-w-72 truncate text-sm" title={service.serverUrl}>+ {service.serverUrl.replace(/^https:\/\//i, "")}+ </span>+ ) : (+ <HostsCell hostPattern={service.hostPattern} />+ );+- export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdit }: Props) => {+ export const ServicesCard = ({+ accessBundleId,+ services,+ canManage,+ onAdd,+ onEdit,+ onSetUp+ }: Props) => {const [search, setSearch] = useState("");const [serviceToDelete, setServiceToDelete] = useState<TAgentVaultService | null>(null);const deleteService = useDeleteAgentVaultService();diff --cc frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsxindex 7d389fe0fd,aa6431d8eb..72480283f0--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx@@@ -4,10 -4,9 +4,10 @@@ importArrowRightIcon,CircleHelpIcon,CircleXIcon,- KeyRoundIcon,+ KeyIcon,type LucideIcon,PlusIcon,+ ServerIcon,ShieldBanIcon} from "lucide-react";import { twMerge } from "tailwind-merge";diff --cc frontend/src/pages/agent-vault/agent-vault-docs-urls.tsindex 535f814a00,e1182d205d..e25e18d86f--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts@@@ -5,6 -5,7 +5,7 @@@ export const AgentVaultDocsUrls =quickstart: `${AGENT_VAULT_DOCS_BASE_URL}/quickstart`,accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,- memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/services#member-provided-values`,++ memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/http-apis#member-provided-values`,variables: `${AGENT_VAULT_DOCS_BASE_URL}/variables`,sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`,