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
initial implementation
Sheen Capadngan748266a0431f
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex fa96f8d28a..e970d75192 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -2707,6 +2707,7 @@ describe("Agent Vault V1 Router", async () => {} as never,licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,resourceAuthMethodService: {} as never,+ agentVaultOauthService: {} as never,...overrides});@@ -2838,7 +2839,8 @@ describe("Agent Vault V1 Router", async () => {Promise.resolve({ decryptor: () => Buffer.from(JSON.stringify({ value: "unsealed" })) })} as never,licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,- resourceAuthMethodService: {} as never+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {} as never});const resolved = await resolver.resolveSession({@@ -3004,7 +3006,8 @@ describe("Agent Vault V1 Router", async () => {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,- resourceAuthMethodService: {} as never+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {} as never});const resolve = () =>resolver.resolveSession({@@ -3743,7 +3746,8 @@ describe("Agent Vault V1 Router", async () => {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,- resourceAuthMethodService: {} as never+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {} as never});const resolve = () =>resolver.resolveSession({@@ -3842,7 +3846,8 @@ describe("Agent Vault V1 Router", async () => {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,- resourceAuthMethodService: {} as never+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {} as never});const resolve = () =>resolver.resolveSession({diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 0d0e5caa84..c76e36210d 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -122,6 +122,7 @@"netmask": "^2.0.2","node-forge": "^1.4.0","nodemailer": "^8.0.9",+ "oauth4webapi": "3.8.8","oci-common": "^2.108.0","oci-identity": "^2.108.0","oci-keymanagement": "^2.108.0",@@ -20367,9 +20368,9 @@"license": "MIT"},"node_modules/oauth4webapi": {- "version": "3.8.3",- "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.3.tgz",- "integrity": "sha512-pQ5BsX3QRTgnt5HxgHwgunIRaDXBdkT23tf8dfzmtTIL2LTpdmxgbpbBm0VgFWAIDlezQvQCTgnVIUmHupXHxw==",+ "version": "3.8.8",+ "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",+ "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==","license": "MIT","funding": {"url": "https://github.com/sponsors/panva"diff --git a/backend/package.json b/backend/package.jsonindex a92fdadfd5..1cfb60a231 100644--- a/backend/package.json+++ b/backend/package.json@@ -264,6 +264,7 @@"netmask": "^2.0.2","node-forge": "^1.4.0","nodemailer": "^8.0.9",+ "oauth4webapi": "3.8.8","oci-common": "^2.108.0","oci-identity": "^2.108.0","oci-keymanagement": "^2.108.0",diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 6f8564ca03..a6afac37fa 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -8,6 +8,7 @@ import { TAccessApprovalRequestServiceFactory } from "@app/ee/services/access-apimport { 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 { 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";@@ -385,6 +386,7 @@ declare module "fastify" {secretScanningV2ProjectResolver: TSecretScanningV2ProjectResolverFactory;agentVaultProjectResolver: TAgentVaultProjectResolverFactory;agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;+ agentVaultOauth: TAgentVaultOauthServiceFactory;agentVaultProxy: TAgentVaultProxyServiceFactory;agentVaultSession: TAgentVaultSessionServiceFactory;agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;diff --git a/backend/src/db/migrations/20261015120000_agent-vault-mcp-services.ts b/backend/src/db/migrations/20261015120000_agent-vault-mcp-services.tsnew file mode 100644index 0000000000..c165e947ab--- /dev/null+++ b/backend/src/db/migrations/20261015120000_agent-vault-mcp-services.ts@@ -0,0 +1,49 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++const TYPE_CHECK = "agent_vault_services_type_check";+const CREDENTIAL_TYPE_CHECK = "agent_vault_services_credential_type_check";++export async function up(knex: Knex): Promise<void> {+ const hasType = await knex.schema.hasColumn(TableName.AgentVaultService, "type");+ const hasConfig = await knex.schema.hasColumn(TableName.AgentVaultService, "config");++ if (!hasType || !hasConfig) {+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {+ if (!hasType) t.string("type", 32).notNullable().defaultTo("http");+ if (!hasConfig) t.jsonb("config").nullable();+ });+ }++ if (!hasType) {+ await knex.raw(+ `ALTER TABLE "${TableName.AgentVaultService}" ADD CONSTRAINT "${TYPE_CHECK}" CHECK ("type" IN ('http', 'mcp'))`+ );+ }++ await knex.raw(`ALTER TABLE "${TableName.AgentVaultService}" DROP CONSTRAINT IF EXISTS "${CREDENTIAL_TYPE_CHECK}"`);+ await knex.raw(+ `ALTER TABLE "${TableName.AgentVaultService}" ADD CONSTRAINT "${CREDENTIAL_TYPE_CHECK}" CHECK ("credentialType" IN ('bearer', 'basic', 'passthrough', 'oauth'))`+ );+}++export async function down(knex: Knex): Promise<void> {+ // Restoring the old check fails while an OAuth service exists, so rolling back requires deleting those first.+ await knex.raw(`ALTER TABLE "${TableName.AgentVaultService}" DROP CONSTRAINT IF EXISTS "${CREDENTIAL_TYPE_CHECK}"`);+ await knex.raw(+ `ALTER TABLE "${TableName.AgentVaultService}" ADD CONSTRAINT "${CREDENTIAL_TYPE_CHECK}" CHECK ("credentialType" IN ('bearer', 'basic', 'passthrough'))`+ );++ await knex.raw(`ALTER TABLE "${TableName.AgentVaultService}" DROP CONSTRAINT IF EXISTS "${TYPE_CHECK}"`);++ const hasType = await knex.schema.hasColumn(TableName.AgentVaultService, "type");+ const hasConfig = await knex.schema.hasColumn(TableName.AgentVaultService, "config");++ if (hasType || hasConfig) {+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {+ if (hasType) t.dropColumn("type");+ if (hasConfig) t.dropColumn("config");+ });+ }+}diff --git a/backend/src/db/schemas/agent-vault-services.ts b/backend/src/db/schemas/agent-vault-services.tsindex cf9dc6c62a..68257b9616 100644--- a/backend/src/db/schemas/agent-vault-services.ts+++ b/backend/src/db/schemas/agent-vault-services.ts@@ -20,7 +20,9 @@ export const AgentVaultServicesSchema = z.object({createdAt: z.date(),updatedAt: z.date(),allowedMethods: z.string().array().nullable().optional(),- allowedPathPrefixes: z.string().array().nullable().optional()+ allowedPathPrefixes: z.string().array().nullable().optional(),+ type: z.string().default("http"),+ config: z.unknown().nullable().optional()});export type TAgentVaultServices = z.infer<typeof AgentVaultServicesSchema>;diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex 580a8bfbf3..d83db32005 100644--- 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@@ -6,13 +6,14 @@ import {AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,AGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";-import { AgentVaultCredentialType } from "@app/ee/services/agent-vault/agent-vault-enums";+import { AgentVaultCredentialType, AgentVaultServiceType } from "@app/ee/services/agent-vault/agent-vault-enums";import { parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";import { readLimit, secretsLimit, writeLimit } from "@app/server/config/rateLimiter";import { addNoCacheHeaders } from "@app/server/lib/caching";+import { openApiHidden } from "@app/server/lib/schemas";import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";@@ -24,19 +25,19 @@ import {AgentVaultAllowedMethodsSchema,AgentVaultAllowedPathPrefixesSchema,AgentVaultCreatedMemberSchema,- AgentVaultCredentialInputSchema,+ AgentVaultCreateServiceBodySchema,AgentVaultCredentialUpdateSchema,- AgentVaultCustomHeadersInputSchema,AgentVaultCustomHeadersUpdateSchema,AgentVaultHostPatternSchema,agentVaultListQuery,+ AgentVaultMcpTransportSchema,AgentVaultMemberIdsSchema,AgentVaultMemberRevokeIdsSchema,AgentVaultMemberSchema,AgentVaultNameSchema,AgentVaultProductMemberSchema,+ AgentVaultServerUrlSchema,AgentVaultServiceSchema,- AgentVaultSubstitutionsInputSchema,AgentVaultSubstitutionsUpdateSchema,AgentVaultVariableKeySchema,AgentVaultVariableSchema,@@ -297,15 +298,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProparams: z.object({accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)}),- body: z.object({- name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),- hostPattern: AgentVaultHostPatternSchema,- allowedMethods: AgentVaultAllowedMethodsSchema.optional(),- allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),- credential: AgentVaultCredentialInputSchema,- customHeaders: AgentVaultCustomHeadersInputSchema.optional(),- substitutions: AgentVaultSubstitutionsInputSchema.optional()- }),+ body: AgentVaultCreateServiceBodySchema,response: {200: z.object({ service: AgentVaultServiceSchema })}@@ -330,12 +323,19 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProaccessBundleName,serviceId: service.id,name: service.name,+ serviceType: service.type,+ serverUrl: service.config.serverUrl,+ transport: service.config.transport,hostPattern: service.hostPattern,credentialType: service.credential.type,headerName:service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerName : undefined,headerPrefix:service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerPrefix : undefined,+ 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,customHeaderNames: service.customHeaders.map((header) => header.name),@@ -345,11 +345,33 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});+ if (service.credential.type === AgentVaultCredentialType.OAuth) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE,+ metadata: {+ accessBundleId: req.params.accessBundleId,+ accessBundleName,+ serviceId: service.id,+ name: service.name,+ serverUrl: service.config.serverUrl,+ oauthIssuer: service.credential.issuer,+ oauthScopes: service.credential.grantedScopes,+ reauthorization: false+ }+ }+ });+ }+emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultServiceCreated,properties: {accessBundleId: req.params.accessBundleId,serviceId: service.id,+ serviceType: service.type,credentialType: service.credential.type,hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length,allowedMethodCount: service.allowedMethods?.length ?? 0,@@ -379,8 +401,12 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}),body: z.object({+ // Accepted only so the refusal is a readable 400 rather than a silently dropped field.+ type: z.nativeEnum(AgentVaultServiceType).optional().describe(openApiHidden()),name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.SERVICE.name),hostPattern: AgentVaultHostPatternSchema.optional(),+ serverUrl: AgentVaultServerUrlSchema.optional(),+ transport: AgentVaultMcpTransportSchema.optional(),allowedMethods: AgentVaultAllowedMethodsSchema.optional(),allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),credential: AgentVaultCredentialUpdateSchema.optional(),@@ -389,7 +415,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}).refine((body) => Object.values(body).some((value) => value !== undefined),- "Provide at least one of 'name', 'hostPattern', 'allowedMethods', 'allowedPathPrefixes', 'credential', 'customHeaders' or 'substitutions' to update"+ "Provide at least one of 'name', 'hostPattern', 'serverUrl', 'transport', 'allowedMethods', 'allowedPathPrefixes', 'credential', 'customHeaders' or 'substitutions' to update"),response: {200: z.object({ service: AgentVaultServiceSchema })@@ -404,6 +430,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProserviceId: req.params.serviceId,...req.body});+ const isOauthAuthorized = req.body.credential?.type === AgentVaultCredentialType.OAuth;await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -417,7 +444,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProaccessBundleName,serviceId: service.id,name: req.body.name,- hostPattern: req.body.hostPattern,+ serviceType: service.type,+ serverUrl: req.body.serverUrl,+ transport: req.body.transport,+ // Derived from the server URL for an MCP service, so it is reported whenever that changed.+ hostPattern: req.body.hostPattern ?? (req.body.serverUrl ? service.hostPattern : undefined),credentialType: req.body.credential?.type,headerName:req.body.credential?.type === AgentVaultCredentialType.Bearer@@ -427,6 +458,14 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProreq.body.credential?.type === AgentVaultCredentialType.Bearer? req.body.credential.headerPrefix: undefined,+ oauthIssuer:+ isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth+ ? service.credential.issuer+ : undefined,+ oauthScopes:+ isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth+ ? service.credential.grantedScopes+ : undefined,allowedMethods: req.body.allowedMethods,allowedPathPrefixes: req.body.allowedPathPrefixes,customHeaderNames: req.body.customHeaders?.map((header) => header.name),@@ -448,11 +487,33 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});+ if (isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE,+ metadata: {+ accessBundleId: req.params.accessBundleId,+ accessBundleName,+ serviceId: service.id,+ name: service.name,+ serverUrl: service.config.serverUrl,+ oauthIssuer: service.credential.issuer,+ oauthScopes: service.credential.grantedScopes,+ reauthorization: true+ }+ }+ });+ }+emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultServiceUpdated,properties: {accessBundleId: req.params.accessBundleId,serviceId: service.id,+ serviceType: service.type,credentialType: service.credential.type,hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length,allowedMethodCount: service.allowedMethods?.length ?? 0,diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.tsnew file mode 100644index 0000000000..cd26810e36--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.ts@@ -0,0 +1,139 @@+import { z } from "zod";++import { AgentVaultOauthAuthorizationStatus } from "@app/ee/services/agent-vault/agent-vault-enums";+import { OAUTH_CLIENT_CREDENTIAL_PATTERN } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns";+import { AGENT_VAULT } from "@app/lib/api-docs";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++import { actorContext } from "./agent-vault-router-fns";+import { AgentVaultServerUrlSchema } from "./agent-vault-schemas";++const AuthorizationViewSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.OAUTH.authorizationId),+ status: z.nativeEnum(AgentVaultOauthAuthorizationStatus).describe(AGENT_VAULT.OAUTH.status),+ error: z.string().nullable().describe(AGENT_VAULT.OAUTH.error),+ scopes: z.string().array().describe(AGENT_VAULT.OAUTH.scopes)+});++const printable = (max: number) =>+ z+ .string()+ .max(max)+ .regex(OAUTH_CLIENT_CREDENTIAL_PATTERN, "Use printable ASCII characters without line breaks or accents");++// JWT only: an authorization ends in a browser redirect, so only a signed-in user can start or finish one.+export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/authorizations",+ config: { rateLimit: writeLimit },+ schema: {+ hide: true,+ operationId: "createAgentVaultOauthAuthorization",+ description:+ "Start an OAuth authorization for an MCP service: discovers the server's authorization server, registers a client, and returns the URL to sign in at.",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ body: z.object({+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.OAUTH.accessBundleId),+ serverUrl: AgentVaultServerUrlSchema.describe(AGENT_VAULT.OAUTH.serverUrl),+ serviceId: z.string().uuid().optional().describe(AGENT_VAULT.OAUTH.serviceId),+ clientId: z+ .string()+ .trim()+ .min(1)+ .max(512)+ .pipe(printable(512))+ .optional()+ .describe(AGENT_VAULT.OAUTH.clientId),+ clientSecret: z+ .string()+ .min(1)+ .max(1024)+ .pipe(printable(1024))+ .optional()+ .describe(AGENT_VAULT.OAUTH.clientSecret)+ }),+ response: {+ 200: z.object({+ registrationRequired: z.boolean().describe(AGENT_VAULT.OAUTH.registrationRequired),+ redirectUri: z.string().describe(AGENT_VAULT.OAUTH.redirectUri),+ registrationError: z.string().nullable().describe(AGENT_VAULT.OAUTH.registrationError),+ authorization: z+ .object({+ id: z.string().uuid().describe(AGENT_VAULT.OAUTH.authorizationId),+ status: z.nativeEnum(AgentVaultOauthAuthorizationStatus).describe(AGENT_VAULT.OAUTH.status),+ authorizeUrl: z.string().describe(AGENT_VAULT.OAUTH.authorizeUrl),+ scopes: z.string().array().describe(AGENT_VAULT.OAUTH.scopes)+ })+ .nullable()+ .describe(AGENT_VAULT.OAUTH.authorization)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) =>+ server.services.agentVaultOauth.createAuthorization({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ ...req.body+ })+ });++ // An action sub-resource rather than a PATCH of the status: completing exchanges a one-time code with a third+ // party, and the callback page only knows what the redirect carried.+ server.route({+ method: "POST",+ url: "/authorizations/:authorizationId/complete",+ config: { rateLimit: writeLimit },+ schema: {+ hide: true,+ operationId: "completeAgentVaultOauthAuthorization",+ description:+ "Finish an OAuth authorization with what the authorization server's redirect carried. An exchange failure returns 200 with status `failed`, so the callback page can show why.",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ params: z.object({ authorizationId: z.string().uuid().describe(AGENT_VAULT.OAUTH.authorizationId) }),+ body: z.object({+ state: z.string().min(1).max(256).describe(AGENT_VAULT.OAUTH.state),+ code: z.string().min(1).max(4096).optional().describe(AGENT_VAULT.OAUTH.code),+ iss: z.string().max(2048).optional().describe(AGENT_VAULT.OAUTH.iss),+ // Provider text, accepted as sent so a long or multi-line reason still fails the authorization; the+ // service normalizes it before storing it.+ error: z.string().max(1024).optional().describe(AGENT_VAULT.OAUTH.callbackError),+ errorDescription: z.string().max(4096).optional().describe(AGENT_VAULT.OAUTH.callbackErrorDescription)+ }),+ response: { 200: z.object({ authorization: AuthorizationViewSchema.describe(AGENT_VAULT.OAUTH.authorization) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) =>+ server.services.agentVaultOauth.completeAuthorization({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ authorizationId: req.params.authorizationId,+ ...req.body+ })+ });++ server.route({+ method: "GET",+ url: "/authorizations/:authorizationId",+ config: { rateLimit: readLimit },+ schema: {+ hide: true,+ operationId: "getAgentVaultOauthAuthorization",+ description: "Get an OAuth authorization's status. Tokens are never returned.",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ params: z.object({ authorizationId: z.string().uuid().describe(AGENT_VAULT.OAUTH.authorizationId) }),+ response: { 200: z.object({ authorization: AuthorizationViewSchema.describe(AGENT_VAULT.OAUTH.authorization) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) =>+ server.services.agentVaultOauth.getAuthorization({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ authorizationId: req.params.authorizationId+ })+ });+};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex 80c17f6e36..9207b803bb 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts@@ -1,6 +1,15 @@+import RE2 from "re2";import { z } from "zod";-import { AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";+import {+ AgentVaultOauthStatus,+ AgentVaultServiceType,+ AgentVaultTrafficPolicy+} from "@app/ee/services/agent-vault/agent-vault-enums";+import {+ MAX_OAUTH_SCOPE_LENGTH,+ OAUTH_SCOPE_TOKEN_PATTERN+} from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns";import { AGENT_VAULT_SESSION_TOKEN_PREFIX } from "@app/ee/services/agent-vault-session/agent-vault-session-fns";import {AgentVaultSessionLogChunkCreateResponseSchema,@@ -12,6 +21,7 @@ import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";import { logger } from "@app/lib/logger";import {+ agentVaultCredentialRefreshLimit,agentVaultHeartbeatLimit,agentVaultResolveLimit,agentVaultSessionLogChunkLimit,@@ -21,6 +31,8 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { ActorType, AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";+import { 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),@@ -29,6 +41,30 @@ const ProxyConfigSchema = z.object({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("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("oauth").optional().describe(AGENT_VAULT.CREDENTIAL_REFRESH.source),+ expiresAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthExpiresAt)+ })+ .describe(JSON.stringify({ title: "Bearer" }));+export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -135,17 +171,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvioperationId: "resolveAgentVaultSession",description: "Resolve a session into the services and credentials the proxy should attach",tags: [ApiDocsTags.AgentVaultProxies],- headers: z- .object({- [SESSION_HEADER]: z- .string()- .trim()- .min(1)- .max(128)- .startsWith(AGENT_VAULT_SESSION_TOKEN_PREFIX)- .describe(AGENT_VAULT.PROXY.sessionToken)- })- .passthrough(),+ headers: SessionHeaderSchema,// Nullish, not optional: proxies predating session logs send no body, which arrives as null. They can't// record, so the handler counts them as already holding the key and never sends it.body: z@@ -162,18 +188,12 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviid: z.string().uuid(),name: z.string(),accessBundleName: z.string(),+ type: z.nativeEnum(AgentVaultServiceType).describe(AGENT_VAULT.SERVICE.type),hostPattern: z.string(),allowedMethods: z.string().array().nullable(),allowedPathPrefixes: z.string().array().nullable(),credential: z.discriminatedUnion("type", [- z- .object({- type: z.literal("bearer"),- headerName: z.string(),- headerPrefix: z.string(),- value: z.string()- })- .describe(JSON.stringify({ title: "Bearer" })),+ ResolvedBearerCredentialSchema,z.object({ type: z.literal("basic"), username: z.string(), password: z.string() }).describe(JSON.stringify({ title: "Basic Auth" })),@@ -204,6 +224,59 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi}});+ // An action sub-resource by choice: kept apart from resolve so it has its own rate limit.+ server.route({+ method: "POST",+ url: "/services/:serviceId/credential-refresh",+ config: { rateLimit: agentVaultCredentialRefreshLimit },+ schema: {+ hide: true,+ operationId: "refreshAgentVaultServiceCredential",+ description:+ "After the upstream rejected an OAuth token, return a fresh one. If the rejected token is no longer the current one, the current one is returned without calling the provider. A 409 means the service's host pattern no longer matches `hostPattern`, and no token is returned.",+ tags: [ApiDocsTags.AgentVaultProxies],+ headers: SessionHeaderSchema,+ params: z.object({ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId) }),+ body: z.object({+ hostPattern: AgentVaultHostPatternSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.hostPattern),+ rejectedTokenHash: z+ .string()+ .length(64)+ .regex(new RE2(/^[0-9a-fA-F]{64}$/), "Must be the hex sha256 of the rejected access token")+ .describe(AGENT_VAULT.CREDENTIAL_REFRESH.rejectedTokenHash),+ requiredScopes: z+ .string()+ .min(1)+ .max(MAX_OAUTH_SCOPE_LENGTH)+ .regex(+ OAUTH_SCOPE_TOKEN_PATTERN,+ "Each scope must be an OAuth scope token: printable ASCII with no spaces, quotes or backslashes"+ )+ .array()+ .max(50)+ .optional()+ .describe(AGENT_VAULT.CREDENTIAL_REFRESH.requiredScopes)+ }),+ response: {+ 200: z.object({+ credential: ResolvedBearerCredentialSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.credential),+ status: z.nativeEnum(AgentVaultOauthStatus).describe(AGENT_VAULT.SERVICE.oauthStatus)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),+ handler: async (req) =>+ server.services.agentVaultProxy.refreshCredential({+ proxyId: req.permission.id,+ orgId: req.permission.orgId,+ sessionToken: req.headers[SESSION_HEADER],+ serviceId: req.params.serviceId,+ hostPattern: req.body.hostPattern,+ rejectedTokenHash: req.body.rejectedTokenHash,+ requiredScopes: req.body.requiredScopes+ })+ });+server.route({method: "POST",url: "/sessions/:sessionId/logs/chunks",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex c4870898e0..0d9944fcba 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -8,12 +8,16 @@ import {import {AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,AgentVaultMemberType,+ AgentVaultOauthStatus,+ AgentVaultServiceType,AgentVaultSubstitutionSurface,AgentVaultVariableReferenceField} 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";+import { agentVaultMcpServerUrlSchema } from "@app/ee/services/agent-vault/agent-vault-service-types";import {acceptsVariableReferences,addDuplicateCustomHeaderNameIssues,@@ -35,7 +39,7 @@ import {} from "@app/ee/services/agent-vault/agent-vault-variable-fns";import { AGENT_VAULT_MAX_GRANTEES } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";import { AGENT_VAULT } from "@app/lib/api-docs";-import { slugSchema } from "@app/server/lib/schemas";+import { openApiHidden, slugSchema } from "@app/server/lib/schemas";export const AgentVaultNameSchema = slugSchema({ max: 64, field: "Name" });@@ -83,7 +87,13 @@ export const AgentVaultCredentialInputSchema = z.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),+ authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.authorizationId)+ })+ .describe(JSON.stringify({ title: "OAuth" }))]).superRefine(basicHalvesAreNotBothEmpty);@@ -119,7 +129,13 @@ export const AgentVaultCredentialUpdateSchema = z.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),+ authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.updateAuthorizationId)+ })+ .describe(JSON.stringify({ title: "OAuth" }))]).superRefine(basicHalvesAreNotBothEmpty);@@ -134,7 +150,26 @@ export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [z.object({ type: z.literal(AgentVaultCredentialType.Basic) }).describe(JSON.stringify({ title: "Basic Auth" })),z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })- .describe(JSON.stringify({ title: "Pass-through" }))+ .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().describe(AGENT_VAULT.SERVICE.oauthExpiresAt),+ authorizedBy: z+ .object({+ userId: z.string().uuid().describe(AGENT_VAULT.SERVICE.oauthAuthorizedByUserId),+ username: z.string().describe(AGENT_VAULT.SERVICE.oauthAuthorizedByUsername)+ })+ .nullable()+ .describe(AGENT_VAULT.SERVICE.oauthAuthorizedBy),+ authorizedAt: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthAuthorizedAt),+ lastError: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthLastError)+ })+ .describe(JSON.stringify({ title: "OAuth" }))]);export const AgentVaultAllowedMethodsSchema = z@@ -154,6 +189,12 @@ export const AgentVaultCustomHeadersInputSchema = AgentVaultCustomHeaderInputSch.superRefine(addDuplicateCustomHeaderNameIssues).describe(AGENT_VAULT.SERVICE.customHeaders);+export const AgentVaultServerUrlSchema = agentVaultMcpServerUrlSchema.describe(AGENT_VAULT.SERVICE.serverUrl);++export const AgentVaultMcpTransportSchema = z+ .nativeEnum(AgentVaultMcpTransport)+ .describe(AGENT_VAULT.SERVICE.transport);+export const AgentVaultCustomHeadersUpdateSchema = AgentVaultCustomHeaderUpdateSchema.array().max(AGENT_VAULT_MAX_CUSTOM_HEADERS).superRefine(addDuplicateCustomHeaderNameIssues)@@ -169,6 +210,54 @@ export const AgentVaultSubstitutionsUpdateSchema = AgentVaultSubstitutionUpdateS.superRefine(addDuplicatePlaceholderIssues).describe(AGENT_VAULT.SERVICE.substitutions);+// `type` is optional and means http, so clients written before MCP services keep working unchanged. Each+// option also takes the other type's fields, hidden from the docs, so the service can refuse them with a+// message naming the field rather than zod dropping them silently.+export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion(+ "type",+ [+ z+ .object({+ type: z+ .literal(AgentVaultServiceType.Http)+ .optional()+ .transform(() => AgentVaultServiceType.Http as const)+ .describe(AGENT_VAULT.SERVICE.type),+ name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),+ hostPattern: AgentVaultHostPatternSchema,+ allowedMethods: AgentVaultAllowedMethodsSchema.optional(),+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),+ credential: AgentVaultCredentialInputSchema,+ customHeaders: AgentVaultCustomHeadersInputSchema.optional(),+ substitutions: AgentVaultSubstitutionsInputSchema.optional(),+ serverUrl: AgentVaultServerUrlSchema.optional().describe(openApiHidden()),+ transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden())+ })+ .describe(JSON.stringify({ title: "HTTP service" })),+ z+ .object({+ type: z.literal(AgentVaultServiceType.Mcp).describe(AGENT_VAULT.SERVICE.type),+ name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),+ serverUrl: AgentVaultServerUrlSchema,+ transport: AgentVaultMcpTransportSchema,+ credential: AgentVaultCredentialInputSchema.describe(AGENT_VAULT.SERVICE.mcpCredential),+ customHeaders: AgentVaultCustomHeadersInputSchema.optional(),+ hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),+ allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional().describe(openApiHidden()),+ substitutions: AgentVaultSubstitutionsInputSchema.optional().describe(openApiHidden())+ })+ .describe(JSON.stringify({ title: "MCP service" }))+ ],+ {+ // The default message lists the optional discriminator's `undefined` as an empty option.+ errorMap: (issue, ctx) =>+ issue.code === z.ZodIssueCode.invalid_union_discriminator+ ? { message: `'type' must be '${AgentVaultServiceType.Http}' or '${AgentVaultServiceType.Mcp}'.` }+ : { message: ctx.defaultError }+ }+);+const variableReferenceBase = {variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),key: z.string().describe(AGENT_VAULT.VARIABLE.key)@@ -206,6 +295,19 @@ export const AgentVaultServiceSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId),accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),name: z.string().describe(AGENT_VAULT.SERVICE.name),+ type: z.nativeEnum(AgentVaultServiceType).describe(AGENT_VAULT.SERVICE.type),+ // MCP first: the empty object matches anything, so it has to be the fallback.+ config: z+ .union([+ z+ .object({+ serverUrl: z.string().describe(AGENT_VAULT.SERVICE.serverUrl),+ transport: z.nativeEnum(AgentVaultMcpTransport).describe(AGENT_VAULT.SERVICE.transport)+ })+ .describe(JSON.stringify({ title: "MCP" })),+ z.object({}).describe(JSON.stringify({ title: "HTTP" }))+ ])+ .describe(AGENT_VAULT.SERVICE.config),hostPattern: z.string().describe(AGENT_VAULT.SERVICE.hostPattern),allowedMethods: z.nativeEnum(AgentVaultHttpMethod).array().nullable().describe(AGENT_VAULT.SERVICE.allowedMethods),allowedPathPrefixes: z.string().array().nullable().describe(AGENT_VAULT.SERVICE.allowedPathPrefixes),diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.tsindex 047d94d09b..df698996ed 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts@@ -1,6 +1,7 @@import { registerAgentVaultAccessBundleRouter } from "./agent-vault-access-bundle-router";import { registerAgentVaultAppConnectionRouter } from "./agent-vault-app-connection-router";import { registerAgentVaultMembershipRouter } from "./agent-vault-membership-router";+import { registerAgentVaultOauthRouter } from "./agent-vault-oauth-router";import { registerAgentVaultProjectRouter } from "./agent-vault-project-router";import { registerAgentVaultProxyAgentRouter } from "./agent-vault-proxy-agent-router";import { registerAgentVaultProxyRouter } from "./agent-vault-proxy-router";@@ -22,6 +23,7 @@ export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {await server.register(registerAgentVaultAppConnectionRouter, { prefix: "/app-connections/aws" });await server.register(registerAgentVaultProxyRouter, { prefix: "/proxies" });await server.register(registerAgentVaultMembershipRouter, { prefix: "/members" });+ await server.register(registerAgentVaultOauthRouter, { prefix: "/oauth" });// Separate prefix so the preValidation project hook still matches while these routes authenticate as the proxy.await server.register(registerAgentVaultProxyAgentRouter, { prefix: "/proxy" });};diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex bb8a17beaf..1e4725b17e 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts@@ -45,10 +45,19 @@ import {AgentVaultHttpMethod,AgentVaultMemberType,AgentVaultResourceRole,+ AgentVaultServiceType,AgentVaultSubstitutionSurface,AgentVaultVariableReferenceField} from "../agent-vault/agent-vault-enums";import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import {+ assertCredentialTypeSupported,+ assertServiceFieldsSupported,+ buildServiceConfig,+ getAgentVaultServiceType,+ resolveServiceHostPattern,+ TAgentVaultServiceConfig+} from "../agent-vault/agent-vault-service-types";import {AGENT_VAULT_MAX_VARIABLES,findStoredVariableIds,@@ -57,6 +66,13 @@ import {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 { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";import {TAddMembersDTO,@@ -106,6 +122,10 @@ type TAgentVaultAccessBundleServiceFactoryDep = {agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;+ agentVaultOauthService: Pick<+ TAgentVaultOauthServiceFactory,+ "claimAuthorization" | "buildCredentialFromAuthorization"+ >;} & TAgentVaultActorNameDALs;export type TAgentVaultAccessBundleServiceFactory = ReturnType<typeof agentVaultAccessBundleServiceFactory>;@@ -134,6 +154,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundagentVaultMemberDAL,userGroupMembershipDAL,identityGroupMembershipDAL,+ agentVaultOauthService,userDAL,groupDAL,identityDAL@@ -333,6 +354,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundsecret: { 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 };}@@ -343,6 +367,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundstored: 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({@@ -388,6 +415,21 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst summarizeCredential = (service: TAgentVaultServices): TAgentVaultCredentialSummary => {const config = service.credentialConfig as Record<string, string>;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,+ authorizedBy: oauth.authorizedBy ?? null,+ authorizedAt: oauth.authorizedAt ?? null,+ lastError: oauth.lastError ?? null+ };+ }case AgentVaultCredentialType.Bearer:return {type: AgentVaultCredentialType.Bearer,@@ -437,6 +479,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundid: service.id,accessBundleId: service.accessBundleId,name: service.name,+ type: service.type as AgentVaultServiceType,+ // Plaintext and secret-free by construction (`{}` for http), so it is returned as stored.+ config: (service.config ?? {}) as TAgentVaultServiceConfig,hostPattern: service.hostPattern,allowedMethods: (service.allowedMethods ?? null) as AgentVaultHttpMethod[] | null,allowedPathPrefixes: service.allowedPathPrefixes ?? null,@@ -584,11 +629,13 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE ="This service's credential was changed by another save while this one was in progress. Reload the service and save again.";- // Basic has no header name in its config, but the proxy always writes Authorization.+ // Basic and OAuth have no header name in their config, but the proxy always writes Authorization for both.const credentialHeaderName = (credentialType: AgentVaultCredentialType, headerName?: string): string | null => {switch (credentialType) {case AgentVaultCredentialType.Bearer:return headerName || "Authorization";+ case AgentVaultCredentialType.OAuth:+ return AGENT_VAULT_OAUTH_HEADER_NAME;case AgentVaultCredentialType.Basic:return "Authorization";default:@@ -599,14 +646,11 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund// The proxy writes the credential last, so a collision costs the header rather than the token; refusing it// on write is what tells the author. Either half of a PATCH can introduce one, which is why both are read.const assertCustomHeadersDoNotShadowCredential = (- config: TAgentVaultCredentialConfig,+ config: { type: AgentVaultCredentialType; headerName?: string },customHeaders: { name: string }[] | undefined) => {if (!customHeaders?.length) return;- const credentialHeader = credentialHeaderName(- config.type,- config.type === AgentVaultCredentialType.Bearer ? config.headerName : undefined- );+ const credentialHeader = credentialHeaderName(config.type, config.headerName);if (!credentialHeader) return;const clash = customHeaders.find((header) => header.name.toLowerCase() === credentialHeader.toLowerCase());@@ -617,6 +661,47 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}};+ // The tokens come from an authorization the same user completed. It is claimed right before the write and+ // deleted only once the write commits, so a save that fails 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 [user] = ctx.actor === ActorType.USER ? await userDAL.find({ id: ctx.actorId }) : [];+ const claim = await agentVaultOauthService.claimAuthorization({+ authorizationId,+ projectId,+ accessBundleId,+ serviceId,+ ctx,+ serverUrl+ });+ const build = (requiredScopes?: string[]) =>+ agentVaultOauthService.buildCredentialFromAuthorization(claim.record, {+ authorizedBy: user ? { userId: user.id, username: user.username } : null,+ 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 });@@ -796,8 +881,11 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst createService = async ({accessBundleId,+ type,name,- hostPattern,+ hostPattern: requestedHostPattern,+ serverUrl,+ transport,allowedMethods,allowedPathPrefixes,credential,@@ -811,6 +899,20 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundProjectPermissionSub.AgentVaultAccessBundles);+ const serviceType = getAgentVaultServiceType(type);+ assertServiceFieldsSupported(serviceType, {+ hostPattern: requestedHostPattern,+ allowedMethods,+ allowedPathPrefixes,+ customHeaders,+ substitutions,+ serverUrl,+ transport+ });+ assertCredentialTypeSupported(serviceType, credential.type);+ const serviceConfig = buildServiceConfig(serviceType, { serverUrl, transport });+ const hostPattern = resolveServiceHostPattern(serviceType, serviceConfig, requestedHostPattern);+const existing = await agentVaultServiceDAL.findOne({ accessBundleId: bundle.id, name });if (existing) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });@@ -829,17 +931,15 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst 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 } = splitCredential(- storeCredentialReferences(credential, store) as TAgentVaultCredentialInput- );- assertCustomHeadersDoNotShadowCredential(config, customHeaders);+ const split =+ credential.type === AgentVaultCredentialType.OAuth+ ? null+ : splitCredential(storeCredentialReferences(credential, store) as TAgentVaultCredentialInput);+ assertCustomHeadersDoNotShadowCredential(split ? split.config : { type: credential.type }, customHeaders);+ const secret = split?.secret ?? null;const { encryptor } = await getProjectCipher(rest.projectId);const seal = (value: string) => encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;-- const encryptedCredential = secret- ? encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob- : null;// Stored once, so the sealed text and the references read off it are the same string.const storedCustomHeaderValues = (customHeaders ?? []).map((header) => store(header.value));const storedSubstitutionValues = (substitutions ?? []).map((substitution) => store(substitution.value));@@ -856,6 +956,21 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundencryptedValue: seal(storedSubstitutionValues[position])}));+ const oauth =+ credential.type === AgentVaultCredentialType.OAuth+ ? await claimOauthCredential({+ projectId: rest.projectId,+ ctx: rest.ctx,+ accessBundleId: bundle.id,+ serverUrl: serviceConfig.serverUrl!,+ authorizationId: credential.authorizationId+ })+ : null;+ const credentialConfig: TAgentVaultCredentialConfig = oauth ? oauth.config : split!.config;+ let encryptedCredential: Buffer | null = null;+ if (oauth) encryptedCredential = oauth.encryptedCredential;+ else if (secret) encryptedCredential = encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob;+// The pre-check above is only a fast failure. The authoritative one runs under the bundle row lock,// the same lock addMembers takes, because no database constraint can express host-pattern overlap.const write = () =>@@ -872,11 +987,13 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund{accessBundleId: bundle.id,name,+ type: serviceType.type,+ config: serviceConfig,hostPattern,allowedMethods: allowedMethods ?? null,allowedPathPrefixes: allowedPathPrefixes ?? null,credentialType: credential.type,- credentialConfig: config,+ credentialConfig,encryptedCredential},tx@@ -926,6 +1043,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundtry {result = await write();} catch (err) {+ await oauth?.claim.restore();if (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });}@@ -955,8 +1073,11 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst updateService = async ({accessBundleId,serviceId,+ type,name,- hostPattern,+ hostPattern: requestedHostPattern,+ serverUrl,+ transport,credential,allowedMethods,allowedPathPrefixes,@@ -973,6 +1094,47 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst service = await agentVaultServiceDAL.findByIdInAccessBundle({ id: serviceId, accessBundleId: bundle.id });if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ if (type !== undefined) {+ throw new BadRequestError({+ message: "A service's type can't be changed. Leave 'type' out, or create a new service of the other type."+ });+ }+ const serviceType = getAgentVaultServiceType(service.type);+ assertServiceFieldsSupported(serviceType, {+ hostPattern: requestedHostPattern,+ allowedMethods,+ allowedPathPrefixes,+ customHeaders,+ substitutions,+ serverUrl,+ transport+ });+ if (credential) assertCredentialTypeSupported(serviceType, credential.type);++ // The fields of the type's config this request sent. Ones left out keep their stored value, so the config+ // is merged here for the fast checks and again under the lock against the row read there.+ const configUpdate = Object.fromEntries(+ Object.entries({ serverUrl, transport }).filter(([, value]) => value !== undefined)+ );+ const hasConfigUpdate = Object.keys(configUpdate).length > 0;+ const deriveHostPattern = (config: TAgentVaultServiceConfig) =>+ resolveServiceHostPattern(serviceType, config, requestedHostPattern);+ const serviceConfig = hasConfigUpdate ? buildServiceConfig(serviceType, configUpdate, service.config) : undefined;+ const hostPattern =+ serviceConfig && serviceType.deriveHostPattern ? deriveHostPattern(serviceConfig) : requestedHostPattern;++ const storedOauth =+ service.credentialType === AgentVaultCredentialType.OAuth+ ? (service.credentialConfig as TAgentVaultOauthConfig)+ : undefined;+ const oauthAuthorizationId =+ credential?.type === AgentVaultCredentialType.OAuth ? credential.authorizationId : undefined;+ const storedServerUrl = (service.config as TAgentVaultServiceConfig | null)?.serverUrl;+ const staysOauth = credential ? credential.type === AgentVaultCredentialType.OAuth : Boolean(storedOauth);+ if (serverUrl !== undefined && serverUrl !== storedServerUrl && staysOauth && !oauthAuthorizationId) {+ throw new BadRequestError({ message: OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE });+ }+if (name && name !== service.name) {const existing = await agentVaultServiceDAL.findOne({ accessBundleId: bundle.id, name });if (existing) {@@ -1024,7 +1186,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund// Undefined leaves the sealed secret, and the references read off it, as they are.let writtenSecret: TCredentialWrite["secret"];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);let encryptedCredential: Buffer | null | undefined;if (secret === null) encryptedCredential = null;@@ -1080,70 +1243,147 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundencryptedValue: 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: (serviceConfig ?? (service.config as TAgentVaultServiceConfig)).serverUrl!,+ authorizationId: oauthAuthorizationId,+ previousRequiredScopes: storedOauth?.requiredScopes+ })+ : null;+ if (oauth) {+ credentialUpdate = {+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: oauth.config,+ encryptedCredential: oauth.encryptedCredential+ };+ // Clears the old credential's variable references, since OAuth tokens never hold one.+ writtenSecret = null;+ 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 lockedConfig = locked.config as TAgentVaultServiceConfig | null;+ 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 ?? null,+ effectiveServerUrl: lockedServiceConfig.serverUrl ?? null,+ 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) {+ 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,+ lockedServerUrl: (lockedServiceConfig ?? lockedConfig)?.serverUrl ?? null,+ readOauth: storedOauth,+ lockedOauth+ });+ const rebuilt = oauth.rebuild(requiredScopes);+ lockedCredentialUpdate = {+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: rebuilt.config,+ encryptedCredential: rebuilt.encryptedCredential+ };+ 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);- if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });+ if (!lockedBundle) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });- if (hostPattern && hostPattern !== service.hostPattern) {- await checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern, excludeServiceId: service.id }, tx);- }+ const locked = await agentVaultServiceDAL.findByIdInAccessBundle(+ { id: service.id, accessBundleId: bundle.id },+ tx+ );+ if (!locked) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ const reconciled = reconcileWithLockedRow(locked);- // The credential was merged against the row read before the lock, whose type decided how the request- // reads. If another save changed it since, writing now would set a half this request left out back to- // an older value.- if (credential) {- const current = await agentVaultServiceDAL.findById(service.id, tx);- if (!current) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });- const secretChanged =- storedSecret !== null && !current.encryptedCredential?.equals(service.encryptedCredential!);- if (current.credentialType !== service.credentialType || secretChanged) {- throw new ConflictError({ message: CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE });- }+ // Only when the pattern actually changes, against the siblings read under the lock.+ if (reconciled.hostPattern && reconciled.hostPattern !== locked.hostPattern) {+ await checkHostPatternConflicts(+ { accessBundleId: bundle.id, hostPattern: reconciled.hostPattern, excludeServiceId: service.id },+ tx+ );}- // Both halves read under the lock. The service read above the transaction came before it, and stale it- // would admit the very collision this check exists to stop.if (credential || customHeaders) {const effectiveCustomHeaders =customHeaders ??(await agentVaultServiceCustomHeaderDAL.findByServiceIds([service.id], tx)).map((row) => ({name: row.name}));- if (!credential) {- const current = await agentVaultServiceDAL.findById(service.id, tx);- if (!current) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });- effectiveCredentialConfig = current.credentialConfig as TAgentVaultCredentialConfig;- }- assertCustomHeadersDoNotShadowCredential(effectiveCredentialConfig, effectiveCustomHeaders);+ assertCustomHeadersDoNotShadowCredential(reconciled.credentialConfig, effectiveCustomHeaders);}const hasColumnUpdate =name !== undefined ||- hostPattern !== undefined ||+ reconciled.hostPattern !== undefined ||+ reconciled.serviceConfig !== undefined ||allowedMethods !== undefined ||allowedPathPrefixes !== undefined ||- Object.keys(credentialUpdate).length > 0;+ Object.keys(reconciled.credentialUpdate).length > 0;const updatedService = hasColumnUpdate? await agentVaultServiceDAL.updateById(service.id,{name,- hostPattern,+ hostPattern: reconciled.hostPattern,+ ...(reconciled.serviceConfig === undefined ? {} : { config: reconciled.serviceConfig }),// `null` clears the restriction, `undefined` leaves the column alone....(allowedMethods === undefined ? {} : { allowedMethods }),...(allowedPathPrefixes === undefined ? {} : { allowedPathPrefixes }),- ...credentialUpdate+ ...reconciled.credentialUpdate},tx)- : service;+ : locked;// 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>(@@ -1265,6 +1505,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundtry {result = await write();} catch (err) {+ await oauth?.claim.restore();if (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });}diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex 07d14ea100..a5c633cfd9 100644--- 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@@ -3,6 +3,9 @@ import { TGenericPermission } from "@app/lib/types";import {AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,+ AgentVaultOauthStatus,+ AgentVaultServiceType,AgentVaultSubstitutionSurface,AgentVaultVariableReferenceField} from "../agent-vault/agent-vault-enums";@@ -11,17 +14,32 @@ import { TAgentVaultAccessBundleOrderBy } from "./agent-vault-access-bundle-dal"export type TAgentVaultCredentialInput =| { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value: string }| { type: AgentVaultCredentialType.Basic; username: string; password: string }- | { 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.Passthrough }+ | { type: AgentVaultCredentialType.OAuth; authorizationId: string };++export type TAgentVaultOauthCredentialSummary = {+ type: AgentVaultCredentialType.OAuth;+ status: AgentVaultOauthStatus;+ issuer: string;+ grantedScopes: string[];+ requiredScopes: string[];+ expiresAt: string | null;+ authorizedBy: { userId: string; username: string } | null;+ authorizedAt: string | null;+ lastError: string | null;+};export type TAgentVaultCredentialSummary =| { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }| { type: AgentVaultCredentialType.Basic }- | { type: AgentVaultCredentialType.Passthrough };+ | { type: AgentVaultCredentialType.Passthrough }+ | TAgentVaultOauthCredentialSummary;export type TAgentVaultVariableReferenceSummary = { variableId: string; key: string } & (| { field: AgentVaultVariableReferenceField.CredentialValue | AgentVaultVariableReferenceField.CredentialUsername }@@ -73,10 +91,15 @@ export type TAgentVaultSubstitutionUpdate = {value?: string;};+// Flat rather than a union on `type`: which of the type-specific fields a service takes is decided by the+// service type registry, which refuses the ones its type does not take.export type TCreateServiceDTO = TAgentVaultProjectScoped & {accessBundleId: string;+ type: AgentVaultServiceType;name: string;- hostPattern: string;+ hostPattern?: string;+ serverUrl?: string;+ transport?: AgentVaultMcpTransport;allowedMethods?: AgentVaultHttpMethod[] | null;allowedPathPrefixes?: string[] | null;credential: TAgentVaultCredentialInput;@@ -87,8 +110,12 @@ export type TCreateServiceDTO = TAgentVaultProjectScoped & {export type TUpdateServiceDTO = TAgentVaultProjectScoped & {accessBundleId: string;serviceId: string;+ // Only so the refusal can be a readable 400: a service's type never changes.+ type?: AgentVaultServiceType;name?: string;hostPattern?: string;+ serverUrl?: string;+ transport?: AgentVaultMcpTransport;allowedMethods?: AgentVaultHttpMethod[] | null;allowedPathPrefixes?: string[] | null;credential?: TAgentVaultCredentialUpdate;diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.tsindex 74a7b99173..617ecde739 100644--- 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@@ -5,6 +5,8 @@ import { TableName, TAgentVaultServices } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify } from "@app/lib/knex";+import { AgentVaultCredentialType, AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";+export type TAgentVaultServiceDALFactory = ReturnType<typeof agentVaultServiceDALFactory>;export const agentVaultServiceDALFactory = (db: TDbClient) => {@@ -32,5 +34,92 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {}};- return { ...orm, findByAccessBundleId, findByIdInAccessBundle };+ 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.+ // `keepStatus` is decided against the row being written, not the one the caller read: a status write that+ // leaves the sealed credential alone (a scope report) passes the compare, and must not be overwritten.+ const compareAndSwapCredential = async (+ {+ id,+ expectedEncryptedCredential,+ encryptedCredential,+ credentialConfigPatch,+ keepStatus+ }: {+ id: string;+ expectedEncryptedCredential: Buffer;+ encryptedCredential?: Buffer;+ credentialConfigPatch: Record<string, unknown>;+ keepStatus?: { status: string; keys: string[] };+ },+ tx?: Knex+ ): Promise<Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined> => {+ try {+ const patch = JSON.stringify(credentialConfigPatch);+ const keptKeys = ["status", ...(keepStatus?.keys ?? [])];+ const credentialConfig = keepStatus+ ? db.raw(+ `CASE WHEN "credentialConfig"->>'status' = ? THEN COALESCE("credentialConfig", '{}'::jsonb) || (?::jsonb${keptKeys.map(() => " - ?::text").join("")}) ELSE COALESCE("credentialConfig", '{}'::jsonb) || ?::jsonb END`,+ [keepStatus.status, patch, ...keptKeys, 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.+ 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 [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])+ .update({+ credentialConfig: db.raw(+ `COALESCE("credentialConfig", '{}'::jsonb) || jsonb_build_object('status', ?::text, 'requiredScopes', ${stored} || COALESCE((SELECT jsonb_agg(reported.scope ORDER BY reported.ord) FROM jsonb_array_elements_text(?::jsonb) WITH ORDINALITY AS reported(scope, ord) WHERE NOT ${stored} @> jsonb_build_array(reported.scope)), '[]'::jsonb))`,+ [AgentVaultOauthStatus.NeedsAdditionalScopes, JSON.stringify([...new Set(requiredScopes)])]+ )+ })+ .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" });+ }+ };++ return {+ ...orm,+ findByAccessBundleId,+ findByIdInAccessBundle,+ findByIdPrimary,+ compareAndSwapCredential,+ addRequiredScopes+ };};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.tsnew file mode 100644index 0000000000..65268639f1--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.ts@@ -0,0 +1,164 @@+import RE2 from "re2";++import { logger } from "@app/lib/logger";++import { describeServer } from "./agent-vault-oauth-discovery-fns";+import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";+import {+ MAX_ERROR_CODE_LENGTH,+ MAX_ERROR_DESCRIPTION_LENGTH,+ normalizeProviderText+} from "./agent-vault-oauth-token-fns";+import { AgentVaultOauthClientAuthMethod, AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";++export const AGENT_VAULT_OAUTH_CLIENT_NAME = "Infisical Agent Vault";++export type TOauthClient = {+ clientId: string;+ clientSecret?: string;+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod;+};++export class OauthRegistrationError extends Error {+ status: number | null;++ constructor(message: string, status: number | null) {+ super(message);+ this.name = "OauthRegistrationError";+ this.status = status;+ }+}++const SUPPORTED_AUTH_METHODS = Object.values(AgentVaultOauthClientAuthMethod) as string[];++// RFC 6749 appendix A.1 and A.2: both are VSCHAR. The ID is stored in jsonb and sent in the authorize URL, and the+// secret is form-encoded into the token request, which throws on a lone surrogate.+export const OAUTH_CLIENT_CREDENTIAL_PATTERN = new RE2(/^[\x20-\x7e]+$/);+const MAX_CLIENT_ID_LENGTH = 512;+const MAX_CLIENT_SECRET_LENGTH = 4096;++const parseRegistration = (body: string): TOauthClient | null => {+ let parsed: Record<string, unknown>;+ try {+ parsed = JSON.parse(body) as Record<string, unknown>;+ } catch {+ return null;+ }+ if (+ !parsed ||+ typeof parsed.client_id !== "string" ||+ parsed.client_id.length > MAX_CLIENT_ID_LENGTH ||+ !OAUTH_CLIENT_CREDENTIAL_PATTERN.test(parsed.client_id)+ ) {+ return null;+ }+ let clientSecret: string | undefined;+ if (typeof parsed.client_secret === "string" && parsed.client_secret) {+ if (+ parsed.client_secret.length > MAX_CLIENT_SECRET_LENGTH ||+ !OAUTH_CLIENT_CREDENTIAL_PATTERN.test(parsed.client_secret)+ ) {+ return null;+ }+ clientSecret = parsed.client_secret;+ }+ // The server may assign a method other than the one asked for; what it returns is what the client holds.+ let method = typeof parsed.token_endpoint_auth_method === "string" ? parsed.token_endpoint_auth_method : null;+ if (!method || !SUPPORTED_AUTH_METHODS.includes(method)) {+ method = clientSecret ? AgentVaultOauthClientAuthMethod.ClientSecretBasic : AgentVaultOauthClientAuthMethod.None;+ }+ return {+ clientId: parsed.client_id,+ clientSecret,+ tokenEndpointAuthMethod: method as AgentVaultOauthClientAuthMethod+ };+};++// RFC 7591. Some servers reject metadata fields they don't know, so a refusal is retried once with only the+// fields every server has to accept.+export const registerOauthClient = async ({+ http,+ serverUrl,+ registrationEndpoint,+ redirectUri+}: {+ http: TOauthHttpClient;+ serverUrl: string;+ registrationEndpoint: string;+ redirectUri: string;+}): Promise<{ client: TOauthClient; compatibility: AgentVaultOauthCompatibility[] }> => {+ const minimal = {+ client_name: AGENT_VAULT_OAUTH_CLIENT_NAME,+ redirect_uris: [redirectUri],+ token_endpoint_auth_method: AgentVaultOauthClientAuthMethod.None+ };+ const full = {+ ...minimal,+ application_type: "web",+ grant_types: ["authorization_code", "refresh_token"],+ response_types: ["code"]+ };++ let lastStatus: number | null = null;+ let lastReason = "";+ // eslint-disable-next-line no-restricted-syntax+ for (const [attempt, body] of [full, minimal].entries()) {+ let response;+ try {+ // eslint-disable-next-line no-await-in-loop+ response = await http.postJson(registrationEndpoint, body);+ } catch {+ logger.info(`agentVaultOauth: client registration unreachable [server=${describeServer(serverUrl)}]`);+ throw new OauthRegistrationError("its registration endpoint couldn't be reached.", null);+ }+ lastStatus = response.status;+ try {+ const refusal = JSON.parse(response.body) as { error?: unknown; error_description?: unknown };+ lastReason =+ normalizeProviderText(refusal.error_description, MAX_ERROR_DESCRIPTION_LENGTH) ||+ normalizeProviderText(refusal.error, MAX_ERROR_CODE_LENGTH);+ } catch {+ lastReason = "";+ }+ if (response.status === 200 || response.status === 201) {+ const client = parseRegistration(response.body);+ if (!client) {+ throw new OauthRegistrationError("its registration endpoint returned no usable client ID.", response.status);+ }+ return {+ client,+ compatibility: attempt === 0 ? [] : [AgentVaultOauthCompatibility.RegistrationMinimal]+ };+ }+ logger.info(+ `agentVaultOauth: client registration refused [server=${describeServer(serverUrl)}] [status=${response.status}] [attempt=${attempt + 1}]`+ );+ if (response.status >= 500) break;+ }++ throw new OauthRegistrationError(+ `its registration endpoint refused to register Infisical as a client (${lastReason || `HTTP ${lastStatus}`}).`,+ lastStatus+ );+};++// An admin-entered client. RFC 8414 makes client_secret_basic the default when the server lists no methods.+export const manualOauthClient = ({+ clientId,+ clientSecret,+ tokenEndpointAuthMethodsSupported+}: {+ clientId: string;+ clientSecret?: string;+ tokenEndpointAuthMethodsSupported: string[] | null;+}): TOauthClient => {+ if (!clientSecret) return { clientId, tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None };+ const supported = tokenEndpointAuthMethodsSupported;+ const method =+ supported &&+ !supported.includes(AgentVaultOauthClientAuthMethod.ClientSecretBasic) &&+ supported.includes(AgentVaultOauthClientAuthMethod.ClientSecretPost)+ ? AgentVaultOauthClientAuthMethod.ClientSecretPost+ : AgentVaultOauthClientAuthMethod.ClientSecretBasic;+ return { clientId, clientSecret, tokenEndpointAuthMethod: method };+};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.tsnew file mode 100644index 0000000000..53fbd48d1c--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts@@ -0,0 +1,486 @@+import { describe, expect, test, vi } from "vitest";++import {+ authorizationServerMetadataUrls,+ checkIssuer,+ checkProtectedResource,+ discoverOauthServer,+ isOauthScopeToken,+ parseBearerChallenge,+ protectedResourceMetadataUrls,+ selectScopes+} from "./agent-vault-oauth-discovery-fns";+import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";+import { AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";++vi.mock("@app/lib/logger", async () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ sanitizeUrlForLog: (+ await vi.importActual<typeof import("@app/lib/logger/sanitize-url")>("@app/lib/logger/sanitize-url")+ ).sanitizeUrlForLog+}));++type TStubServer = {+ challenge?: string | null;+ probeThrows?: boolean;+ json: Record<string, unknown>;+};++const stubHttp = ({ challenge = null, probeThrows = false, json }: TStubServer) => {+ const fetched: string[] = [];+ const http: TOauthHttpClient = {+ probe: async () => {+ if (probeThrows) throw new Error("connect ECONNREFUSED");+ return { status: 401, wwwAuthenticate: challenge };+ },+ get: async (url) => {+ fetched.push(url);+ return url in json+ ? { status: 200, contentType: "application/json", body: JSON.stringify(json[url]) }+ : { status: 404, contentType: "text/plain", body: "not found" };+ },+ postForm: async () => {+ throw new Error("unexpected");+ },+ postJson: async () => {+ throw new Error("unexpected");+ }+ };+ return { http, fetched };+};++const LINEAR_AS = {+ issuer: "https://mcp.linear.app",+ authorization_endpoint: "https://mcp.linear.app/authorize",+ token_endpoint: "https://mcp.linear.app/token",+ registration_endpoint: "https://mcp.linear.app/register",+ scopes_supported: ["read", "write", "openid", "email"],+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],+ code_challenge_methods_supported: ["S256"],+ authorization_response_iss_parameter_supported: true+};++describe("parsing the WWW-Authenticate challenge", () => {+ test("Unicode whitespace and vertical tabs still delimit challenges and parameters", () => {+ expect(parseBearerChallenge('Basic realm="x",\u00a0Bearer\vscope\u2028=\ufeff"read write"')).toEqual({+ scope: "read write"+ });+ });+ test("reads resource_metadata and scope", () => {+ expect(+ parseBearerChallenge(+ 'Bearer realm="OAuth", resource_metadata="https://mcp.linear.app/.well-known/oauth-protected-resource/mcp", scope="read write"'+ )+ ).toEqual({+ realm: "OAuth",+ resource_metadata: "https://mcp.linear.app/.well-known/oauth-protected-resource/mcp",+ scope: "read write"+ });+ });++ test("keeps commas and escaped quotes inside quoted values", () => {+ expect(+ parseBearerChallenge('Bearer error="invalid_request", error_description="No token, \\"really\\"", scope=repo')+ ).toEqual({ error: "invalid_request", error_description: 'No token, "really"', scope: "repo" });+ });++ test("finds the Bearer challenge among others and stops at the next scheme", () => {+ expect(parseBearerChallenge('Basic realm="x", Bearer scope="a" , DPoP algs="ES256"')).toEqual({ scope: "a" });+ });++ test("malformed parameters end this challenge instead of skipping forward into another", () => {+ expect(parseBearerChallenge('Bearer scope="read", broken, DPoP error="other-challenge"')).toEqual({+ scope: "read"+ });+ });++ test("no Bearer challenge is null", () => {+ expect(parseBearerChallenge('Basic realm="x"')).toBeNull();+ expect(parseBearerChallenge(null)).toBeNull();+ });+});++describe("where metadata is looked for", () => {+ test("protected resource: the challenge's URL, then the path-suffixed and root well-known URLs", () => {+ expect(+ protectedResourceMetadataUrls("https://mcp.example.com/mcp", "https://mcp.example.com/.well-known/custom")+ ).toEqual([+ "https://mcp.example.com/.well-known/custom",+ "https://mcp.example.com/.well-known/oauth-protected-resource/mcp",+ "https://mcp.example.com/.well-known/oauth-protected-resource"+ ]);+ });++ test("protected resource: a non-https challenge URL is ignored, and a root server has one candidate", () => {+ expect(protectedResourceMetadataUrls("https://mcp.example.com/", "http://evil.example.com/prm")).toEqual([+ "https://mcp.example.com/.well-known/oauth-protected-resource"+ ]);+ });++ test("authorization server with a path: RFC 8414 then both OpenID forms", () => {+ expect(authorizationServerMetadataUrls("https://github.com/login/oauth")).toEqual([+ "https://github.com/.well-known/oauth-authorization-server/login/oauth",+ "https://github.com/.well-known/openid-configuration/login/oauth",+ "https://github.com/login/oauth/.well-known/openid-configuration"+ ]);+ });++ test("authorization server without a path", () => {+ expect(authorizationServerMetadataUrls("https://mcp.linear.app/")).toEqual([+ "https://mcp.linear.app/.well-known/oauth-authorization-server",+ "https://mcp.linear.app/.well-known/openid-configuration"+ ]);+ });+});++describe("checking the protected resource against the server URL", () => {+ test("an exact match, ignoring a trailing slash", () => {+ expect(checkProtectedResource("https://mcp.example.com/mcp", "https://mcp.example.com/mcp")).toEqual({+ resource: "https://mcp.example.com/mcp",+ compatibility: null+ });+ expect(checkProtectedResource("https://api.example.com/mcp", "https://api.example.com/mcp/").compatibility).toBe(+ null+ );+ });++ test("a same-origin path prefix is accepted, and that value is what gets sent", () => {+ expect(checkProtectedResource("https://mcp.example.com/mcp/v2", "https://mcp.example.com/mcp")).toEqual({+ resource: "https://mcp.example.com/mcp",+ compatibility: AgentVaultOauthCompatibility.ResourcePrefix+ });+ expect(checkProtectedResource("https://mcp.example.com/mcp", "https://mcp.example.com").compatibility).toBe(+ AgentVaultOauthCompatibility.ResourcePrefix+ );+ });++ test("a different origin is rejected", () => {+ expect(() => checkProtectedResource("https://mcp.example.com/mcp", "https://other.example.com/mcp")).toThrow(+ /different server/+ );+ });++ test("a path that only shares characters is not a prefix", () => {+ expect(() => checkProtectedResource("https://mcp.example.com/mcpx", "https://mcp.example.com/mcp")).toThrow(+ /doesn't cover/+ );+ });++ test("a missing resource falls back to the server URL", () => {+ expect(checkProtectedResource("https://mcp.example.com/mcp", undefined)).toEqual({+ resource: "https://mcp.example.com/mcp",+ compatibility: AgentVaultOauthCompatibility.ResourceMissing+ });+ });+});++describe("issuer validation", () => {+ test("must equal the issuer the metadata was fetched for", () => {+ expect(checkIssuer("https://s.example.com", "https://as.example.com", "https://as.example.com")).toBeNull();+ expect(() => checkIssuer("https://s.example.com", "https://as.example.com", "https://evil.example.com")).toThrow(+ /different issuer/+ );+ expect(() => checkIssuer("https://s.example.com", "https://as.example.com", undefined)).toThrow(/different issuer/);+ });++ test("a trailing slash difference is accepted and recorded", () => {+ expect(checkIssuer("https://s.example.com", "https://as.example.com", "https://as.example.com/")).toBe(+ AgentVaultOauthCompatibility.IssuerTrailingSlash+ );+ });+});++describe("scope selection", () => {+ test("the challenge's scope wins", () => {+ expect(selectScopes({ challengeScope: "read write", scopesSupported: ["admin"] })).toEqual(["read", "write"]);+ });++ test("then the protected resource's scopes_supported", () => {+ expect(selectScopes({ scopesSupported: ["repo", "gist"] })).toEqual(["repo", "gist"]);+ });++ test("else nothing is requested", () => {+ expect(selectScopes({})).toEqual([]);+ });++ test("offline_access is added only when the authorization server lists it", () => {+ expect(selectScopes({ challengeScope: "read", authorizationServerScopes: ["offline_access"] })).toEqual([+ "read",+ "offline_access"+ ]);+ expect(selectScopes({ challengeScope: "read", authorizationServerScopes: ["read"] })).toEqual(["read"]);+ });++ test("scopes that aren't OAuth scope tokens are dropped from the challenge and from scopes_supported", () => {+ expect(selectScopes({ challengeScope: 'read wr"ite a\\b \u0000 \tadmin' })).toEqual(["read"]);+ expect(+ selectScopes({ scopesSupported: ["repo", "has space", "nul\u0000", "", 7, "x".repeat(257), "gist"] })+ ).toEqual(["repo", "gist"]);+ });+});++describe("the OAuth scope-token grammar (RFC 6749 section 3.3)", () => {+ test("accepts printable ASCII other than space, quote and backslash", () => {+ for (const scope of ["read", "repo:status", "https://graph.example/.default", "!#[]~", "x".repeat(256)]) {+ expect(isOauthScopeToken(scope)).toBe(true);+ }+ });++ test("refuses empty, whitespace, quotes, backslashes, control and non-ASCII characters, and long scopes", () => {+ for (const scope of ["", " ", "a b", "a\tb", 'a"b', "a\\b", "\u0000", "a\u007fb", "caf\u00e9", "x".repeat(257)]) {+ expect(isOauthScopeToken(scope)).toBe(false);+ }+ expect(isOauthScopeToken(undefined)).toBe(false);+ });+});++describe("discovering an MCP server's authorization server", () => {+ test("a conforming server (Linear): challenge, protected resource, then authorization server metadata", async () => {+ const { http, fetched } = stubHttp({+ challenge:+ 'Bearer realm="OAuth", resource_metadata="https://mcp.linear.app/.well-known/oauth-protected-resource/mcp", scope="read write"',+ json: {+ "https://mcp.linear.app/.well-known/oauth-protected-resource/mcp": {+ resource: "https://mcp.linear.app/mcp",+ authorization_servers: ["https://mcp.linear.app"],+ scopes_supported: ["read", "write"]+ },+ "https://mcp.linear.app/.well-known/oauth-authorization-server": LINEAR_AS+ }+ });++ expect(await discoverOauthServer(http, "https://mcp.linear.app/mcp")).toEqual({+ issuer: "https://mcp.linear.app",+ authorizationEndpoint: "https://mcp.linear.app/authorize",+ tokenEndpoint: "https://mcp.linear.app/token",+ registrationEndpoint: "https://mcp.linear.app/register",+ endpointsGuessed: false,+ resource: "https://mcp.linear.app/mcp",+ scopes: ["read", "write"],+ issParameterSupported: true,+ tokenEndpointAuthMethodsSupported: ["client_secret_basic", "client_secret_post", "none"],+ compatibility: []+ });+ expect(fetched).toEqual([+ "https://mcp.linear.app/.well-known/oauth-protected-resource/mcp",+ "https://mcp.linear.app/.well-known/oauth-authorization-server"+ ]);+ });++ test("an issuer with a path and no registration endpoint (GitHub)", async () => {+ const { http, fetched } = stubHttp({+ challenge:+ 'Bearer error="invalid_request", error_description="No access token was provided in this request", resource_metadata="https://api.githubcopilot.com/.well-known/oauth-protected-resource/mcp/"',+ json: {+ "https://api.githubcopilot.com/.well-known/oauth-protected-resource/mcp/": {+ resource: "https://api.githubcopilot.com/mcp/",+ authorization_servers: ["https://github.com/login/oauth"],+ scopes_supported: ["repo", "read:org"]+ },+ "https://github.com/.well-known/oauth-authorization-server/login/oauth": {+ issuer: "https://github.com/login/oauth",+ authorization_endpoint: "https://github.com/login/oauth/authorize",+ token_endpoint: "https://github.com/login/oauth/access_token",+ code_challenge_methods_supported: ["S256"],+ authorization_response_iss_parameter_supported: true,+ scopes_supported: ["offline_access"]+ }+ }+ });++ const discovery = await discoverOauthServer(http, "https://api.githubcopilot.com/mcp/");+ expect(discovery.registrationEndpoint).toBeNull();+ expect(discovery.scopes).toEqual(["repo", "read:org", "offline_access"]);+ expect(discovery.resource).toBe("https://api.githubcopilot.com/mcp/");+ expect(fetched[1]).toBe("https://github.com/.well-known/oauth-authorization-server/login/oauth");+ });++ test("without a challenge, the well-known locations are tried in order", async () => {+ const { http, fetched } = stubHttp({+ probeThrows: true,+ json: {+ "https://mcp.example.com/.well-known/oauth-protected-resource": {+ resource: "https://mcp.example.com/mcp",+ authorization_servers: ["https://auth.example.com"]+ },+ "https://auth.example.com/.well-known/openid-configuration": {+ issuer: "https://auth.example.com",+ authorization_endpoint: "https://auth.example.com/oauth/authorize",+ token_endpoint: "https://auth.example.com/oauth/token",+ code_challenge_methods_supported: ["plain", "S256"]+ }+ }+ });++ const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");+ expect(fetched).toEqual([+ "https://mcp.example.com/.well-known/oauth-protected-resource/mcp",+ "https://mcp.example.com/.well-known/oauth-protected-resource",+ "https://auth.example.com/.well-known/oauth-authorization-server",+ "https://auth.example.com/.well-known/openid-configuration"+ ]);+ expect(discovery.issuer).toBe("https://auth.example.com");+ expect(discovery.scopes).toEqual([]);+ expect(discovery.issParameterSupported).toBe(false);+ });++ test("no protected resource metadata: the MCP origin is the authorization server", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com",+ authorization_endpoint: "https://mcp.example.com/authorize",+ token_endpoint: "https://mcp.example.com/token",+ registration_endpoint: "https://mcp.example.com/register"+ }+ }+ });++ const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");+ expect(discovery.issuer).toBe("https://mcp.example.com");+ expect(discovery.resource).toBe("https://mcp.example.com/mcp");+ expect(discovery.compatibility).toEqual([AgentVaultOauthCompatibility.NoProtectedResourceMetadata]);+ });++ test("no metadata at all: default endpoints at the origin", async () => {+ const { http } = stubHttp({ json: {} });++ const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");+ expect(discovery).toMatchObject({+ issuer: "https://mcp.example.com",+ authorizationEndpoint: "https://mcp.example.com/authorize",+ tokenEndpoint: "https://mcp.example.com/token",+ registrationEndpoint: "https://mcp.example.com/register",+ endpointsGuessed: true+ });+ expect(discovery.compatibility).toEqual(+ expect.arrayContaining([+ AgentVaultOauthCompatibility.NoProtectedResourceMetadata,+ AgentVaultOauthCompatibility.NoAuthorizationServerMetadata+ ])+ );+ });++ test("a protected resource for another origin is rejected", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-protected-resource/mcp": {+ resource: "https://attacker.example.net/mcp",+ authorization_servers: ["https://auth.example.com"]+ }+ }+ });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp")).rejects.toThrow(+ "Couldn't set up OAuth for 'mcp.example.com': its protected resource metadata is for 'attacker.example.net', a different server. Check the server URL."+ );+ });++ test("an authorization server naming another issuer is rejected", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://evil.example"+ }+ }+ });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp")).rejects.toThrow(/different issuer/);+ });++ test("an issuer differing by a trailing slash is accepted", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com/"+ }+ }+ });+ const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");+ expect(discovery.compatibility).toContain(AgentVaultOauthCompatibility.IssuerTrailingSlash);+ });++ test("PKCE: refused when the list exists without S256, assumed when there is no list", async () => {+ const withoutS256 = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com",+ code_challenge_methods_supported: ["plain"]+ }+ }+ });+ await expect(discoverOauthServer(withoutS256.http, "https://mcp.example.com/mcp")).rejects.toThrow(/S256/);++ const { code_challenge_methods_supported: omitted, ...withoutList } = LINEAR_AS;+ const unadvertised = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...withoutList,+ issuer: "https://mcp.example.com"+ }+ }+ });+ const discovery = await discoverOauthServer(unadvertised.http, "https://mcp.example.com/mcp");+ expect(omitted).toBeDefined();+ expect(discovery.compatibility).toContain(AgentVaultOauthCompatibility.PkceUnadvertised);+ });++ test("an authorization server with a plain-http token endpoint is rejected", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com",+ token_endpoint: "http://mcp.example.com/token"+ }+ }+ });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp")).rejects.toThrow(/https/);+ });++ test("an endpoint URL that isn't printable ASCII is rejected, since it would be stored as sent", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com",+ token_endpoint: "https://mcp.example.com/tok\u0000en"+ }+ }+ });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp")).rejects.toThrow(/https/);++ const registration = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com",+ registration_endpoint: "https://mcp.example.com/reg\ud800"+ }+ }+ });+ const discovery = await discoverOauthServer(registration.http, "https://mcp.example.com/mcp");+ expect(discovery.registrationEndpoint).toBeNull();+ });++ test.each([+ "https://user:[email protected]/token",+ "https://mcp.example.com/token#fragment",+ "https://mcp.example.com/token#"+ ])("an endpoint with embedded credentials or a fragment is rejected: %s", async (tokenEndpoint) => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://mcp.example.com",+ token_endpoint: tokenEndpoint+ }+ }+ });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp")).rejects.toThrow(+ /without usernames, passwords or fragments/+ );+ });+});diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.tsnew file mode 100644index 0000000000..2eecbfbde3--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts@@ -0,0 +1,322 @@+import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";+import { logger, sanitizeUrlForLog } from "@app/lib/logger";++import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";+import { AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";++export const OFFLINE_ACCESS_SCOPE = "offline_access";++export type TOauthDiscovery = {+ issuer: string;+ authorizationEndpoint: string;+ tokenEndpoint: string;+ registrationEndpoint: string | null;+ // True when the endpoints were guessed at the origin, so a failed registration means "enter a client" rather+ // than "the server is broken".+ endpointsGuessed: boolean;+ resource: string;+ scopes: string[];+ issParameterSupported: boolean;+ tokenEndpointAuthMethodsSupported: string[] | null;+ compatibility: AgentVaultOauthCompatibility[];+};++export const describeServer = (serverUrl: string) => {+ try {+ return new URL(serverUrl).host;+ } catch {+ return "the MCP server";+ }+};++export const oauthSetupError = (serverUrl: string, problem: string) =>+ new BadRequestError({ message: `Couldn't set up OAuth for '${describeServer(serverUrl)}': ${problem}` });++// Printable ASCII only, as RFC 3986 requires: these URLs are stored in jsonb as sent, and the URL parser would+// accept a NUL or a lone surrogate that the jsonb write then fails on.+const URL_PATTERN = new RE2(/^[\x21-\x7e]+$/);+const TRAILING_SLASH_RE = new RE2(/\/+$/);+// RE2's \s is ASCII-only; include the Unicode whitespace accepted by the existing parser.+const BEARER_CHALLENGE_RE = new RE2(/(^|[\s\v\p{Z}\ufeff,])Bearer([\s\v\p{Z}\ufeff]|$)/iu);+const BEARER_PREFIX_RE = new RE2(/^[\s\v\p{Z}\ufeff,]*Bearer[\s\v\p{Z}\ufeff]*/iu);+const CHALLENGE_SEPARATOR_RE = new RE2(/[\s\v\p{Z}\ufeff,]/u);+const QUOTED_ESCAPE_RE = new RE2(/\\(.)/g);++const isHttpsUrl = (value: unknown): value is string => {+ if (typeof value !== "string" || value.length > 2048 || !URL_PATTERN.test(value)) return false;+ try {+ const url = new URL(value);+ return url.protocol === "https:" && !url.username && !url.password && !value.includes("#");+ } catch {+ return false;+ }+};++export const stripTrailingSlash = (value: string) => value.replace(TRAILING_SLASH_RE, "");++// RFC 6750 section 3 auth-params of the Bearer challenge. Quoted strings may hold commas and escaped quotes.+export const parseBearerChallenge = (header: string | null): Record<string, string> | null => {+ if (!header) return null;+ const start = header.search(BEARER_CHALLENGE_RE);+ if (start === -1) return null;+ const rest = header.slice(start).replace(BEARER_PREFIX_RE, "");++ const params: Record<string, string> = {};+ const paramRe = new RE2(+ /([A-Za-z0-9_-]+)[\s\v\p{Z}\ufeff]*=[\s\v\p{Z}\ufeff]*(?:"((?:[^"\\]|\\.)*)"|([^\s\v\p{Z}\ufeff,"]+))/uy+ );+ let index = 0;+ while (index < rest.length) {+ while (index < rest.length && CHALLENGE_SEPARATOR_RE.test(rest[index])) index += 1;+ if (index >= rest.length) break;+ paramRe.lastIndex = index;+ const match = paramRe.exec(rest);+ // Anything else is the next challenge's scheme, which ends this one.+ if (!match) break;+ const [, key, quoted, token] = match;+ params[key.toLowerCase()] = quoted !== undefined ? quoted.replace(QUOTED_ESCAPE_RE, "$1") : token;+ index = paramRe.lastIndex;+ }+ return params;+};++export const MAX_OAUTH_SCOPE_LENGTH = 256;+// RFC 6749 section 3.3 scope-token. Scopes are joined with spaces into the scope parameter and stored in jsonb, so+// whitespace, quotes, backslashes and control characters (NUL included) would corrupt one or the other.+export const OAUTH_SCOPE_TOKEN_PATTERN = new RE2(/^[\x21\x23-\x5b\x5d-\x7e]+$/);++export const isOauthScopeToken = (scope: unknown): scope is string =>+ typeof scope === "string" && scope.length <= MAX_OAUTH_SCOPE_LENGTH && OAUTH_SCOPE_TOKEN_PATTERN.test(scope);++export const splitScopes = (scope: unknown, delimiter: RE2 | string = " "): string[] =>+ typeof scope === "string" ? [...new Set(scope.split(delimiter).filter(isOauthScopeToken))] : [];++const parseJsonObject = (response: TOauthHttpResponse): Record<string, unknown> | null => {+ if (response.status !== 200) return null;+ try {+ const parsed: unknown = JSON.parse(response.body);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;+ } catch {+ return null;+ }+};++const fetchJson = async (http: TOauthHttpClient, url: string) => {+ try {+ return parseJsonObject(await http.get(url));+ } catch {+ logger.info(`agentVaultOauth: metadata fetch failed [url=${sanitizeUrlForLog(url)}]`);+ return null;+ }+};++// RFC 9728 section 3.1: the well-known segment goes between the host and the path.+export const protectedResourceMetadataUrls = (serverUrl: string, challengeUrl?: string): string[] => {+ const url = new URL(serverUrl);+ const path = url.pathname === "/" ? "" : url.pathname;+ return [+ ...(challengeUrl && isHttpsUrl(challengeUrl) ? [challengeUrl] : []),+ ...(path ? [`${url.origin}/.well-known/oauth-protected-resource${path}`] : []),+ `${url.origin}/.well-known/oauth-protected-resource`+ ];+};++// The order the MCP authorization spec gives for an issuer with and without a path.+export const authorizationServerMetadataUrls = (issuer: string): string[] => {+ const url = new URL(issuer);+ const path = stripTrailingSlash(url.pathname);+ if (!path) {+ return [`${url.origin}/.well-known/oauth-authorization-server`, `${url.origin}/.well-known/openid-configuration`];+ }+ return [+ `${url.origin}/.well-known/oauth-authorization-server${path}`,+ `${url.origin}/.well-known/openid-configuration${path}`,+ `${url.origin}${path}/.well-known/openid-configuration`+ ];+};++// The resource a token is bound to has to cover the server we broker. A prefix on the same origin covers it+// (a server at /mcp/v2 protected as /mcp); another origin never does.+export const checkProtectedResource = (+ serverUrl: string,+ resource: unknown+): { resource: string; compatibility: AgentVaultOauthCompatibility | null } => {+ if (resource === undefined || resource === null) {+ return { resource: serverUrl, compatibility: AgentVaultOauthCompatibility.ResourceMissing };+ }+ if (!isHttpsUrl(resource)) {+ throw oauthSetupError(serverUrl, "its protected resource metadata names a resource that isn't an https URL.");+ }++ const server = new URL(serverUrl);+ const advertised = new URL(resource);+ if (advertised.origin !== server.origin) {+ throw oauthSetupError(+ serverUrl,+ `its protected resource metadata is for '${advertised.host}', a different server. Check the server URL.`+ );+ }++ const serverPath = stripTrailingSlash(server.pathname);+ const resourcePath = stripTrailingSlash(advertised.pathname);+ if (serverPath === resourcePath) return { resource, compatibility: null };+ if (!resourcePath || serverPath.startsWith(`${resourcePath}/`)) {+ return { resource, compatibility: AgentVaultOauthCompatibility.ResourcePrefix };+ }+ throw oauthSetupError(+ serverUrl,+ "its protected resource metadata is for a path that doesn't cover this server URL. Check the server URL."+ );+};++// RFC 8414 section 3.3: an issuer that differs from the one the metadata was fetched for is a mix-up attack.+// A trailing slash is the one difference accepted, since servers disagree on it.+export const checkIssuer = (+ serverUrl: string,+ expected: string,+ advertised: unknown+): AgentVaultOauthCompatibility | null => {+ if (advertised === expected) return null;+ if (typeof advertised === "string" && stripTrailingSlash(advertised) === stripTrailingSlash(expected)) {+ return AgentVaultOauthCompatibility.IssuerTrailingSlash;+ }+ throw oauthSetupError(+ serverUrl,+ "its authorization server metadata names a different issuer than the one it was fetched from, so it can't be trusted."+ );+};++export const selectScopes = ({+ challengeScope,+ scopesSupported,+ authorizationServerScopes+}: {+ challengeScope?: string;+ scopesSupported?: unknown;+ authorizationServerScopes?: unknown;+}): string[] => {+ let scopes = splitScopes(challengeScope);+ if (!scopes.length && Array.isArray(scopesSupported)) {+ scopes = scopesSupported.filter(isOauthScopeToken);+ }+ const offline =+ Array.isArray(authorizationServerScopes) && authorizationServerScopes.includes(OFFLINE_ACCESS_SCOPE)+ ? [OFFLINE_ACCESS_SCOPE]+ : [];+ return [...new Set([...scopes, ...offline])];+};++export const discoverOauthServer = async (http: TOauthHttpClient, serverUrl: string): Promise<TOauthDiscovery> => {+ const compatibility = new Set<AgentVaultOauthCompatibility>();++ let challenge: Record<string, string> | null = null;+ try {+ challenge = parseBearerChallenge((await http.probe(serverUrl)).wwwAuthenticate);+ } catch {+ // The challenge only says where to look first; the well-known locations below still apply.+ logger.info(`agentVaultOauth: MCP server probe failed [server=${describeServer(serverUrl)}]`);+ }++ let protectedResource: Record<string, unknown> | null = null;+ // eslint-disable-next-line no-restricted-syntax+ for (const url of protectedResourceMetadataUrls(serverUrl, challenge?.resource_metadata)) {+ // eslint-disable-next-line no-await-in-loop+ const candidate = await fetchJson(http, url);+ if (candidate && Array.isArray(candidate.authorization_servers)) {+ protectedResource = candidate;+ break;+ }+ }++ let resource = serverUrl;+ let issuer = new URL(serverUrl).origin;+ if (protectedResource) {+ const checked = checkProtectedResource(serverUrl, protectedResource.resource);+ resource = checked.resource;+ if (checked.compatibility) compatibility.add(checked.compatibility);++ const [firstServer] = protectedResource.authorization_servers as unknown[];+ if (!isHttpsUrl(firstServer)) {+ throw oauthSetupError(serverUrl, "its protected resource metadata names no https authorization server.");+ }+ issuer = firstServer;+ } else {+ // The 2025-03-26 spec behavior: the MCP server's origin is its own authorization server.+ compatibility.add(AgentVaultOauthCompatibility.NoProtectedResourceMetadata);+ }++ let metadata: Record<string, unknown> | null = null;+ // eslint-disable-next-line no-restricted-syntax+ for (const url of authorizationServerMetadataUrls(issuer)) {+ // eslint-disable-next-line no-await-in-loop+ metadata = await fetchJson(http, url);+ if (metadata) break;+ }++ const scopes = selectScopes({+ challengeScope: challenge?.scope,+ scopesSupported: protectedResource?.scopes_supported,+ authorizationServerScopes: metadata?.scopes_supported+ });++ if (!metadata) {+ compatibility.add(AgentVaultOauthCompatibility.NoAuthorizationServerMetadata);+ compatibility.add(AgentVaultOauthCompatibility.PkceUnadvertised);+ const { origin } = new URL(issuer);+ return {+ issuer,+ authorizationEndpoint: `${origin}/authorize`,+ tokenEndpoint: `${origin}/token`,+ registrationEndpoint: `${origin}/register`,+ endpointsGuessed: true,+ resource,+ scopes,+ issParameterSupported: false,+ tokenEndpointAuthMethodsSupported: null,+ compatibility: [...compatibility]+ };+ }++ const issuerCompatibility = checkIssuer(serverUrl, issuer, metadata.issuer);+ if (issuerCompatibility) compatibility.add(issuerCompatibility);++ const authorizationEndpoint = metadata.authorization_endpoint;+ const tokenEndpoint = metadata.token_endpoint;+ const registrationEndpoint = metadata.registration_endpoint;+ if (!isHttpsUrl(authorizationEndpoint) || !isHttpsUrl(tokenEndpoint)) {+ throw oauthSetupError(+ serverUrl,+ "its authorization server metadata needs https authorization and token endpoints without usernames, passwords or fragments. Ask the MCP server administrator to correct its OAuth metadata."+ );+ }++ const challengeMethods = metadata.code_challenge_methods_supported;+ if (Array.isArray(challengeMethods)) {+ if (!challengeMethods.includes("S256")) {+ throw oauthSetupError(+ serverUrl,+ "its authorization server doesn't support PKCE with S256, which the MCP authorization spec requires."+ );+ }+ } else {+ compatibility.add(AgentVaultOauthCompatibility.PkceUnadvertised);+ }++ const authMethods = metadata.token_endpoint_auth_methods_supported;+ return {+ issuer,+ authorizationEndpoint,+ tokenEndpoint,+ registrationEndpoint: isHttpsUrl(registrationEndpoint) ? registrationEndpoint : null,+ endpointsGuessed: false,+ resource,+ scopes,+ issParameterSupported: metadata.authorization_response_iss_parameter_supported === true,+ tokenEndpointAuthMethodsSupported: Array.isArray(authMethods)+ ? authMethods.filter((method): method is string => typeof method === "string")+ : null,+ compatibility: [...compatibility]+ };+};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.tsnew file mode 100644index 0000000000..bbfe1a76f2--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.ts@@ -0,0 +1,115 @@+import { Readable } from "node:stream";++import { safeRequest } from "@app/lib/validator";++export type TOauthHttpResponse = {+ status: number;+ contentType: string;+ body: string;+};++// Narrow on purpose, so the OAuth fns are tested against stubbed servers without a network.+export type TOauthHttpClient = {+ get: (url: string) => Promise<TOauthHttpResponse>;+ postForm: (+ url: string,+ form: URLSearchParams,+ headers?: Record<string, string>,+ options?: { timeoutMs?: number }+ ) => Promise<TOauthHttpResponse>;+ postJson: (url: string, body: unknown) => Promise<TOauthHttpResponse>;+ // An unauthenticated MCP request, for the `WWW-Authenticate` challenge only. The body is never read.+ probe: (url: string) => Promise<{ status: number; wwwAuthenticate: string | null }>;+};++const TIMEOUT_MS = 10_000;+const MAX_BODY_BYTES = 1024 * 1024;++const headerValue = (value: unknown): string => {+ if (Array.isArray(value)) return value.join(", ");+ return typeof value === "string" ? value : "";+};++// Redirects are never followed (safeRequest pins maxRedirects to 0), so a metadata URL or token endpoint can't+// bounce a request carrying a code or a client secret to another host.+export const agentVaultOauthHttpClient: TOauthHttpClient = {+ get: async (url) => {+ const response = await safeRequest.get<string>(url, {+ timeout: TIMEOUT_MS,+ signal: AbortSignal.timeout(TIMEOUT_MS),+ maxContentLength: MAX_BODY_BYTES,+ responseType: "text",+ transformResponse: (data: string) => data,+ validateStatus: () => true,+ headers: { Accept: "application/json" }+ });+ return {+ status: response.status,+ contentType: headerValue(response.headers["content-type"]),+ body: response.data ?? ""+ };+ },+ postForm: async (url, form, headers = {}, options = {}) => {+ const timeoutMs = Math.max(1, Math.min(options.timeoutMs ?? TIMEOUT_MS, TIMEOUT_MS));+ const response = await safeRequest.post<string>(url, form.toString(), {+ timeout: timeoutMs,+ "axios-retry": { retries: 0 },+ // axios's timeout restarts on socket activity, so a server trickling bytes could outlast it.+ signal: AbortSignal.timeout(timeoutMs),+ maxContentLength: MAX_BODY_BYTES,+ responseType: "text",+ transformResponse: (data: string) => data,+ validateStatus: () => true,+ headers: { ...headers, Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" }+ });+ return {+ status: response.status,+ contentType: headerValue(response.headers["content-type"]),+ body: response.data ?? ""+ };+ },+ postJson: async (url, body) => {+ const response = await safeRequest.post<string>(url, JSON.stringify(body), {+ timeout: TIMEOUT_MS,+ signal: AbortSignal.timeout(TIMEOUT_MS),+ "axios-retry": { retries: 0 },+ maxContentLength: MAX_BODY_BYTES,+ responseType: "text",+ transformResponse: (data: string) => data,+ validateStatus: () => true,+ headers: { Accept: "application/json", "Content-Type": "application/json" }+ });+ return {+ status: response.status,+ contentType: headerValue(response.headers["content-type"]),+ body: response.data ?? ""+ };+ },+ probe: async (url) => {+ const response = await safeRequest.post<Readable>(+ url,+ JSON.stringify({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: "2025-06-18",+ capabilities: {},+ clientInfo: { name: "Infisical Agent Vault", version: "1.0.0" }+ }+ }),+ {+ timeout: TIMEOUT_MS,+ signal: AbortSignal.timeout(TIMEOUT_MS),+ "axios-retry": { retries: 0 },+ // A server that needs no auth answers with a stream that may never end, so the body is dropped unread.+ responseType: "stream",+ validateStatus: () => true,+ headers: { Accept: "application/json, text/event-stream", "Content-Type": "application/json" }+ }+ );+ response.data?.destroy?.();+ const challenge = headerValue(response.headers["www-authenticate"]);+ return { status: response.status, wwwAuthenticate: challenge || null };+ }+};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.tsnew file mode 100644index 0000000000..2a286a34de--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.ts@@ -0,0 +1,1288 @@+import crypto from "node:crypto";++import { createMongoAbility } from "@casl/ability";+import { beforeEach, describe, expect, test, vi } from "vitest";++import {+ ProjectPermissionAgentVaultAccessBundleActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";+import { ActorType } from "@app/services/auth/auth-type";++import {+ AgentVaultCredentialType,+ AgentVaultOauthAuthorizationStatus,+ AgentVaultOauthStatus,+ AgentVaultServiceType+} from "../agent-vault/agent-vault-enums";+import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";+import {+ agentVaultOauthServiceFactory,+ checkOauthClaimUnderLock,+ checkOauthServerUnderLock+} from "./agent-vault-oauth-service";+import { hashAccessToken } from "./agent-vault-oauth-token-fns";+import {+ AgentVaultOauthClientAuthMethod,+ AgentVaultOauthCompatibility,+ AgentVaultOauthRegistration,+ TAgentVaultOauthAuthorization,+ TAgentVaultOauthConfig,+ TAgentVaultOauthSecret+} from "./agent-vault-oauth-types";++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ SITE_URL: "https://app.infisical.test" }) }));++vi.mock("@app/lib/logger", async () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ sanitizeUrlForLog: (+ await vi.importActual<typeof import("@app/lib/logger/sanitize-url")>("@app/lib/logger/sanitize-url")+ ).sanitizeUrlForLog+}));++const PROJECT_ID = "11111111-1111-4111-8111-111111111111";+const BUNDLE_ID = "22222222-2222-4222-8222-222222222222";+const SERVICE_ID = "33333333-3333-4333-8333-333333333333";+const USER_ID = "44444444-4444-4444-8444-444444444444";+const OTHER_USER_ID = "55555555-5555-4555-8555-555555555555";+const SERVER_URL = "https://mcp.linear.app/mcp";+const REDIRECT_URI = "https://app.infisical.test/agent-vault/oauth/callback";+const DESTINATION = { hostPattern: "mcp.linear.app", serverUrl: SERVER_URL };++const ctxOf = (actorId: string) => ({+ actor: ActorType.USER,+ actorId,+ actorOrgId: "org-1",+ actorAuthMethod: null+});++const json = (status: number, body: unknown): TOauthHttpResponse => ({+ status,+ contentType: "application/json",+ body: JSON.stringify(body)+});++// The fake cipher is reversible and visibly "sealed", so a test can tell sealed bytes from plaintext.+const SEAL_PREFIX = Buffer.from("sealed:");+const sealBytes = (value: unknown) => Buffer.concat([SEAL_PREFIX, Buffer.from(JSON.stringify(value))]);+const openBytes = <T>(blob: Buffer) => JSON.parse(blob.subarray(SEAL_PREFIX.length).toString("utf-8")) as T;++type TRow = {+ id: string;+ name: string;+ type: string;+ accessBundleId: string;+ credentialType: string;+ credentialConfig: unknown;+ encryptedCredential: Buffer | null;+ hostPattern?: string;+ config?: unknown;+};++const LINEAR_JSON: Record<string, unknown> = {+ "https://mcp.linear.app/.well-known/oauth-protected-resource/mcp": {+ resource: SERVER_URL,+ authorization_servers: ["https://mcp.linear.app"],+ scopes_supported: ["read", "write"]+ },+ "https://mcp.linear.app/.well-known/oauth-authorization-server": {+ issuer: "https://mcp.linear.app",+ authorization_endpoint: "https://mcp.linear.app/authorize",+ token_endpoint: "https://mcp.linear.app/token",+ registration_endpoint: "https://mcp.linear.app/register",+ code_challenge_methods_supported: ["S256"],+ authorization_response_iss_parameter_supported: true+ }+};++const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown> } = {}) => {+ const store = new Map<string, string>();+ const ttls = new Map<string, number>();+ const rows = new Map<string, TRow>();+ const tokenRequests: URLSearchParams[] = [];+ const registrations: unknown[] = [];+ let registerHandler: () => TOauthHttpResponse = () => json(201, { client_id: "registered-client" });+ let tokenHandler: (form: URLSearchParams) => TOauthHttpResponse = () =>+ json(200, { access_token: "at-1", token_type: "Bearer", refresh_token: "rt-1", expires_in: 3600, scope: "read" });++ const http: TOauthHttpClient = {+ probe: async () => ({+ status: 401,+ wwwAuthenticate: `Bearer resource_metadata="https://mcp.linear.app/.well-known/oauth-protected-resource/mcp"`+ }),+ get: async (url) =>+ url in metadata ? json(200, metadata[url]) : { status: 404, contentType: "text/plain", body: "" },+ postJson: async (_url, body) => {+ registrations.push(body);+ return registerHandler();+ },+ postForm: async (_url, form) => {+ tokenRequests.push(form);+ return tokenHandler(form);+ }+ };++ let decrypts = 0;+ const kms = {+ createCipherPairWithDataKey: async () => ({+ encryptor: ({ plainText }: { plainText: Buffer }) => ({+ cipherTextBlob: Buffer.concat([SEAL_PREFIX, plainText])+ }),+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => {+ decrypts += 1;+ return cipherTextBlob.subarray(SEAL_PREFIX.length);+ }+ })+ };++ const service = agentVaultOauthServiceFactory({+ http,+ keyStore: {+ getItemPrimary: async (key: string) => store.get(key) ?? null,+ setItemWithExpiry: async (key: string, ttl: number | string, value: string | number | Buffer) => {+ store.set(key, String(value));+ ttls.set(key, Number(ttl));+ return "OK" as const;+ },+ setItemWithExpiryNX: async (key: string, _ttl: number | string, value: string | number | Buffer) => {+ if (store.has(key)) return null;+ store.set(key, String(value));+ return "OK" as const;+ },+ deleteItem: async (key: string) => (store.delete(key) ? 1 : 0),+ ttl: async (key: string) => (store.has(key) ? (ttls.get(key) ?? -1) : -2),+ acquireLock: async () => ({ release: async () => ({}) as never })+ },+ kmsService: kms as never,+ agentVaultServiceDAL: {+ findByIdInAccessBundle: async ({ id }: { id: string }) => rows.get(id) as never,+ findByIdPrimary: async (id: string) => {+ const row = rows.get(id);+ return (row ? { ...row, credentialConfig: structuredClone(row.credentialConfig) } : undefined) as never;+ },+ // Mirrors the SQL: the compare is on the sealed credential only, and `keepStatus` is decided on the row+ // being written.+ compareAndSwapCredential: async ({+ id,+ expectedEncryptedCredential,+ encryptedCredential,+ credentialConfigPatch,+ keepStatus+ }: {+ id: string;+ expectedEncryptedCredential: Buffer;+ encryptedCredential?: Buffer;+ credentialConfigPatch: Record<string, unknown>;+ keepStatus?: { status: string; keys: string[] };+ }) => {+ const row = rows.get(id);+ if (!row?.encryptedCredential?.equals(expectedEncryptedCredential)) return undefined;+ if (encryptedCredential) row.encryptedCredential = encryptedCredential;+ const stored = row.credentialConfig as Record<string, unknown>;+ const patch =+ keepStatus && stored.status === keepStatus.status+ ? Object.fromEntries(+ Object.entries(credentialConfigPatch).filter(+ ([key]) => key !== "status" && !keepStatus.keys.includes(key)+ )+ )+ : credentialConfigPatch;+ row.credentialConfig = { ...stored, ...patch };+ return {+ id,+ hostPattern: row.hostPattern ?? "",+ config: row.config ?? null,+ credentialConfig: structuredClone(row.credentialConfig)+ } as never;+ },+ // Mirrors the SQL: every condition and the union are evaluated on the row being written.+ addRequiredScopes: async ({+ id,+ expectedEncryptedCredential,+ rejectedTokenHash,+ requiredScopes+ }: {+ id: string;+ expectedEncryptedCredential: Buffer;+ rejectedTokenHash: string;+ requiredScopes: string[];+ }) => {+ // Lets a concurrent report run between the caller's read and this write.+ await new Promise((resolve) => {+ setImmediate(resolve);+ });+ const row = rows.get(id);+ const stored = row?.credentialConfig as TAgentVaultOauthConfig | undefined;+ if (+ !row?.encryptedCredential?.equals(expectedEncryptedCredential) ||+ row.credentialType !== AgentVaultCredentialType.OAuth ||+ stored?.accessTokenHash !== rejectedTokenHash ||+ stored.status === AgentVaultOauthStatus.NeedsReauthorization+ ) {+ return undefined;+ }+ const existing = stored.requiredScopes ?? [];+ row.credentialConfig = {+ ...stored,+ status: AgentVaultOauthStatus.NeedsAdditionalScopes,+ requiredScopes: [...existing, ...[...new Set(requiredScopes)].filter((scope) => !existing.includes(scope))]+ };+ return {+ id,+ hostPattern: row.hostPattern ?? "",+ config: row.config ?? null,+ credentialConfig: structuredClone(row.credentialConfig)+ } as never;+ }+ },+ agentVaultAccessBundleDAL: {+ findByIdInProject: async ({ id }: { id: string }) => (id === BUNDLE_ID ? ({ id } as never) : undefined)+ },+ permissionService: {+ getProjectPermission: async () =>+ ({+ permission: createMongoAbility([+ {+ action: ProjectPermissionAgentVaultAccessBundleActions.Edit,+ subject: ProjectPermissionSub.AgentVaultAccessBundles+ }+ ]),+ hasRole: () => true,+ memberships: []+ }) as never+ },+ membershipDAL: { findResourceMembershipsForActor: async () => [] }+ });++ return {+ service,+ store,+ ttls,+ rows,+ tokenRequests,+ registrations,+ kms,+ decrypts: () => decrypts,+ onToken: (handler: typeof tokenHandler) => {+ tokenHandler = handler;+ },+ onRegister: (handler: typeof registerHandler) => {+ registerHandler = handler;+ }+ };+};++const createAuthorization = (env: ReturnType<typeof setup>, extra: Record<string, string> = {}) =>+ env.service.createAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ accessBundleId: BUNDLE_ID,+ serverUrl: SERVER_URL,+ ...extra+ });++const authorize = async (env: ReturnType<typeof setup>) => {+ const { authorization } = await createAuthorization(env);+ const state = new URL(authorization!.authorizeUrl).searchParams.get("state")!;+ await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state,+ code: "code-1",+ iss: "https://mcp.linear.app"+ });+ return authorization!.id;+};++describe("starting an authorization", () => {+ test("discovers, registers a client, and returns an authorize URL with PKCE S256, resource and state", async () => {+ const env = setup();+ const result = await createAuthorization(env);++ expect(result.registrationRequired).toBe(false);+ const { authorization } = result;+ const url = new URL(authorization!.authorizeUrl);+ expect(url.origin + url.pathname).toBe("https://mcp.linear.app/authorize");+ expect(url.searchParams.get("client_id")).toBe("registered-client");+ expect(url.searchParams.get("code_challenge_method")).toBe("S256");+ expect(url.searchParams.get("resource")).toBe(SERVER_URL);+ expect(url.searchParams.get("redirect_uri")).toBe(REDIRECT_URI);+ expect(url.searchParams.get("state")!.startsWith(`${authorization!.id}.`)).toBe(true);+ expect(authorization!.scopes).toEqual(["read", "write"]);+ expect(authorization!.status).toBe(AgentVaultOauthAuthorizationStatus.Pending);+ expect(env.registrations).toHaveLength(1);++ // The PKCE verifier is sealed in Redis, never stored in plaintext.+ const raw = env.store.get(`agent-vault-oauth-authorization:${authorization!.id}`)!;+ expect(raw).not.toContain("codeVerifier");+ });++ test("a server without a registration endpoint asks for a client", async () => {+ const env = setup({+ metadata: {+ ...LINEAR_JSON,+ "https://mcp.linear.app/.well-known/oauth-authorization-server": {+ ...(LINEAR_JSON["https://mcp.linear.app/.well-known/oauth-authorization-server"] as object),+ registration_endpoint: undefined+ }+ }+ });+ expect(await createAuthorization(env)).toEqual({+ registrationRequired: true,+ redirectUri: REDIRECT_URI,+ registrationError: null,+ authorization: null+ });+ });++ test("a registration endpoint that refuses asks for a client, with the reason naming the host only", async () => {+ const env = setup();+ env.onRegister(() => json(400, { error: "invalid_redirect_uri", error_description: "Redirect URI not allowed" }));++ const result = await createAuthorization(env);+ expect(result).toEqual({+ registrationRequired: true,+ redirectUri: REDIRECT_URI,+ registrationError:+ "Couldn't set up OAuth for 'mcp.linear.app': its registration endpoint refused to register Infisical as a client (Redirect URI not allowed). Enter the client ID and secret of your own OAuth app instead.",+ authorization: null+ });+ expect(result.registrationError).not.toContain("/mcp");+ });++ test("a registration endpoint that can't be reached says so without the error text", async () => {+ const env = setup();+ env.onRegister(() => {+ throw new Error("connect ECONNREFUSED https://mcp.linear.app/register?token=abc");+ });+ const result = await createAuthorization(env);+ expect(result.registrationRequired).toBe(true);+ expect(result.registrationError).toBe(+ "Couldn't set up OAuth for 'mcp.linear.app': its registration endpoint couldn't be reached. Enter the client ID and secret of your own OAuth app instead."+ );+ });++ test("a successful start has no registration error", async () => {+ expect((await createAuthorization(setup())).registrationError).toBeNull();+ });++ test("an admin-entered client is used as is, with no registration", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env, { clientId: "my-app", clientSecret: "shh" });+ expect(new URL(authorization!.authorizeUrl).searchParams.get("client_id")).toBe("my-app");+ expect(env.registrations).toHaveLength(0);+ });++ test("a client secret without a client ID is refused", async () => {+ await expect(createAuthorization(setup(), { clientSecret: "shh" })).rejects.toThrow(/client ID/);+ });++ test("an unknown bundle is a 404", async () => {+ const env = setup();+ await expect(+ env.service.createAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ accessBundleId: "99999999-9999-4999-8999-999999999999",+ serverUrl: SERVER_URL+ })+ ).rejects.toThrow(/not found/);+ });+});++describe("completing an authorization", () => {+ test("the creator cannot read, complete or claim an authorization through a different project", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ const projectId = "99999999-9999-4999-8999-999999999999";+ const state = new URL(authorization!.authorizeUrl).searchParams.get("state")!;+ await expect(+ env.service.getAuthorization({ projectId, ctx: ctxOf(USER_ID), authorizationId: authorization!.id })+ ).rejects.toThrow(NotFoundError);+ await expect(+ env.service.completeAuthorization({+ projectId,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state,+ code: "code-1"+ })+ ).rejects.toThrow(NotFoundError);+ await expect(+ env.service.claimAuthorization({+ projectId,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ accessBundleId: BUNDLE_ID,+ serverUrl: SERVER_URL+ })+ ).rejects.toThrow(NotFoundError);+ expect(env.tokenRequests).toHaveLength(0);+ expect(env.store.size).toBe(1);+ });++ test("exchanges the code with the PKCE verifier and resource, and never returns a token", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ const url = new URL(authorization!.authorizeUrl);++ const { authorization: view } = await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state: url.searchParams.get("state")!,+ code: "code-1",+ iss: "https://mcp.linear.app"+ });++ expect(view).toEqual({+ id: authorization!.id,+ status: AgentVaultOauthAuthorizationStatus.Authorized,+ error: null,+ scopes: ["read"]+ });+ const [form] = env.tokenRequests;+ expect(form.get("grant_type")).toBe("authorization_code");+ expect(form.get("code")).toBe("code-1");+ expect(form.get("resource")).toBe(SERVER_URL);+ expect(form.get("redirect_uri")).toBe(REDIRECT_URI);+ expect(crypto.createHash("sha256").update(form.get("code_verifier")!).digest("base64url")).toBe(+ url.searchParams.get("code_challenge")+ );+ expect(+ JSON.stringify(+ await env.service.getAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id+ })+ )+ ).not.toContain("at-1");+ });++ test("another user gets a 404, and a wrong state a 400", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ const state = new URL(authorization!.authorizeUrl).searchParams.get("state")!;++ await expect(+ env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(OTHER_USER_ID),+ authorizationId: authorization!.id,+ state,+ code: "c"+ })+ ).rejects.toThrow(/not found/);+ await expect(+ env.service.getAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(OTHER_USER_ID),+ authorizationId: authorization!.id+ })+ ).rejects.toThrow(/not found/);+ await expect(+ env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state: `${authorization!.id}.forged`,+ code: "c"+ })+ ).rejects.toThrow(/doesn't belong/);+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("an iss from another server fails it before the code is used", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ const { authorization: view } = await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state: new URL(authorization!.authorizeUrl).searchParams.get("state")!,+ code: "c",+ iss: "https://evil.example.com"+ });+ expect(view.status).toBe(AgentVaultOauthAuthorizationStatus.Failed);+ expect(view.error).toMatch(/different server/);+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("a missing iss from a server that advertises it fails", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ const { authorization: view } = await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state: new URL(authorization!.authorizeUrl).searchParams.get("state")!,+ code: "c"+ });+ expect(view.status).toBe(AgentVaultOauthAuthorizationStatus.Failed);+ });++ test("a multi-line or long reason from the provider still fails the authorization, normalized", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ const view = await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state: new URL(authorization!.authorizeUrl).searchParams.get("state")!,+ error: "server_error",+ errorDescription: `The admin\r\n\tdisabled\u202e this app. ${"x".repeat(3000)}`+ });+ expect(view.authorization.status).toBe(AgentVaultOauthAuthorizationStatus.Failed);+ expect(view.authorization.error).toMatch(+ /^'mcp\.linear\.app' didn't authorize Infisical: The admin disabled this app\. x+$/+ );+ expect(view.authorization.error!.length).toBeLessThan(600);+ });++ test("a denied authorization and a failed exchange are readable failures, not errors", async () => {+ const denied = setup();+ const first = (await createAuthorization(denied)).authorization!;+ const deniedView = await denied.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: first.id,+ state: new URL(first.authorizeUrl).searchParams.get("state")!,+ error: "access_denied"+ });+ expect(deniedView.authorization.error).toBe("Access to 'mcp.linear.app' was denied, so nothing was connected.");++ const refused = setup();+ refused.onToken(() => json(400, { error: "invalid_grant", error_description: "Code expired" }));+ const second = (await createAuthorization(refused)).authorization!;+ const refusedView = await refused.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: second.id,+ state: new URL(second.authorizeUrl).searchParams.get("state")!,+ code: "c",+ iss: "https://mcp.linear.app"+ });+ expect(refusedView.authorization).toMatchObject({+ status: AgentVaultOauthAuthorizationStatus.Failed,+ error: "'mcp.linear.app' refused the token request: Code expired"+ });+ });++ test("an exchange refused with only an error code still stores a normalized reason", async () => {+ const env = setup();+ env.onToken(() => json(400, { error: "bad\u0000code" }));+ const { authorization } = await createAuthorization(env);+ const view = await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state: new URL(authorization!.authorizeUrl).searchParams.get("state")!,+ code: "test-authorization-code",+ iss: "https://mcp.linear.app"+ });+ expect(view.authorization.error).toBe("'mcp.linear.app' refused the token request: bad code");+ });++ test("comma-joined scopes from the exchange are granted as the scopes asked for, and recorded", async () => {+ const env = setup();+ env.onToken(() => json(200, { access_token: "at-1", token_type: "Bearer", scope: "read,write" }));+ const id = await authorize(env);+ const record = JSON.parse(env.store.get(`agent-vault-oauth-authorization:${id}`)!) as TAgentVaultOauthAuthorization;+ expect(record.grantedScopes).toEqual(["read", "write"]);+ expect(record.compatibility).toContain(AgentVaultOauthCompatibility.ScopeCommaSeparated);+ expect(record.expiresAt).toBeNull();+ });+});++describe("using an authorization", () => {+ const claimArgs = {+ projectId: PROJECT_ID,+ accessBundleId: BUNDLE_ID,+ ctx: ctxOf(USER_ID),+ serverUrl: SERVER_URL+ };++ test("only once it is authorized, and only for the same bundle, user and server URL", async () => {+ const env = setup();+ const { authorization } = await createAuthorization(env);+ await expect(env.service.claimAuthorization({ ...claimArgs, authorizationId: authorization!.id })).rejects.toThrow(+ /hasn't finished/+ );++ const id = await authorize(env);+ const otherPath = env.service.claimAuthorization({+ ...claimArgs,+ authorizationId: id,+ serverUrl: "https://mcp.linear.app/secret-key-in-path"+ });+ await expect(otherPath).rejects.toThrow(/Authorize again for the new URL/);+ await expect(otherPath).rejects.not.toThrow(/secret-key-in-path|\/mcp/);+ await expect(+ env.service.claimAuthorization({ ...claimArgs, authorizationId: id, serverUrl: "https://other.example.com/k" })+ ).rejects.toThrow("This authorization is for 'mcp.linear.app', but the service's server is 'other.example.com'.");+ await expect(+ env.service.claimAuthorization({ ...claimArgs, authorizationId: id, ctx: ctxOf(OTHER_USER_ID) })+ ).rejects.toThrow(/not found/);+ await expect(+ env.service.claimAuthorization({+ ...claimArgs,+ authorizationId: id,+ accessBundleId: "99999999-9999-4999-8999-999999999999"+ })+ ).rejects.toThrow(/different access bundle/);+ });++ test("a claim uses it up, and another claim is refused with a readable error", async () => {+ const env = setup();+ const id = await authorize(env);++ await expect(+ env.service.claimAuthorization({ ...claimArgs, authorizationId: id, ctx: ctxOf(OTHER_USER_ID) })+ ).rejects.toThrow(NotFoundError);+ const { record } = await env.service.claimAuthorization({ ...claimArgs, authorizationId: id });+ const { config, encryptedCredential } = env.service.buildCredentialFromAuthorization(record, {+ authorizedBy: { userId: USER_ID, username: "[email protected]" }+ });++ expect(openBytes<TAgentVaultOauthSecret>(encryptedCredential)).toEqual({+ accessToken: "at-1",+ refreshToken: "rt-1"+ });+ expect(config).toMatchObject({+ type: AgentVaultCredentialType.OAuth,+ status: AgentVaultOauthStatus.Connected,+ issuer: "https://mcp.linear.app",+ clientId: "registered-client",+ registration: AgentVaultOauthRegistration.Dynamic,+ grantedScopes: ["read"],+ accessTokenHash: hashAccessToken("at-1")+ });+ expect(env.store.size).toBe(0);+ await expect(env.service.claimAuthorization({ ...claimArgs, authorizationId: id })).rejects.toThrow(+ "It may have expired or was already used. Authorize the service again."+ );+ });++ test("two saves claiming it at once end with exactly one winner", async () => {+ const env = setup();+ const id = await authorize(env);++ const results = await Promise.allSettled([+ env.service.claimAuthorization({ ...claimArgs, authorizationId: id }),+ env.service.claimAuthorization({ ...claimArgs, authorizationId: id })+ ]);++ expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1);+ const [lost] = results.filter((result) => result.status === "rejected");+ expect(lost.reason).toBeInstanceOf(ConflictError);+ expect((lost.reason as Error).message).toBe(+ "This authorization was already used by another save. Authorize the service again."+ );+ });++ test("a failed save restores it exactly, with the TTL it had left, so a retry can use it", async () => {+ const env = setup();+ const id = await authorize(env);+ const [key] = [...env.store.keys()];+ const stored = env.store.get(key);+ env.ttls.set(key, 123);++ const first = await env.service.claimAuthorization({ ...claimArgs, authorizationId: id });+ expect(env.store.has(key)).toBe(false);+ await first.restore();++ expect(env.store.get(key)).toBe(stored);+ expect(env.ttls.get(key)).toBe(123);+ const retry = await env.service.claimAuthorization({ ...claimArgs, authorizationId: id });+ expect(retry.record).toEqual(first.record);+ });++ test("a validation failure consumes nothing, and a restore with no TTL left writes nothing", async () => {+ const env = setup();+ const id = await authorize(env);+ const [key] = [...env.store.keys()];++ await expect(+ env.service.claimAuthorization({+ ...claimArgs,+ authorizationId: id,+ accessBundleId: "99999999-9999-4999-8999-999999999999"+ })+ ).rejects.toThrow(/different access bundle/);+ expect(env.store.has(key)).toBe(true);++ env.ttls.set(key, -1);+ const claim = await env.service.claimAuthorization({ ...claimArgs, authorizationId: id });+ await claim.restore();+ expect(env.store.has(key)).toBe(false);+ });++ test("a reauthorization is tied to its service", async () => {+ const env = setup();+ env.rows.set(SERVICE_ID, {+ id: SERVICE_ID,+ name: "linear",+ type: AgentVaultServiceType.Mcp,+ accessBundleId: BUNDLE_ID,+ credentialType: AgentVaultCredentialType.Bearer,+ credentialConfig: {},+ encryptedCredential: sealBytes({ value: "pat" })+ });+ const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID });+ const state = new URL(authorization!.authorizeUrl).searchParams.get("state")!;+ await env.service.completeAuthorization({+ projectId: PROJECT_ID,+ ctx: ctxOf(USER_ID),+ authorizationId: authorization!.id,+ state,+ code: "c",+ iss: "https://mcp.linear.app"+ });+ await expect(env.service.claimAuthorization({ ...claimArgs, authorizationId: authorization!.id })).rejects.toThrow(+ /can't create a new one/+ );+ await expect(+ env.service.claimAuthorization({ ...claimArgs, authorizationId: authorization!.id, serviceId: SERVICE_ID })+ ).resolves.toBeDefined();+ });+});++const oauthConfig = (overrides: Partial<TAgentVaultOauthConfig> = {}): TAgentVaultOauthConfig => ({+ type: AgentVaultCredentialType.OAuth,+ grantType: "authorization_code",+ issuer: "https://mcp.linear.app",+ authorizationEndpoint: "https://mcp.linear.app/authorize",+ tokenEndpoint: "https://mcp.linear.app/token",+ resource: SERVER_URL,+ clientId: "registered-client",+ registration: AgentVaultOauthRegistration.Dynamic,+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None,+ compatibility: [],+ requestedScopes: ["read", "write"],+ grantedScopes: ["read"],+ requiredScopes: [],+ status: AgentVaultOauthStatus.Connected,+ expiresAt: new Date(Date.now() + 3600_000).toISOString(),+ accessTokenHash: hashAccessToken("old-access"),+ authorizedBy: { userId: USER_ID, username: "[email protected]" },+ authorizedAt: new Date().toISOString(),+ lastRefreshedAt: null,+ lastError: null,+ ...overrides+});++describe("refreshing a service's token", () => {+ let env: ReturnType<typeof setup>;+ const row = () => env.rows.get(SERVICE_ID)!;+ const config = () => row().credentialConfig as TAgentVaultOauthConfig;++ beforeEach(() => {+ env = setup();+ env.rows.set(SERVICE_ID, {+ id: SERVICE_ID,+ name: "linear",+ type: AgentVaultServiceType.Mcp,+ accessBundleId: BUNDLE_ID,+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: oauthConfig(),+ encryptedCredential: sealBytes({ accessToken: "old-access", refreshToken: "old-refresh" }),+ hostPattern: "mcp.linear.app",+ config: { serverUrl: SERVER_URL, transport: "streamable-http" }+ });+ });++ test("a rejected token that is no longer current returns the current one without calling the provider", async () => {+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("older-access")+ });+ expect(result.credential).toEqual({+ type: "bearer",+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "old-access",+ source: "oauth",+ expiresAt: config().expiresAt+ });+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("the current token rejected is refreshed with resource, and the old refresh token kept if none came back", async () => {+ env.onToken(() => json(200, { access_token: "new-access", token_type: "Bearer", expires_in: 600 }));+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });++ expect(result.credential.value).toBe("new-access");+ expect(result.status).toBe(AgentVaultOauthStatus.Connected);+ expect(Object.fromEntries(env.tokenRequests[0])).toEqual({+ grant_type: "refresh_token",+ refresh_token: "old-refresh",+ resource: SERVER_URL,+ client_id: "registered-client"+ });+ expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!)).toEqual({+ accessToken: "new-access",+ refreshToken: "old-refresh"+ });+ expect(config()).toMatchObject({ accessTokenHash: hashAccessToken("new-access"), lastError: null });+ expect(config().lastRefreshedAt).not.toBeNull();+ });++ test("a reauthorization that lands mid-refresh wins: the swap writes nothing and the newer token is returned", async () => {+ env.onToken(() => {+ // An admin reauthorized while the provider was answering.+ row().encryptedCredential = sealBytes({ accessToken: "reauthorized-access", refreshToken: "rt-new" });+ row().credentialConfig = oauthConfig({ accessTokenHash: hashAccessToken("reauthorized-access") });+ return json(200, { access_token: "stale-refresh-access", token_type: "Bearer", expires_in: 600 });+ });++ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });++ expect(result.credential.value).toBe("reauthorized-access");+ expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!).accessToken).toBe("reauthorized-access");+ });++ test("invalid_grant marks the service as needing reauthorization", async () => {+ env.onToken(() => json(400, { error: "invalid_grant" }));+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });+ expect(result.status).toBe(AgentVaultOauthStatus.NeedsReauthorization);+ expect(result.credential.value).toBe("old-access");+ expect(config().status).toBe(AgentVaultOauthStatus.NeedsReauthorization);+ expect(config().lastError).toMatch(/Reauthorize this service/);+ });++ test("any other failure records lastError and keeps the service connected", async () => {+ env.onToken(() => json(503, { error: "temporarily_unavailable" }));+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });+ expect(result.status).toBe(AgentVaultOauthStatus.Connected);+ expect(config().lastError).toBe("'mcp.linear.app' refused the token request: temporarily_unavailable");+ expect(config().lastError).not.toContain("old-");+ });++ test("an error code jsonb can't hold (NUL, a lone surrogate) is normalized before it is stored", async () => {+ env.onToken(() => json(400, { error: "server\u0000_error\ud800" }));+ await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });+ expect(config().lastError).toBe("'mcp.linear.app' refused the token request: server _error");+ });++ test("an expires_in too large for a date is stored as no expiry instead of throwing", async () => {+ env.onToken(() => json(200, { access_token: "new-access", token_type: "Bearer", expires_in: 1e20 }));+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });+ expect(result.credential).toMatchObject({ value: "new-access", expiresAt: null });+ expect(config().expiresAt).toBeNull();+ });++ test("comma-joined granted scopes are split only as a recorded fallback", async () => {+ env.onToken(() => json(200, { access_token: "new-access", token_type: "Bearer", scope: "read,write" }));+ await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });+ expect(config().grantedScopes).toEqual(["read", "write"]);+ expect(config().compatibility).toEqual([AgentVaultOauthCompatibility.ScopeCommaSeparated]);+ });++ test("required scopes from a 403 mark it as needing them, with no refresh", async () => {+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["admin"]+ });+ expect(result.status).toBe(AgentVaultOauthStatus.NeedsAdditionalScopes);+ expect(config().requiredScopes).toEqual(["admin"]);+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("required scopes for a token that was already replaced change nothing", async () => {+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("older-access"),+ requiredScopes: ["admin"]+ });+ expect(result.status).toBe(AgentVaultOauthStatus.Connected);+ expect(result.credential.value).toBe("old-access");+ expect(config().status).toBe(AgentVaultOauthStatus.Connected);+ expect(config().requiredScopes).toEqual([]);+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("required scopes never override needs reauthorization", async () => {+ row().credentialConfig = oauthConfig({+ status: AgentVaultOauthStatus.NeedsReauthorization,+ lastError: "revoked"+ });+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["admin"]+ });+ expect(result.status).toBe(AgentVaultOauthStatus.NeedsReauthorization);+ expect(config().status).toBe(AgentVaultOauthStatus.NeedsReauthorization);+ expect(config().requiredScopes).toEqual([]);+ });++ test("a refresh opens the stored credential once and builds one project cipher", async () => {+ const createCipher = vi.spyOn(env.kms, "createCipherPairWithDataKey");+ env.onToken(() => json(200, { access_token: "new-access", token_type: "Bearer", expires_in: 600 }));+ await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });+ expect(createCipher).toHaveBeenCalledTimes(1);+ expect(env.decrypts()).toBe(1);+ });++ test("lazy: a token valid past the horizon isn't refreshed, one expiring inside it is", async () => {+ await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ expiresWithinSeconds: 120+ });+ expect(env.tokenRequests).toHaveLength(0);++ row().credentialConfig = oauthConfig({ expiresAt: new Date(Date.now() + 30_000).toISOString() });+ env.onToken(() => json(200, { access_token: "new-access", token_type: "Bearer", refresh_token: "rt-2" }));+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ expiresWithinSeconds: 120+ });+ expect(result.credential.value).toBe("new-access");+ expect(result.credential.expiresAt).toBeNull();+ expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!).refreshToken).toBe("rt-2");+ });++ test("a service that moved to another host is a 409, with no provider call and no token", async () => {+ row().hostPattern = "mcp.other.example";+ row().config = { serverUrl: "https://mcp.other.example/mcp", transport: "streamable-http" };+ const result = env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: { hostPattern: "mcp.linear.app" },+ rejectedTokenHash: hashAccessToken("old-access")+ });+ await expect(result).rejects.toThrow(ConflictError);+ await expect(result).rejects.not.toThrow(/mcp\.other|mcp\.linear|\/mcp/);+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("a move that lands while the provider answers is a 409, though the refreshed tokens are stored", async () => {+ env.onToken(() => {+ row().hostPattern = "mcp.other.example";+ return json(200, { access_token: "new-access", token_type: "Bearer", expires_in: 600 });+ });+ await expect(+ env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: { hostPattern: "mcp.linear.app" },+ rejectedTokenHash: hashAccessToken("old-access")+ })+ ).rejects.toThrow(ConflictError);+ expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!).accessToken).toBe("new-access");+ });++ test("a reauthorization for another server mid-refresh is a 409, never the new server's token", async () => {+ env.onToken(() => {+ row().encryptedCredential = sealBytes({ accessToken: "other-server-access", refreshToken: "rt-other" });+ row().hostPattern = "mcp.other.example";+ return json(200, { access_token: "stale-refresh-access", token_type: "Bearer", expires_in: 600 });+ });+ await expect(+ env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: { hostPattern: "mcp.linear.app" },+ rejectedTokenHash: hashAccessToken("old-access")+ })+ ).rejects.toThrow(ConflictError);+ });++ test("resolve's destination also pins the server URL, so a path change on the same host is a 409", async () => {+ row().config = { serverUrl: "https://mcp.linear.app/v2/mcp", transport: "streamable-http" };+ await expect(+ env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ expiresWithinSeconds: 7200+ })+ ).rejects.toThrow(ConflictError);+ expect(env.tokenRequests).toHaveLength(0);+ });++ test("a scope report that lands mid-refresh keeps its warning after the refresh writes", async () => {+ env.onToken(() => {+ // The report changes only the config, so the refresh's compare on the sealed credential still passes.+ row().credentialConfig = {+ ...config(),+ status: AgentVaultOauthStatus.NeedsAdditionalScopes,+ requiredScopes: ["admin"]+ };+ return json(200, { access_token: "new-access", token_type: "Bearer", refresh_token: "rt-2", expires_in: 600 });+ });+ const result = await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access")+ });++ expect(result.status).toBe(AgentVaultOauthStatus.NeedsAdditionalScopes);+ expect(result.credential.value).toBe("new-access");+ expect(config()).toMatchObject({+ status: AgentVaultOauthStatus.NeedsAdditionalScopes,+ requiredScopes: ["admin"],+ accessTokenHash: hashAccessToken("new-access")+ });+ expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!).refreshToken).toBe("rt-2");+ });++ test("two scope reports for the same token at once both end up required", async () => {+ const report = (scopes: string[]) =>+ env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: scopes+ });+ await Promise.all([report(["admin"]), report(["write", "admin"])]);++ expect(config().status).toBe(AgentVaultOauthStatus.NeedsAdditionalScopes);+ expect([...config().requiredScopes].sort()).toEqual(["admin", "write"]);+ });++ test("a scope report keeps the scopes already required, without duplicates", async () => {+ row().credentialConfig = oauthConfig({+ status: AgentVaultOauthStatus.NeedsAdditionalScopes,+ requiredScopes: ["admin"]+ });+ await env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["write", "admin", "write"]+ });+ expect(config().requiredScopes).toEqual(["admin", "write"]);+ });++ test("a reauthorization needed after the report's read still isn't overridden by it", async () => {+ const liveRow = env.rows.get(SERVICE_ID)!;+ const result = env.service.refreshServiceToken({+ serviceId: SERVICE_ID,+ projectId: PROJECT_ID,+ destination: DESTINATION,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["admin"]+ });+ liveRow.credentialConfig = oauthConfig({+ status: AgentVaultOauthStatus.NeedsReauthorization,+ lastError: "revoked"+ });+ expect((await result).status).toBe(AgentVaultOauthStatus.NeedsReauthorization);+ expect(config().requiredScopes).toEqual([]);+ });+});++describe("building a credential from an authorization", () => {+ const record = (grantedScopes: string[]) =>+ ({+ issuer: "https://mcp.linear.app",+ authorizationEndpoint: "https://mcp.linear.app/authorize",+ tokenEndpoint: "https://mcp.linear.app/token",+ resource: SERVER_URL,+ clientId: "registered-client",+ registration: AgentVaultOauthRegistration.Dynamic,+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None,+ compatibility: [],+ requestedScopes: ["read", "write", "admin"],+ grantedScopes,+ expiresAt: null,+ accessTokenHash: hashAccessToken("at-1"),+ sealedCredential: sealBytes({ accessToken: "at-1" }).toString("base64")+ }) as unknown as TAgentVaultOauthAuthorization;+ const build = (grantedScopes: string[], previousRequiredScopes?: string[]) =>+ setup().service.buildCredentialFromAuthorization(record(grantedScopes), {+ authorizedBy: null,+ previousRequiredScopes+ }).config;++ test("a required scope the provider didn't grant keeps the service needing it", () => {+ expect(build(["read", "write"], ["admin", "write"])).toMatchObject({+ status: AgentVaultOauthStatus.NeedsAdditionalScopes,+ requiredScopes: ["admin"]+ });+ });++ test("records the server URL the tokens were authorized for", () => {+ const { config } = setup().service.buildCredentialFromAuthorization(+ { ...record(["read"]), serverUrl: SERVER_URL } as TAgentVaultOauthAuthorization,+ { authorizedBy: null }+ );+ expect(config.serverUrl).toBe(SERVER_URL);+ });++ test("once every required scope is granted it is connected, with nothing left required", () => {+ expect(build(["read", "admin"], ["admin"])).toMatchObject({+ status: AgentVaultOauthStatus.Connected,+ requiredScopes: []+ });+ expect(build(["read"])).toMatchObject({ status: AgentVaultOauthStatus.Connected, requiredScopes: [] });+ });+});++describe("a reauthorization checked under the bundle lock", () => {+ const authorizedAt = "2026-10-15T10:00:00.000Z";++ test("a service moved to another server since the claim refuses the save, naming hosts only", () => {+ const check = () =>+ checkOauthClaimUnderLock({+ authorizedServerUrl: "https://mcp.linear.app/mcp?k=secret",+ lockedServerUrl: "https://mcp.other.example/path/key",+ readOauth: { authorizedAt },+ lockedOauth: { authorizedAt, requiredScopes: [] }+ });+ expect(check).toThrow(BadRequestError);+ expect(check).toThrow(+ "This authorization is for 'mcp.linear.app', but the service's server is 'mcp.other.example'. Authorize again for the new URL."+ );+ });++ test("a newer reauthorization since the first read is kept, with a 409", () => {+ expect(() =>+ checkOauthClaimUnderLock({+ authorizedServerUrl: SERVER_URL,+ lockedServerUrl: SERVER_URL,+ readOauth: { authorizedAt },+ lockedOauth: { authorizedAt: "2026-10-15T10:05:00.000Z", requiredScopes: [] }+ })+ ).toThrow(ConflictError);+ });++ test("a refresh since the first read doesn't block it, and scopes reported meanwhile carry over", () => {+ expect(+ checkOauthClaimUnderLock({+ authorizedServerUrl: SERVER_URL,+ lockedServerUrl: SERVER_URL,+ readOauth: { authorizedAt },+ lockedOauth: { authorizedAt, requiredScopes: ["admin"] }+ })+ ).toEqual(["admin"]);+ expect(+ checkOauthClaimUnderLock({+ authorizedServerUrl: SERVER_URL,+ lockedServerUrl: SERVER_URL,+ readOauth: undefined,+ lockedOauth: undefined+ })+ ).toEqual([]);+ });+});++describe("an edit that keeps a service's OAuth tokens, checked under the bundle lock", () => {+ const OTHER_SERVER_URL = "https://mcp.other.example/mcp/key";++ test("an edit resending the old URL after a reauthorization for another server is a 409, naming hosts only", () => {+ const check = () =>+ checkOauthServerUnderLock({+ requestedServerUrl: SERVER_URL,+ readServerUrl: SERVER_URL,+ effectiveServerUrl: SERVER_URL,+ lockedOauth: { serverUrl: OTHER_SERVER_URL }+ });+ expect(check).toThrow(ConflictError);+ expect(check).toThrow(+ "This service was reauthorized for 'mcp.other.example' while this save was in progress, so its server can't be set back to 'mcp.linear.app'. Reload the service and save again."+ );+ });++ test("a path change on the same host is a 409 that doesn't print either path", () => {+ const check = () =>+ checkOauthServerUnderLock({+ requestedServerUrl: SERVER_URL,+ readServerUrl: SERVER_URL,+ effectiveServerUrl: SERVER_URL,+ lockedOauth: { serverUrl: "https://mcp.linear.app/v2/secret-path" }+ });+ expect(check).toThrow(ConflictError);+ expect(check).not.toThrow(/secret-path|\/mcp/);+ });++ test("a request that changes the URL itself without a new authorization is a 400", () => {+ expect(() =>+ checkOauthServerUnderLock({+ requestedServerUrl: OTHER_SERVER_URL,+ readServerUrl: SERVER_URL,+ effectiveServerUrl: OTHER_SERVER_URL,+ lockedOauth: { serverUrl: SERVER_URL }+ })+ ).toThrow(BadRequestError);+ });++ test("a URL that still matches the server the tokens are for passes", () => {+ expect(() =>+ checkOauthServerUnderLock({+ requestedServerUrl: SERVER_URL,+ readServerUrl: SERVER_URL,+ effectiveServerUrl: SERVER_URL,+ lockedOauth: { serverUrl: SERVER_URL }+ })+ ).not.toThrow();+ expect(() =>+ checkOauthServerUnderLock({+ requestedServerUrl: undefined,+ readServerUrl: SERVER_URL,+ effectiveServerUrl: SERVER_URL,+ lockedOauth: { serverUrl: SERVER_URL }+ })+ ).not.toThrow();+ });+});diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.tsnew file mode 100644index 0000000000..ec5bb89b37--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts@@ -0,0 +1,912 @@+import crypto from "node:crypto";++import { ForbiddenError } from "@casl/ability";++import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAgentVaultAccessBundleActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { KeyStorePrefixes, TKeyStoreFactory, TKeyStoreLock } from "@app/keystore/keystore";+import { getConfig } from "@app/lib/config/env";+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { ActorType } from "@app/services/auth/auth-type";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";++import {+ AgentVaultCredentialType,+ AgentVaultOauthAuthorizationStatus,+ AgentVaultOauthStatus,+ AgentVaultServiceType+} from "../agent-vault/agent-vault-enums";+import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import { TAgentVaultServiceConfig } from "../agent-vault/agent-vault-service-types";+import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";+import { TAgentVaultServiceDALFactory } from "../agent-vault-access-bundle/agent-vault-service-dal";+import {+ manualOauthClient,+ OauthRegistrationError,+ registerOauthClient,+ TOauthClient+} from "./agent-vault-oauth-client-fns";+import {+ describeServer,+ discoverOauthServer,+ oauthSetupError,+ OFFLINE_ACCESS_SCOPE+} from "./agent-vault-oauth-discovery-fns";+import { agentVaultOauthHttpClient, TOauthHttpClient } from "./agent-vault-oauth-http-fns";+import {+ buildAuthorizeUrl,+ decideRefresh,+ exchangeAuthorizationCode,+ expiresAtFrom,+ generatePkce,+ generateState,+ hashAccessToken,+ isSameState,+ normalizeProviderText,+ refreshAccessToken,+ validateCallbackIssuer,+ withTokenCompatibility+} from "./agent-vault-oauth-token-fns";+import {+ AGENT_VAULT_OAUTH_GRANT_TYPE,+ AGENT_VAULT_OAUTH_HEADER_NAME,+ AGENT_VAULT_OAUTH_HEADER_PREFIX,+ AgentVaultOauthRegistration,+ TAgentVaultOauthAuthorization,+ TAgentVaultOauthAuthorizationView,+ TAgentVaultOauthConfig,+ TAgentVaultOauthSecret,+ TClaimAuthorizationDTO,+ TCompleteAuthorizationDTO,+ TCreateAuthorizationDTO,+ TGetAuthorizationDTO,+ TRefreshServiceTokenDTO,+ TResolvedOauthCredential+} from "./agent-vault-oauth-types";++export const AGENT_VAULT_OAUTH_AUTHORIZATION_TTL_SECONDS = 10 * 60;+const COMPLETE_LOCK_TTL_SECONDS = 60;+// Outlasts the holder's work: the token requests share a 7 second budget.+const REFRESH_LOCK_DURATION_MS = 15 * 1000;+// Waits at most ~3s for a concurrent refresh of the same service, then answers with whatever is stored. With the+// token budget, the proxy's credential refresh answers inside its 15 second timeout.+const REFRESH_LOCK_SETTINGS = { retryCount: 12, retryDelay: 200, retryJitter: 50 };+export const AGENT_VAULT_OAUTH_CALLBACK_PATH = "/agent-vault/oauth/callback";++type TAgentVaultOauthServiceFactoryDep = {+ keyStore: Pick<+ TKeyStoreFactory,+ "getItemPrimary" | "setItemWithExpiry" | "setItemWithExpiryNX" | "deleteItem" | "ttl" | "acquireLock"+ >;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ agentVaultServiceDAL: Pick<+ TAgentVaultServiceDALFactory,+ "findByIdInAccessBundle" | "findByIdPrimary" | "compareAndSwapCredential" | "addRequiredScopes"+ >;+ agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "findByIdInProject">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;+ http?: TOauthHttpClient;+};++export type TAgentVaultOauthServiceFactory = ReturnType<typeof agentVaultOauthServiceFactory>;++type TProjectCipher = Awaited<ReturnType<TKmsServiceFactory["createCipherPairWithDataKey"]>>;++type TLoadedOauthService = {+ config: TAgentVaultOauthConfig;+ secret: TAgentVaultOauthSecret;+ encryptedCredential: Buffer;+ hostPattern: string;+ serverUrl: string | null;+};++export const AGENT_VAULT_SERVICE_MOVED_MESSAGE =+ "This service's server changed after the proxy last fetched it, so Infisical won't send its credential to the old host. The proxy picks up the change on its next poll.";++const serverUrlOf = (config: unknown) => (config as TAgentVaultServiceConfig | null)?.serverUrl ?? null;++// Names hosts only: a server URL's path or query can hold a key.+export const assertAuthorizationServerUrl = (authorizedServerUrl: string, serviceServerUrl: string | null) => {+ if (authorizedServerUrl === serviceServerUrl) return;+ const authorizedHost = describeServer(authorizedServerUrl);+ if (!serviceServerUrl) {+ throw new BadRequestError({+ message: `This authorization is for '${authorizedHost}', but the service has no server URL, so it can't use OAuth.`+ });+ }+ const serviceHost = describeServer(serviceServerUrl);+ throw new BadRequestError({+ message:+ authorizedHost === serviceHost+ ? `This authorization is for a different server URL on '${serviceHost}' than the service uses. Authorize again for the new URL.`+ : `This authorization is for '${authorizedHost}', but the service's server is '${serviceHost}'. Authorize again for the new URL.`+ });+};++export const OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE =+ "Changing an OAuth service's server URL needs a new authorization, since its tokens belong to the old server. Authorize the service for the new URL and send its 'authorizationId'.";++export const AGENT_VAULT_REAUTHORIZED_DURING_SAVE_MESSAGE =+ "This service was reauthorized by another save while this one was in progress, and that newer connection was kept. Reload the service, then authorize again if you still want to replace it.";++// Run under the bundle lock against the row read there, since a save that landed after the first read may have+// moved the service or reauthorized it. A newer reauthorization wins over a stale one, so an older authorization+// can't swap the account the service acts as back. A refresh doesn't count: it keeps `authorizedAt`, and its+// rotated tokens are what this save replaces anyway. Returns the required scopes still to carry over.+export const checkOauthClaimUnderLock = ({+ authorizedServerUrl,+ lockedServerUrl,+ readOauth,+ lockedOauth+}: {+ authorizedServerUrl: string;+ lockedServerUrl: string | null;+ readOauth: Pick<TAgentVaultOauthConfig, "authorizedAt"> | undefined;+ lockedOauth: Pick<TAgentVaultOauthConfig, "authorizedAt" | "requiredScopes"> | undefined;+}) => {+ assertAuthorizationServerUrl(authorizedServerUrl, lockedServerUrl);+ if ((readOauth?.authorizedAt ?? null) !== (lockedOauth?.authorizedAt ?? null)) {+ throw new ConflictError({ message: AGENT_VAULT_REAUTHORIZED_DURING_SAVE_MESSAGE });+ }+ return lockedOauth?.requiredScopes ?? [];+};++// For an edit that keeps the service's tokens, under the bundle lock: the server URL the save writes must still be+// the one those tokens were authorized for. A reauthorization for another server can commit between the first read+// and the lock, and merging this request's URL over it would send the new server's tokens to the old host.+export const checkOauthServerUnderLock = ({+ requestedServerUrl,+ readServerUrl,+ effectiveServerUrl,+ lockedOauth+}: {+ requestedServerUrl: string | undefined;+ readServerUrl: string | null;+ effectiveServerUrl: string | null;+ lockedOauth: Pick<TAgentVaultOauthConfig, "serverUrl">;+}) => {+ const boundServerUrl = lockedOauth.serverUrl;+ if (effectiveServerUrl === boundServerUrl) return;+ if (requestedServerUrl !== undefined && requestedServerUrl !== readServerUrl) {+ throw new BadRequestError({ message: OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE });+ }+ const boundHost = describeServer(boundServerUrl);+ const effectiveHost = effectiveServerUrl ? describeServer(effectiveServerUrl) : null;+ throw new ConflictError({+ message:+ effectiveHost && effectiveHost !== boundHost+ ? `This service was reauthorized for '${boundHost}' while this save was in progress, so its server can't be set back to '${effectiveHost}'. Reload the service and save again.`+ : `This service was reauthorized for a different server URL on '${boundHost}' while this save was in progress. Reload the service and save again.`+ });+};++const toView = (record: TAgentVaultOauthAuthorization): TAgentVaultOauthAuthorizationView => ({+ id: record.id,+ status: record.status,+ error: record.error,+ scopes:+ record.status === AgentVaultOauthAuthorizationStatus.Authorized ? record.grantedScopes : record.requestedScopes+});++export const agentVaultOauthServiceFactory = ({+ keyStore,+ kmsService,+ agentVaultServiceDAL,+ agentVaultAccessBundleDAL,+ permissionService,+ membershipDAL,+ http = agentVaultOauthHttpClient+}: TAgentVaultOauthServiceFactoryDep) => {+ const getProjectCipher = (projectId: string) =>+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });++ const sealWith = ({ encryptor }: TProjectCipher, value: unknown) =>+ encryptor({ plainText: Buffer.from(JSON.stringify(value)) }).cipherTextBlob;++ const openWith = <T>({ decryptor }: TProjectCipher, blob: Buffer): T =>+ JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as T;++ const seal = async (projectId: string, value: unknown) => sealWith(await getProjectCipher(projectId), value);++ const open = async <T>(projectId: string, blob: Buffer): Promise<T> =>+ openWith<T>(await getProjectCipher(projectId), blob);++ const redirectUri = () => {+ const { SITE_URL } = getConfig();+ if (!SITE_URL) {+ throw new BadRequestError({+ message:+ "OAuth needs this Infisical instance's SITE_URL to be set, since it is the redirect URI. Ask your administrator to set it."+ });+ }+ return `${SITE_URL}${AGENT_VAULT_OAUTH_CALLBACK_PATH}`;+ };++ const saveAuthorization = (record: TAgentVaultOauthAuthorization) =>+ keyStore.setItemWithExpiry(+ KeyStorePrefixes.AgentVaultOauthAuthorization(record.id),+ AGENT_VAULT_OAUTH_AUTHORIZATION_TTL_SECONDS,+ JSON.stringify(record)+ );++ const loadAuthorization = async (authorizationId: string) => {+ const raw = await keyStore.getItemPrimary(KeyStorePrefixes.AgentVaultOauthAuthorization(authorizationId));+ return raw ? { record: JSON.parse(raw) as TAgentVaultOauthAuthorization, raw } : null;+ };++ // Only its creator in the original project can see, complete or claim one. A different user or tenant gets+ // the same 404 as an unknown id.+ const loadOwnStoredAuthorization = async (+ authorizationId: string,+ ctx: TGetAuthorizationDTO["ctx"],+ projectId: string+ ) => {+ const stored = await loadAuthorization(authorizationId);+ if (+ !stored ||+ stored.record.projectId !== projectId ||+ ctx.actor !== ActorType.USER ||+ stored.record.actorUserId !== ctx.actorId+ ) {+ throw new NotFoundError({+ message: `Authorization with ID '${authorizationId}' not found. It may have expired or was already used. Authorize the service again.`+ });+ }+ return stored;+ };++ const loadOwnAuthorization = async (authorizationId: string, ctx: TGetAuthorizationDTO["ctx"], projectId: string) =>+ (await loadOwnStoredAuthorization(authorizationId, ctx, projectId)).record;++ const createAuthorization = async ({+ projectId,+ ctx,+ accessBundleId,+ serverUrl,+ serviceId,+ clientId,+ clientSecret+ }: TCreateAuthorizationDTO) => {+ const { permission, accessBundleIds } = await getAgentVaultReachability(+ { permissionService, membershipDAL },+ { projectId, ctx }+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );++ const bundle = await agentVaultAccessBundleDAL.findByIdInProject({ id: accessBundleId, projectId });+ if (!bundle || (accessBundleIds && !accessBundleIds.includes(accessBundleId.toLowerCase()))) {+ throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });+ }+ if (ctx.actor !== ActorType.USER) {+ throw new BadRequestError({+ message: "Only a user can authorize an OAuth connection, since it needs a browser."+ });+ }+ if (clientSecret && !clientId) {+ throw new BadRequestError({ message: "A client secret needs the client ID it belongs to." });+ }++ let stored: { config: TAgentVaultOauthConfig; clientSecret?: string } | null = null;+ if (serviceId) {+ const service = await agentVaultServiceDAL.findByIdInAccessBundle({ id: serviceId, accessBundleId: bundle.id });+ if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ if (service.type !== AgentVaultServiceType.Mcp) {+ throw new BadRequestError({+ message: `The service '${service.name}' is an HTTP service. Only MCP services use OAuth.`+ });+ }+ if (service.credentialType === AgentVaultCredentialType.OAuth && service.encryptedCredential) {+ const secret = await open<TAgentVaultOauthSecret>(projectId, service.encryptedCredential);+ stored = { config: service.credentialConfig as TAgentVaultOauthConfig, clientSecret: secret.clientSecret };+ }+ }++ const callbackUri = redirectUri();+ const discovery = await discoverOauthServer(http, serverUrl);+ const compatibility = [...discovery.compatibility];++ let client: TOauthClient;+ let registration: AgentVaultOauthRegistration;+ if (clientId) {+ client = manualOauthClient({+ clientId,+ clientSecret,+ tokenEndpointAuthMethodsSupported: discovery.tokenEndpointAuthMethodsSupported+ });+ registration = AgentVaultOauthRegistration.Manual;+ } else if (stored && stored.config.issuer === discovery.issuer) {+ // A client is only ever used with the issuer it was registered at.+ client = {+ clientId: stored.config.clientId,+ clientSecret: stored.clientSecret,+ tokenEndpointAuthMethod: stored.config.tokenEndpointAuthMethod+ };+ registration = stored.config.registration;+ } else if (discovery.registrationEndpoint) {+ try {+ const registered = await registerOauthClient({+ http,+ serverUrl,+ registrationEndpoint: discovery.registrationEndpoint,+ redirectUri: callbackUri+ });+ client = registered.client;+ compatibility.push(...registered.compatibility);+ registration = AgentVaultOauthRegistration.Dynamic;+ } catch (error) {+ if (!(error instanceof OauthRegistrationError)) throw error;+ // A guessed /register that isn't there means the server has no registration, not that it is broken.+ // Either way the fix is the same, an admin-entered client, so the caller is asked for one.+ return {+ registrationRequired: true,+ redirectUri: callbackUri,+ registrationError: discovery.endpointsGuessed+ ? null+ : oauthSetupError(+ serverUrl,+ `${error.message} Enter the client ID and secret of your own OAuth app instead.`+ ).message,+ authorization: null+ };+ }+ } else {+ return { registrationRequired: true, redirectUri: callbackUri, registrationError: null, authorization: null };+ }++ const storedScopes = stored ? [...new Set([...stored.config.grantedScopes, ...stored.config.requiredScopes])] : [];+ const requestedScopes = storedScopes.length+ ? [+ ...new Set([+ ...storedScopes,+ ...(discovery.scopes.includes(OFFLINE_ACCESS_SCOPE) ? [OFFLINE_ACCESS_SCOPE] : [])+ ])+ ]+ : discovery.scopes;++ const id = crypto.randomUUID();+ const state = generateState(id);+ const { codeVerifier, codeChallenge } = generatePkce();+ const sealedPending = await seal(projectId, { codeVerifier, clientSecret: client.clientSecret });++ const record: TAgentVaultOauthAuthorization = {+ id,+ projectId,+ accessBundleId: bundle.id,+ serviceId: serviceId ?? null,+ actorUserId: ctx.actorId,+ serverUrl,+ state,+ redirectUri: callbackUri,+ status: AgentVaultOauthAuthorizationStatus.Pending,+ error: null,+ issuer: discovery.issuer,+ issParameterSupported: discovery.issParameterSupported,+ authorizationEndpoint: discovery.authorizationEndpoint,+ tokenEndpoint: discovery.tokenEndpoint,+ resource: discovery.resource,+ clientId: client.clientId,+ registration,+ tokenEndpointAuthMethod: client.tokenEndpointAuthMethod,+ compatibility: [...new Set(compatibility)],+ requestedScopes,+ grantedScopes: [],+ expiresAt: null,+ accessTokenHash: null,+ sealedPending: sealedPending.toString("base64"),+ sealedCredential: null+ };+ await saveAuthorization(record);++ return {+ registrationRequired: false,+ redirectUri: callbackUri,+ registrationError: null,+ authorization: {+ id,+ status: record.status,+ authorizeUrl: buildAuthorizeUrl({+ authorizationEndpoint: record.authorizationEndpoint,+ clientId: client.clientId,+ redirectUri: callbackUri,+ codeChallenge,+ state,+ resource: record.resource,+ scopes: requestedScopes+ }),+ scopes: requestedScopes+ }+ };+ };++ const completeAuthorization = async ({+ projectId,+ ctx,+ authorizationId,+ state,+ code,+ iss,+ error,+ errorDescription+ }: TCompleteAuthorizationDTO) => {+ const initial = await loadOwnAuthorization(authorizationId, ctx, projectId);+ if (!isSameState(initial.state, state)) {+ throw new BadRequestError({+ message:+ "The authorization response doesn't belong to this authorization. Close the window and authorize again."+ });+ }+ if (initial.status !== AgentVaultOauthAuthorizationStatus.Pending) return { authorization: toView(initial) };++ const lockKey = KeyStorePrefixes.AgentVaultOauthAuthorizationCompleteLock(authorizationId);+ if (!(await keyStore.setItemWithExpiryNX(lockKey, COMPLETE_LOCK_TTL_SECONDS, "1"))) {+ throw new ConflictError({+ message: "This authorization is already being completed. Wait a moment and check its status."+ });+ }++ try {+ // Re-read under the lock: a completion that finished between the first read and the lock already redeemed+ // the code, and running again would overwrite its result with the provider's invalid_grant.+ const record = await loadOwnAuthorization(authorizationId, ctx, projectId);+ if (record.status !== AgentVaultOauthAuthorizationStatus.Pending) return { authorization: toView(record) };++ const host = describeServer(record.serverUrl);+ const fail = (message: string) => {+ record.status = AgentVaultOauthAuthorizationStatus.Failed;+ record.error = normalizeProviderText(message);+ logger.warn(+ `agentVaultOauth: authorization failed [authorizationId=${record.id}] [projectId=${record.projectId}] [server=${host}] [error=${record.error}]`+ );+ };++ const issuerProblem = validateCallbackIssuer({+ iss,+ expectedIssuer: record.issuer,+ issParameterSupported: record.issParameterSupported,+ serverUrl: record.serverUrl+ });++ if (error) {+ const providerError = normalizeProviderText(error, undefined, [code, state]);+ const detail =+ normalizeProviderText(errorDescription, undefined, [code, state]) || providerError || "no reason given";+ fail(+ providerError === "access_denied"+ ? `Access to '${host}' was denied, so nothing was connected.`+ : `'${host}' didn't authorize Infisical: ${detail}`+ );+ } else if (issuerProblem) {+ fail(issuerProblem);+ } else if (!code) {+ fail(`'${host}' sent no authorization code. Authorize again.`);+ } else {+ const pending = await open<{ codeVerifier: string; clientSecret?: string }>(+ record.projectId,+ Buffer.from(record.sealedPending, "base64")+ );+ // Outside any transaction: this is a network call to the provider.+ const result = await exchangeAuthorizationCode({+ http,+ serverUrl: record.serverUrl,+ issuer: record.issuer,+ tokenEndpoint: record.tokenEndpoint,+ clientId: record.clientId,+ clientSecret: pending.clientSecret,+ tokenEndpointAuthMethod: record.tokenEndpointAuthMethod,+ resource: record.resource,+ code,+ codeVerifier: pending.codeVerifier,+ redirectUri: record.redirectUri,+ requestedScopes: record.requestedScopes+ });++ if (!result.ok) {+ fail(result.message);+ } else {+ const secret: TAgentVaultOauthSecret = {+ accessToken: result.tokens.accessToken,+ refreshToken: result.tokens.refreshToken,+ clientSecret: pending.clientSecret+ };+ record.sealedCredential = (await seal(record.projectId, secret)).toString("base64");+ record.status = AgentVaultOauthAuthorizationStatus.Authorized;+ record.grantedScopes = result.tokens.scopes ?? record.requestedScopes;+ record.expiresAt = expiresAtFrom(result.tokens.expiresIn, new Date());+ record.accessTokenHash = hashAccessToken(result.tokens.accessToken);+ record.compatibility = withTokenCompatibility(record.compatibility, {+ resourceDropped: result.resourceDropped,+ scopesCommaSeparated: result.tokens.scopesCommaSeparated+ });+ if (result.resourceDropped) record.resource = null;+ }+ }++ await saveAuthorization(record);+ return { authorization: toView(record) };+ } finally {+ await keyStore.deleteItem(lockKey);+ }+ };++ const getAuthorization = async ({ ctx, projectId, authorizationId }: TGetAuthorizationDTO) => ({+ authorization: toView(await loadOwnAuthorization(authorizationId, ctx, projectId))+ });++ // Single use: the save that deletes the record wins, so two saves racing for one authorization end with one+ // winner. A save that then fails (a name conflict, say) restores it, so it can be retried without authorizing+ // again. Only an authorized record is consumed, and completion never rewrites one, so the record validated+ // here is the one deleted.+ const claimAuthorization = async ({+ authorizationId,+ projectId,+ accessBundleId,+ serviceId,+ ctx,+ serverUrl+ }: TClaimAuthorizationDTO) => {+ const recordKey = KeyStorePrefixes.AgentVaultOauthAuthorization(authorizationId);+ const { record, raw } = await loadOwnStoredAuthorization(authorizationId, ctx, projectId);+ if (record.accessBundleId.toLowerCase() !== accessBundleId.toLowerCase()) {+ throw new BadRequestError({+ message: "This authorization was started for a different access bundle. Authorize again here."+ });+ }+ assertAuthorizationServerUrl(record.serverUrl, serverUrl);+ if (record.serviceId && record.serviceId.toLowerCase() !== serviceId?.toLowerCase()) {+ throw new BadRequestError({+ message: serviceId+ ? "This authorization was started for a different service. Authorize this service again."+ : "This authorization reauthorizes an existing service, so it can't create a new one. Authorize again."+ });+ }+ if (record.status === AgentVaultOauthAuthorizationStatus.Failed) {+ throw new BadRequestError({+ message: `This authorization failed, so it can't be saved. Start a new one. ${record.error ?? ""}`.trim()+ });+ }+ if (record.status !== AgentVaultOauthAuthorizationStatus.Authorized || !record.sealedCredential) {+ throw new BadRequestError({ message: "This authorization hasn't finished yet. Finish signing in, then save." });+ }++ const remainingTtlSeconds = await keyStore.ttl(recordKey);+ if ((await keyStore.deleteItem(recordKey)) !== 1) {+ throw new ConflictError({+ message: "This authorization was already used by another save. Authorize the service again."+ });+ }++ // Never throws: it runs while a save is failing, and that save's own error is the one to report.+ const restore = async () => {+ if (!(remainingTtlSeconds > 0)) return;+ try {+ await keyStore.setItemWithExpiry(recordKey, remainingTtlSeconds, raw);+ } catch (error) {+ logger.warn(+ error,+ `agentVaultOauth: could not restore the authorization after a failed save [authorizationId=${authorizationId}]`+ );+ }+ };++ return { record, restore };+ };++ // The non-secret half goes to credentialConfig and the record's sealed blob becomes encryptedCredential as is:+ // both are the project cipher over the same JSON shape, so nothing is opened to move it.+ const buildCredentialFromAuthorization = (+ record: TAgentVaultOauthAuthorization,+ {+ authorizedBy,+ previousRequiredScopes = []+ }: {+ authorizedBy: { userId: string; username: string } | null;+ previousRequiredScopes?: string[];+ }+ ): { config: TAgentVaultOauthConfig; encryptedCredential: Buffer } => {+ const now = new Date().toISOString();+ // A provider may grant less than was asked, so a scope the upstream demanded stays missing until it's granted.+ const requiredScopes = [...new Set(previousRequiredScopes)].filter(+ (scope) => !record.grantedScopes.includes(scope)+ );+ return {+ config: {+ type: AgentVaultCredentialType.OAuth,+ grantType: AGENT_VAULT_OAUTH_GRANT_TYPE,+ serverUrl: record.serverUrl,+ issuer: record.issuer,+ authorizationEndpoint: record.authorizationEndpoint,+ tokenEndpoint: record.tokenEndpoint,+ resource: record.resource,+ clientId: record.clientId,+ registration: record.registration,+ tokenEndpointAuthMethod: record.tokenEndpointAuthMethod,+ compatibility: record.compatibility,+ requestedScopes: record.requestedScopes,+ grantedScopes: record.grantedScopes,+ requiredScopes,+ status: requiredScopes.length ? AgentVaultOauthStatus.NeedsAdditionalScopes : AgentVaultOauthStatus.Connected,+ expiresAt: record.expiresAt,+ accessTokenHash: record.accessTokenHash ?? "",+ authorizedBy,+ authorizedAt: now,+ lastRefreshedAt: null,+ lastError: null+ },+ encryptedCredential: Buffer.from(record.sealedCredential!, "base64")+ };+ };++ const toResolvedCredential = (config: TAgentVaultOauthConfig, accessToken: string): TResolvedOauthCredential => ({+ type: "bearer",+ headerName: AGENT_VAULT_OAUTH_HEADER_NAME,+ headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,+ value: accessToken,+ source: "oauth",+ expiresAt: config.expiresAt+ });++ // An unchanged blob holds the same tokens, so a re-read only opens the blob when it changed.+ const loadOauthService = async (+ serviceId: string,+ cipher: () => Promise<TProjectCipher>,+ previous?: TLoadedOauthService+ ): Promise<TLoadedOauthService> => {+ const service = await agentVaultServiceDAL.findByIdPrimary(serviceId);+ if (!service || service.credentialType !== AgentVaultCredentialType.OAuth || !service.encryptedCredential) {+ throw new NotFoundError({ message: `OAuth service with ID '${serviceId}' not found` });+ }+ const secret = previous?.encryptedCredential.equals(service.encryptedCredential)+ ? previous.secret+ : openWith<TAgentVaultOauthSecret>(await cipher(), service.encryptedCredential);+ return {+ config: service.credentialConfig as TAgentVaultOauthConfig,+ secret,+ encryptedCredential: service.encryptedCredential,+ hostPattern: service.hostPattern,+ serverUrl: serverUrlOf(service.config)+ };+ };++ const writeStatus = async (+ serviceId: string,+ expectedEncryptedCredential: Buffer,+ { lastError, ...rest }: Partial<TAgentVaultOauthConfig>,+ previousStatus: AgentVaultOauthStatus+ ) => {+ // Whatever reached the message, jsonb has to be able to store it.+ const patch = {+ ...rest,+ ...(lastError === undefined ? {} : { lastError: normalizeProviderText(lastError) || null })+ };+ const updated = await agentVaultServiceDAL.compareAndSwapCredential({+ id: serviceId,+ expectedEncryptedCredential,+ credentialConfigPatch: patch+ });+ if (updated && patch.status && patch.status !== previousStatus) {+ logger.warn(+ `agentVaultOauth: service status changed [serviceId=${serviceId}] [from=${previousStatus}] [to=${patch.status}] [reason=${patch.lastError ?? "none"}]`+ );+ }+ return updated;+ };++ // One algorithm for resolve's lazy refresh and the proxy's on-demand refresh. A failing provider never throws+ // from here: the caller gets the current token and the failure is recorded on the service.+ const refreshServiceToken = async ({+ serviceId,+ projectId,+ rejectedTokenHash,+ requiredScopes,+ expiresWithinSeconds,+ destination+ }: TRefreshServiceTokenDTO): Promise<{ credential: TResolvedOauthCredential; status: AgentVaultOauthStatus }> => {+ let cipherPair: Promise<TProjectCipher> | null = null;+ const cipher = () => {+ cipherPair ??= getProjectCipher(projectId);+ return cipherPair;+ };++ // Checked on every row a token can come from, so a move that lands mid-refresh can't send the new server's+ // token to the old host, nor refresh a token the caller would then misdirect.+ const assertSameDestination = (loaded: TLoadedOauthService) => {+ if (+ loaded.hostPattern !== destination.hostPattern ||+ (destination.serverUrl !== undefined && loaded.serverUrl !== destination.serverUrl)+ ) {+ throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });+ }+ return loaded;+ };+ const load = async (previous?: TLoadedOauthService) =>+ assertSameDestination(await loadOauthService(serviceId, cipher, previous));++ let current = await load();+ const answer = () => {+ assertSameDestination(current);+ return {+ credential: toResolvedCredential(current.config, current.secret.accessToken),+ status: current.config.status+ };+ };++ const fromWrittenRow = (+ row: NonNullable<Awaited<ReturnType<typeof writeStatus>>>,+ secret: TAgentVaultOauthSecret,+ encryptedCredential: Buffer+ ): TLoadedOauthService =>+ assertSameDestination({+ config: row.credentialConfig as TAgentVaultOauthConfig,+ secret,+ encryptedCredential,+ hostPattern: row.hostPattern,+ serverUrl: serverUrlOf(row.config)+ });++ // A failed swap means the row moved on (a reauthorization, usually), and the new row is the answer.+ const applyStatus = async (patch: Partial<TAgentVaultOauthConfig>) => {+ const updated = await writeStatus(serviceId, current.encryptedCredential, patch, current.config.status);+ current = updated ? fromWrittenRow(updated, current.secret, current.encryptedCredential) : await load(current);+ };++ if (requiredScopes?.length) {+ // Only the refused token is known to lack the scopes: a replacement may carry them. And a service that needs+ // reauthorizing keeps saying so, since reauthorizing is what fixes both.+ // Both conditions are checked again in the UPDATE, against the row it writes.+ if (+ rejectedTokenHash === current.config.accessTokenHash &&+ current.config.status !== AgentVaultOauthStatus.NeedsReauthorization+ ) {+ const previousStatus = current.config.status;+ const updated = await agentVaultServiceDAL.addRequiredScopes({+ id: serviceId,+ expectedEncryptedCredential: current.encryptedCredential,+ rejectedTokenHash,+ requiredScopes+ });+ current = updated ? fromWrittenRow(updated, current.secret, current.encryptedCredential) : await load(current);+ if (updated && previousStatus !== AgentVaultOauthStatus.NeedsAdditionalScopes) {+ logger.warn(+ `agentVaultOauth: service status changed [serviceId=${serviceId}] [from=${previousStatus}] [to=${AgentVaultOauthStatus.NeedsAdditionalScopes}] [reason=insufficient_scope]`+ );+ }+ }+ return answer();+ }++ const decide = () =>+ decideRefresh({+ status: current.config.status,+ expiresAt: current.config.expiresAt,+ accessTokenHash: current.config.accessTokenHash,+ hasRefreshToken: Boolean(current.secret.refreshToken),+ rejectedTokenHash,+ expiresWithinSeconds,+ now: new Date()+ });++ const markNeedsReauthorization = (reason: string) =>+ applyStatus({ status: AgentVaultOauthStatus.NeedsReauthorization, lastError: reason });++ const first = decide();+ if (first.action === "return-current") return answer();+ if (first.action === "needs-reauthorization") {+ await markNeedsReauthorization(first.reason);+ return answer();+ }++ let lock: TKeyStoreLock;+ try {+ lock = await keyStore.acquireLock(+ [KeyStorePrefixes.AgentVaultOauthRefreshLock(serviceId)],+ REFRESH_LOCK_DURATION_MS,+ REFRESH_LOCK_SETTINGS+ );+ } catch {+ // Another refresh held the lock the whole time; whatever it stored is the best answer available.+ current = await load(current);+ return answer();+ }++ try {+ current = await load(current);+ const second = decide();+ if (second.action === "return-current") return answer();+ if (second.action === "needs-reauthorization") {+ await markNeedsReauthorization(second.reason);+ return answer();+ }++ const { config, secret } = current;+ const result = await refreshAccessToken({+ http,+ serverUrl: config.resource ?? config.issuer,+ issuer: config.issuer,+ tokenEndpoint: config.tokenEndpoint,+ clientId: config.clientId,+ clientSecret: secret.clientSecret,+ tokenEndpointAuthMethod: config.tokenEndpointAuthMethod,+ resource: config.resource,+ requestedScopes: config.requestedScopes,+ sensitiveValues: [secret.accessToken],+ refreshToken: secret.refreshToken!+ });++ if (!result.ok) {+ if (result.errorCode === "invalid_grant") {+ await markNeedsReauthorization(+ "The MCP server no longer accepts the stored refresh token (it may have been revoked). Reauthorize this service."+ );+ } else {+ await applyStatus({ lastError: result.message });+ logger.warn(`agentVaultOauth: token refresh failed [serviceId=${serviceId}] [error=${result.message}]`);+ }+ return answer();+ }++ const now = new Date();+ const nextSecret: TAgentVaultOauthSecret = {+ accessToken: result.tokens.accessToken,+ // RFC 6749 section 6: a server that issues no new refresh token keeps the old one valid.+ refreshToken: result.tokens.refreshToken ?? secret.refreshToken,+ clientSecret: secret.clientSecret+ };+ const compatibility = withTokenCompatibility(config.compatibility, {+ resourceDropped: result.resourceDropped,+ scopesCommaSeparated: result.tokens.scopesCommaSeparated+ });+ const patch: Partial<TAgentVaultOauthConfig> = {+ // Missing scopes stay missing after a refresh; only reauthorizing can add them. `keepStatus` below covers a+ // scope report that lands after this read.+ status:+ config.status === AgentVaultOauthStatus.NeedsAdditionalScopes+ ? AgentVaultOauthStatus.NeedsAdditionalScopes+ : AgentVaultOauthStatus.Connected,+ expiresAt: expiresAtFrom(result.tokens.expiresIn, now),+ accessTokenHash: hashAccessToken(result.tokens.accessToken),+ grantedScopes: result.tokens.scopes ?? config.grantedScopes,+ lastRefreshedAt: now.toISOString(),+ lastError: null,+ ...(result.resourceDropped ? { resource: null } : {}),+ ...(compatibility === config.compatibility ? {} : { compatibility })+ };+ const encryptedCredential = sealWith(await cipher(), nextSecret);+ const swapped = await agentVaultServiceDAL.compareAndSwapCredential({+ id: serviceId,+ expectedEncryptedCredential: current.encryptedCredential,+ encryptedCredential,+ credentialConfigPatch: patch,+ keepStatus: { status: AgentVaultOauthStatus.NeedsAdditionalScopes, keys: ["requiredScopes"] }+ });++ if (!swapped) {+ // Someone reauthorized while this refresh was in flight, and their tokens stand.+ current = await load(current);+ return answer();+ }+ current = fromWrittenRow(swapped, nextSecret, encryptedCredential);+ return answer();+ } finally {+ await lock.release().catch(() => {});+ }+ };++ return {+ createAuthorization,+ completeAuthorization,+ getAuthorization,+ claimAuthorization,+ buildCredentialFromAuthorization,+ refreshServiceToken+ };+};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.tsnew file mode 100644index 0000000000..2df7d75aad--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.ts@@ -0,0 +1,199 @@+import https from "node:https";+import type { AddressInfo } from "node:net";++import forge from "node-forge";+import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";++import { agentVaultOauthHttpClient } from "./agent-vault-oauth-http-fns";+import { exchangeAuthorizationCode, refreshAccessToken } from "./agent-vault-oauth-token-fns";+import { AgentVaultOauthClientAuthMethod } from "./agent-vault-oauth-types";++const { transportTrust } = vi.hoisted(() => ({ transportTrust: { ca: "", allowInternalIps: true } }));++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({+ isDevelopmentMode: false,+ ALLOW_INTERNAL_IP_CONNECTIONS: transportTrust.allowInternalIps,+ SAFE_REQUEST_FORCE_DIRECT_EGRESS: true+ })+}));+vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: vi.fn(async () => undefined)+}));+vi.mock("@app/lib/logger", async () => ({+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ sanitizeUrlForLog: (+ await vi.importActual<typeof import("@app/lib/logger/sanitize-url")>("@app/lib/logger/sanitize-url")+ ).sanitizeUrlForLog+}));+vi.mock("@app/lib/logger/logger", () => ({+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++// Trust only the test server's certificate; the library, OAuth transport and SSRF-safe dispatch stay real.+vi.mock("@app/lib/validator", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@app/lib/validator")>();+ const post: typeof actual.safeRequest.post = (url, data, options) =>+ actual.safeRequest.post(url, data, { ...options, ca: transportTrust.ca });+ return { ...actual, safeRequest: { ...actual.safeRequest, post } };+});++describe("OAuth token requests over HTTPS", () => {+ let server: https.Server;+ let issuer: string;+ const requests: { path: string; authorization?: string; form: URLSearchParams }[] = [];++ beforeAll(async () => {+ const keys = forge.pki.rsa.generateKeyPair(2048);+ const certificate = forge.pki.createCertificate();+ certificate.publicKey = keys.publicKey;+ certificate.serialNumber = "01";+ certificate.validity.notBefore = new Date(Date.now() - 60_000);+ certificate.validity.notAfter = new Date(Date.now() + 60_000);+ certificate.setSubject([{ name: "commonName", value: "localhost" }]);+ certificate.setIssuer(certificate.subject.attributes);+ certificate.setExtensions([+ { name: "basicConstraints", cA: true },+ { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] }+ ]);+ certificate.sign(keys.privateKey, forge.md.sha256.create());+ transportTrust.ca = forge.pki.certificateToPem(certificate);++ server = https.createServer(+ { key: forge.pki.privateKeyToPem(keys.privateKey), cert: transportTrust.ca },+ (request, response) => {+ let body = "";+ request.setEncoding("utf8");+ request.on("data", (chunk: string) => {+ body += chunk;+ });+ request.on("end", () => {+ const form = new URLSearchParams(body);+ requests.push({ path: request.url ?? "", authorization: request.headers.authorization, form });+ if (request.url === "/redirect") {+ response.writeHead(302, { Location: `${issuer}/unexpected` });+ response.end();+ } else if (request.url === "/unavailable") {+ response.writeHead(503, { "Content-Type": "application/json" });+ response.end(JSON.stringify({ error: "temporarily_unavailable" }));+ } else if (request.url === "/trickle") {+ response.writeHead(200, { "Content-Type": "application/json" });+ response.write("{");+ const timer = setInterval(() => response.write(" "), 10);+ response.once("close", () => clearInterval(timer));+ } else if (form.get("grant_type") === "authorization_code") {+ response.writeHead(200, { "Content-Type": "application/x-www-form-urlencoded" });+ response.end("access_token=at-code&token_type=bearer&refresh_token=rt-one&scope=repo%2Cgist");+ } else if (form.has("resource")) {+ response.writeHead(400, { "Content-Type": "application/json" });+ response.end(JSON.stringify({ error: "invalid_target" }));+ } else {+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(+ JSON.stringify({ access_token: "at-refreshed", token_type: "Bearer", refresh_token: "rt-two" })+ );+ }+ });+ }+ );+ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", () => resolve());+ });+ issuer = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;+ }, 30_000);++ beforeEach(() => {+ requests.length = 0;+ transportTrust.allowInternalIps = true;+ });++ afterAll(async () => {+ if (server) {+ server.closeAllConnections();+ await new Promise<void>((resolve) => {+ server.close(() => resolve());+ });+ }+ });++ const args = () => ({+ http: agentVaultOauthHttpClient,+ issuer,+ serverUrl: `${issuer}/mcp`,+ tokenEndpoint: `${issuer}/token`,+ clientId: "id: one",+ resource: `${issuer}/mcp`,+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None+ });++ test("exchanges a code with Basic authentication and PKCE, accepting a form-encoded response", async () => {+ const result = await exchangeAuthorizationCode({+ ...args(),+ clientSecret: "secret &two",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretBasic,+ code: "code-one",+ codeVerifier: "verifier-one",+ redirectUri: "https://infisical.test/agent-vault/oauth/callback",+ requestedScopes: ["repo", "gist"]+ });+ expect(result).toMatchObject({+ ok: true,+ tokens: { accessToken: "at-code", refreshToken: "rt-one", scopes: ["repo", "gist"], scopesCommaSeparated: true }+ });+ expect(requests).toHaveLength(1);+ expect(requests[0].authorization).toBe(`Basic ${Buffer.from("id%3A+one:secret+%26two").toString("base64")}`);+ expect(Object.fromEntries(requests[0].form)).toEqual({+ grant_type: "authorization_code",+ code: "code-one",+ code_verifier: "verifier-one",+ redirect_uri: "https://infisical.test/agent-vault/oauth/callback",+ resource: `${issuer}/mcp`+ });+ });++ test("refreshes through the safe client and retries invalid_target once without resource", async () => {+ const result = await refreshAccessToken({ ...args(), refreshToken: "rt-one" });+ expect(result).toMatchObject({+ ok: true,+ resourceDropped: true,+ tokens: { accessToken: "at-refreshed", refreshToken: "rt-two" }+ });+ expect(requests).toHaveLength(2);+ expect(requests[0].form.get("resource")).toBe(`${issuer}/mcp`);+ expect(requests[1].form.has("resource")).toBe(false);+ expect(requests[1].form.get("refresh_token")).toBe("rt-one");+ expect(requests[1].form.get("client_id")).toBe("id: one");+ });++ test("never follows a redirect carrying a refresh token", async () => {+ const result = await refreshAccessToken({ ...args(), tokenEndpoint: `${issuer}/redirect`, refreshToken: "rt-one" });+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.message).toContain("HTTP 302");+ expect(requests.map(({ path }) => path)).toEqual(["/redirect"]);+ });++ test("never automatically retries a failed rotating refresh token request", async () => {+ const result = await refreshAccessToken({+ ...args(),+ tokenEndpoint: `${issuer}/unavailable`,+ refreshToken: "rt-one"+ });+ expect(result).toMatchObject({ ok: false, errorCode: "temporarily_unavailable" });+ expect(requests).toHaveLength(1);+ });++ test("the production SSRF check refuses a private token endpoint before sending any credentials", async () => {+ transportTrust.allowInternalIps = false;+ const result = await refreshAccessToken({ ...args(), refreshToken: "rt-one" });+ expect(result.ok).toBe(false);+ expect(requests).toHaveLength(0);+ });++ test("a provider trickling response bytes cannot extend the request deadline", async () => {+ const startedAt = Date.now();+ await expect(+ agentVaultOauthHttpClient.postForm(`${issuer}/trickle`, new URLSearchParams(), undefined, { timeoutMs: 100 })+ ).rejects.toThrow();+ expect(Date.now() - startedAt).toBeLessThan(1000);+ });+});diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.tsnew file mode 100644index 0000000000..941e3318ed--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts@@ -0,0 +1,684 @@+import crypto from "node:crypto";++import { describe, expect, test, vi } from "vitest";++import { AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";+import { manualOauthClient, OauthRegistrationError, registerOauthClient } from "./agent-vault-oauth-client-fns";+import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";+import {+ buildAuthorizeUrl,+ decideRefresh,+ exchangeAuthorizationCode,+ expiresAtFrom,+ generatePkce,+ generateState,+ hashAccessToken,+ isSameState,+ MAX_EXPIRES_IN_SECONDS,+ normalizeProviderText,+ parseExpiresIn,+ parseGrantedScopes,+ requestToken,+ validateCallbackIssuer,+ withTokenCompatibility+} from "./agent-vault-oauth-token-fns";+import { AgentVaultOauthClientAuthMethod, AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";++vi.mock("@app/lib/logger", async () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ sanitizeUrlForLog: (+ await vi.importActual<typeof import("@app/lib/logger/sanitize-url")>("@app/lib/logger/sanitize-url")+ ).sanitizeUrlForLog+}));++type TCall = { url: string; form?: URLSearchParams; json?: unknown; headers?: Record<string, string> };++const stubPosts = (responses: TOauthHttpResponse[]) => {+ const calls: TCall[] = [];+ const next = () => {+ const response = responses.shift();+ if (!response) throw new Error("no more stubbed responses");+ return response;+ };+ const http: TOauthHttpClient = {+ probe: async () => ({ status: 401, wwwAuthenticate: null }),+ get: async () => next(),+ postForm: async (url, form, headers) => {+ calls.push({ url, form, headers });+ return next();+ },+ postJson: async (url, json) => {+ calls.push({ url, json });+ return next();+ }+ };+ return { http, calls };+};++const json = (status: number, body: unknown): TOauthHttpResponse => ({+ status,+ contentType: "application/json",+ body: JSON.stringify(body)+});++const tokenArgs = {+ serverUrl: "https://mcp.example.com/mcp",+ issuer: "https://mcp.example.com",+ tokenEndpoint: "https://mcp.example.com/token",+ params: { grant_type: "refresh_token", refresh_token: "rt-1" },+ clientId: "client-1",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None,+ resource: "https://mcp.example.com/mcp"+};++describe("PKCE and state", () => {+ test("the challenge is the S256 of the verifier", () => {+ const { codeVerifier, codeChallenge } = generatePkce();+ expect(codeVerifier).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(codeChallenge).toBe(crypto.createHash("sha256").update(codeVerifier).digest("base64url"));+ });++ test("state carries the authorization id before the first dot, and compares whole", () => {+ const id = "6f1f8b4e-2f6c-4c55-9d61-1f6a2b7c9d10";+ const state = generateState(id);+ expect(state.split(".")[0]).toBe(id);+ expect(state.split(".")[1].length).toBeGreaterThanOrEqual(43);+ expect(isSameState(state, state)).toBe(true);+ expect(isSameState(state, `${state}x`)).toBe(false);+ expect(isSameState(state, `${id}.forged`)).toBe(false);+ });++ test("the token hash is lowercase hex sha256", () => {+ expect(hashAccessToken("abc")).toBe("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");+ });+});++describe("the authorize URL", () => {+ test("carries PKCE S256, state, resource and scopes, and keeps the endpoint's own query", () => {+ const url = new URL(+ buildAuthorizeUrl({+ authorizationEndpoint: "https://auth.example.com/authorize?tenant=x",+ clientId: "client-1",+ redirectUri: "https://app.infisical.com/agent-vault/oauth/callback",+ codeChallenge: "challenge",+ state: "id.random",+ resource: "https://mcp.example.com/mcp",+ scopes: ["read", "write"]+ })+ );+ expect(Object.fromEntries(url.searchParams)).toEqual({+ tenant: "x",+ response_type: "code",+ client_id: "client-1",+ redirect_uri: "https://app.infisical.com/agent-vault/oauth/callback",+ code_challenge: "challenge",+ code_challenge_method: "S256",+ state: "id.random",+ resource: "https://mcp.example.com/mcp",+ scope: "read write"+ });+ });++ test("no scopes and no resource leave both out", () => {+ const url = new URL(+ buildAuthorizeUrl({+ authorizationEndpoint: "https://auth.example.com/authorize",+ clientId: "c",+ redirectUri: "https://x/cb",+ codeChallenge: "c",+ state: "s",+ resource: null,+ scopes: []+ })+ );+ expect(url.searchParams.has("scope")).toBe(false);+ expect(url.searchParams.has("resource")).toBe(false);+ });+});++describe("iss in the callback (RFC 9207)", () => {+ const base = { expectedIssuer: "https://auth.example.com", serverUrl: "https://mcp.example.com/mcp" };++ test.each([+ { iss: "https://auth.example.com", supported: true, ok: true, why: "matches" },+ { iss: "https://auth.example.com/", supported: true, ok: true, why: "matches but for a trailing slash" },+ { iss: "https://auth.example.com", supported: false, ok: true, why: "sent though not advertised" },+ { iss: "https://evil.example.com", supported: true, ok: false, why: "names another issuer" },+ { iss: "https://evil.example.com", supported: false, ok: false, why: "names another issuer, unadvertised" },+ { iss: undefined, supported: true, ok: false, why: "missing though advertised" },+ { iss: undefined, supported: false, ok: true, why: "missing and never advertised" }+ ])("$why", ({ iss, supported, ok }) => {+ const problem = validateCallbackIssuer({ ...base, iss, issParameterSupported: supported });+ expect(problem === null).toBe(ok);+ });+});++describe("token requests", () => {+ test("a JSON response, a public client sending client_id and resource in the form", async () => {+ const { http, calls } = stubPosts([+ json(200, { access_token: "at-2", token_type: "Bearer", expires_in: 3600, refresh_token: "rt-2", scope: "read" })+ ]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(result).toEqual({+ ok: true,+ tokens: { accessToken: "at-2", refreshToken: "rt-2", expiresIn: 3600, scopes: ["read"] },+ resourceDropped: false+ });+ expect(Object.fromEntries(calls[0].form!)).toEqual({+ grant_type: "refresh_token",+ refresh_token: "rt-1",+ resource: "https://mcp.example.com/mcp",+ client_id: "client-1"+ });+ expect(new Headers(calls[0].headers).has("authorization")).toBe(false);+ expect(new Headers(calls[0].headers).get("content-type")).toContain("application/x-www-form-urlencoded");+ });++ test("a form-encoded response is parsed, and GitHub's comma-joined scopes split as a recorded fallback", async () => {+ const { http } = stubPosts([+ {+ status: 200,+ contentType: "application/x-www-form-urlencoded; charset=utf-8",+ body: "access_token=gho_abc&token_type=bearer&scope=repo%2Cgist"+ }+ ]);+ const result = await requestToken({ http, ...tokenArgs, requestedScopes: ["repo", "gist", "user"] });+ expect(result.ok && result.tokens).toEqual({+ accessToken: "gho_abc",+ refreshToken: undefined,+ expiresIn: undefined,+ scopes: ["repo", "gist"],+ scopesCommaSeparated: true+ });+ });++ test("an error code is normalized like the description, and still branches", async () => {+ const { http } = stubPosts([json(400, { error: "invalid_grant\u0000\ud800" })]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(result).toMatchObject({+ ok: false,+ errorCode: "invalid_grant",+ message: "'mcp.example.com' refused the token request: invalid_grant"+ });+ });++ test("an error code with nothing printable falls back to the HTTP status", async () => {+ const { http } = stubPosts([json(400, { error: "\u0000" })]);+ expect(await requestToken({ http, ...tokenArgs })).toMatchObject({+ ok: false,+ errorCode: null,+ message: "'mcp.example.com' refused the token request: HTTP 400"+ });+ });++ test("an access token that can't go into a header is refused, and a bad refresh token is dropped", async () => {+ const refused = stubPosts([json(200, { access_token: "a\r\nX-Evil: 1", token_type: "bearer" })]);+ expect((await requestToken({ http: refused.http, ...tokenArgs })).ok).toBe(false);++ const dropped = stubPosts([json(200, { access_token: "a", token_type: "bearer", refresh_token: "r\u0000" })]);+ const result = await requestToken({ http: dropped.http, ...tokenArgs });+ expect(result.ok && result.tokens.refreshToken).toBeUndefined();+ });++ test.each(["\n", "\r\n"])("a token ending in %j is refused", async (suffix) => {+ const { http } = stubPosts([json(200, { access_token: `access-token${suffix}` })]);+ expect((await requestToken({ http, ...tokenArgs })).ok).toBe(false);+ });++ test("provider refusals cannot expose request secrets or their Basic authorization header", async () => {+ const clientSecret = "client +/secret";+ const encoded = new URLSearchParams({ value: clientSecret }).toString().slice("value=".length);+ const basic = Buffer.from(`${tokenArgs.clientId}:${encoded}`).toString("base64");+ const { http } = stubPosts([+ json(400, {+ error: "invalid_grant",+ error_description: `Refused ${clientSecret}, ${encoded}, ${basic}, rt-1 and current-access`+ })+ ]);+ const result = await requestToken({+ http,+ ...tokenArgs,+ clientSecret,+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretBasic,+ sensitiveValues: ["current-access"]+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.errorCode).toBe("invalid_grant");+ [clientSecret, encoded, basic, "rt-1", "current-access"].forEach((secret) =>+ expect(result.message).not.toContain(secret)+ );+ });++ test("granted scopes that aren't OAuth scope tokens are dropped rather than stored", async () => {+ const { http } = stubPosts([+ json(200, { access_token: "at-2", token_type: "Bearer", scope: 'read \u0000 wr"ite a\\b\twrite read' })+ ]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(result.ok && result.tokens.scopes).toEqual(["read"]);+ });++ test("client_secret_basic form-encodes both halves into the header", async () => {+ const { http, calls } = stubPosts([json(200, { access_token: "a", token_type: "bearer" })]);+ await requestToken({+ http,+ ...tokenArgs,+ clientId: "id:1",+ clientSecret: "s&2",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretBasic+ });+ expect(new Headers(calls[0].headers).get("authorization")).toBe(+ `Basic ${Buffer.from("id%3A1:s%262").toString("base64")}`+ );+ expect(calls[0].form!.has("client_secret")).toBe(false);+ });++ test("client_secret_post puts the secret in the form", async () => {+ const { http, calls } = stubPosts([json(200, { access_token: "a", token_type: "bearer" })]);+ await requestToken({+ http,+ ...tokenArgs,+ clientSecret: "s",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretPost+ });+ expect(calls[0].form!.get("client_secret")).toBe("s");+ });++ test("client_secret_basic uses form encoding for spaces and reserved characters", async () => {+ const { http, calls } = stubPosts([json(200, { access_token: "a", token_type: "bearer" })]);+ await requestToken({+ http,+ ...tokenArgs,+ clientId: "id :!~",+ clientSecret: "s &'()",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretBasic+ });+ expect(new Headers(calls[0].headers).get("authorization")).toBe(+ `Basic ${Buffer.from("id+%3A%21%7E:s+%26%27%28%29").toString("base64")}`+ );+ });++ test("code exchange sends the code, redirect URI and PKCE verifier instead of refresh parameters", async () => {+ const { http, calls } = stubPosts([json(200, { access_token: "a", token_type: "bearer" })]);+ const result = await exchangeAuthorizationCode({+ http,+ ...tokenArgs,+ code: "code-1",+ codeVerifier: "verifier-1",+ redirectUri: "https://app.infisical.com/agent-vault/oauth/callback"+ });+ expect(result.ok).toBe(true);+ expect(Object.fromEntries(calls[0].form!)).toEqual({+ grant_type: "authorization_code",+ code: "code-1",+ code_verifier: "verifier-1",+ redirect_uri: "https://app.infisical.com/agent-vault/oauth/callback",+ client_id: "client-1",+ resource: tokenArgs.resource+ });+ });++ test("invalid_target is retried once without resource", async () => {+ const { http, calls } = stubPosts([+ json(400, { error: "invalid_target" }),+ json(200, { access_token: "a", token_type: "bearer" })+ ]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(result.ok).toBe(true);+ expect(result.resourceDropped).toBe(true);+ expect(calls).toHaveLength(2);+ expect(calls[0].form!.has("resource")).toBe(true);+ expect(calls[1].form!.has("resource")).toBe(false);+ });++ test("an error in a 200 body (GitHub) is a failure with its code", async () => {+ const { http } = stubPosts([+ json(200, { error: "bad_verification_code", error_description: "The code passed is incorrect or expired." })+ ]);+ expect(await requestToken({ http, ...tokenArgs })).toEqual({+ ok: false,+ errorCode: "bad_verification_code",+ message: "'mcp.example.com' refused the token request: The code passed is incorrect or expired.",+ resourceDropped: false+ });+ });++ test("invalid_grant comes back as a code the refresh logic can branch on", async () => {+ const { http } = stubPosts([json(400, { error: "invalid_grant" })]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(result.ok).toBe(false);+ expect(!result.ok && result.errorCode).toBe("invalid_grant");+ });++ test("a non-bearer token is refused", async () => {+ const { http } = stubPosts([json(200, { access_token: "a", token_type: "DPoP" })]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(result.ok).toBe(false);+ });++ test("provider text is stripped of control characters and bounded", async () => {+ const { http } = stubPosts([json(400, { error: "x", error_description: `bad\n${"a".repeat(500)}` })]);+ const result = await requestToken({ http, ...tokenArgs });+ expect(!result.ok && result.message).not.toContain("\n");+ expect(!result.ok && result.message.length).toBeLessThan(400);+ });++ test("a network failure is a readable failure, not a throw", async () => {+ const http: TOauthHttpClient = {+ ...stubPosts([]).http,+ postForm: async () => {+ throw new Error("ETIMEDOUT");+ }+ };+ const result = await requestToken({ http, ...tokenArgs });+ expect(!result.ok && result.message).toBe(+ "Couldn't reach the token endpoint of 'mcp.example.com'. Try again in a moment."+ );+ });++ test("a server that never answers fails inside the budget, and each request gets only what is left of it", async () => {+ const timeouts: number[] = [];+ const http: TOauthHttpClient = {+ ...stubPosts([]).http,+ postForm: (_url, _form, _headers, options) => {+ timeouts.push(options?.timeoutMs ?? -1);+ return new Promise(() => {});+ }+ };+ const startedAt = Date.now();+ const result = await requestToken({ http, ...tokenArgs, budgetMs: 50 });+ expect(Date.now() - startedAt).toBeLessThan(1000);+ expect(!result.ok && result.message).toBe(+ "Couldn't reach the token endpoint of 'mcp.example.com'. Try again in a moment."+ );+ expect(timeouts).toHaveLength(1);+ expect(timeouts[0]).toBeLessThanOrEqual(50);+ });++ test("invalid_target isn't retried once the budget is nearly spent", async () => {+ const { http, calls } = stubPosts([json(400, { error: "invalid_target" })]);+ const result = await requestToken({ http, ...tokenArgs, budgetMs: 100 });+ expect(!result.ok && result.errorCode).toBe("invalid_target");+ expect(calls).toHaveLength(1);+ });++ test("an invalid_target retry receives only the remaining timeout budget", async () => {+ const now = vi.spyOn(Date, "now").mockReturnValue(1000);+ const { http } = stubPosts([json(400, { error: "invalid_target" }), json(200, { access_token: "a" })]);+ const { postForm } = http;+ const timeouts: number[] = [];+ http.postForm = async (url, form, headers, options) => {+ timeouts.push(options?.timeoutMs ?? -1);+ now.mockReturnValue(1600);+ return postForm(url, form, headers, options);+ };+ try {+ const result = await requestToken({ http, ...tokenArgs, budgetMs: 1200 });+ expect(result.ok).toBe(true);+ expect(timeouts).toEqual([1200, 600]);+ } finally {+ now.mockRestore();+ }+ });+});++describe("text from a provider", () => {+ test("Unicode whitespace becomes spaces while ordinary replacement characters survive", () => {+ expect(normalizeProviderText("read\u00a0write\u2028next\ufeffstep\vlast �")).toBe("read write next step last �");+ });++ test("literal and encoded secrets are removed before truncation, and URLs lose paths and query values", () => {+ const secret = "refresh +/token";+ const encoded = new URLSearchParams({ value: secret }).toString().slice("value=".length);+ const normalized = normalizeProviderText(+ `Refused ${secret}, ${encoded} and https://auth.example.com/secret-in-path?token=query-secret`,+ 500,+ [secret]+ );+ expect(normalized).toContain("[redacted]");+ expect(normalized).not.toContain(secret);+ expect(normalized).not.toContain(encoded);+ expect(normalized).not.toContain("secret-in-path");+ expect(normalized).not.toContain("query-secret");+ expect(normalizeProviderText(`bad ${secret}`, 10, [secret])).toBe("bad [redac");+ });+ test("line breaks and tabs become spaces, other control and formatting characters go, and it is bounded", () => {+ expect(normalizeProviderText("The user\r\n\tdeclined the request\u0007")).toBe("The user declined the request");+ expect(normalizeProviderText("é ünïcode stays")).toBe("é ünïcode stays");+ expect(normalizeProviderText("a".repeat(5000))).toHaveLength(500);+ expect(normalizeProviderText("a".repeat(5000), 100)).toHaveLength(100);+ expect(normalizeProviderText(undefined)).toBe("");+ expect(normalizeProviderText(42)).toBe("");+ });++ test("NUL and lone surrogates, which jsonb can't hold, never survive", () => {+ const normalized = normalizeProviderText("a\u0000b \ud800c \udfffd 😀");+ expect(normalized).toBe("a b c d 😀");+ expect(JSON.stringify(normalized)).not.toMatch(/\\u0000|\\ud[89ab]/i);+ });+});++describe("expires_in", () => {+ test.each([+ { value: 3600, expected: 3600 },+ { value: "3600", expected: 3600 },+ { value: 3599.9, expected: 3599 },+ { value: MAX_EXPIRES_IN_SECONDS, expected: MAX_EXPIRES_IN_SECONDS },+ { value: MAX_EXPIRES_IN_SECONDS + 1, expected: undefined },+ { value: 1e20, expected: undefined },+ { value: "1e20", expected: undefined },+ { value: Number.MAX_VALUE, expected: undefined },+ { value: Infinity, expected: undefined },+ { value: 0, expected: undefined },+ { value: 0.5, expected: undefined },+ { value: -60, expected: undefined },+ { value: "", expected: undefined },+ { value: " ", expected: undefined },+ { value: "soon", expected: undefined },+ { value: null, expected: undefined },+ { value: true, expected: undefined }+ ])("$value is $expected", ({ value, expected }) => {+ expect(parseExpiresIn(value)).toBe(expected);+ });++ test("an expiry that isn't a date is no expiry rather than a throw", () => {+ const now = new Date("2026-10-15T12:00:00Z");+ expect(expiresAtFrom(60, now)).toBe("2026-10-15T12:01:00.000Z");+ expect(expiresAtFrom(1e20, now)).toBeNull();+ expect(expiresAtFrom(undefined, now)).toBeNull();+ });+});++describe("granted scopes", () => {+ test.each(["\t", "\n", "\r", "\u00a0"])("only a space separates scopes, not %j", (separator) => {+ expect(parseGrantedScopes(`read${separator}write`)).toEqual({ scopes: [], commaSeparated: false });+ });+ test("split on spaces, so a comma inside a scope token stays", () => {+ expect(parseGrantedScopes("read:a,b write", ["read:a,b", "write"])).toEqual({+ scopes: ["read:a,b", "write"],+ commaSeparated: false+ });+ expect(parseGrantedScopes("a,b", [])).toEqual({ scopes: ["a,b"], commaSeparated: false });+ });++ test("a comma-joined value that was itself requested stays one scope", () => {+ expect(parseGrantedScopes("a,b", ["a,b", "a", "b"])).toEqual({ scopes: ["a,b"], commaSeparated: false });+ });++ test("a comma-joined value splits only when every part was requested", () => {+ expect(parseGrantedScopes("repo,gist", ["repo", "gist", "user"])).toEqual({+ scopes: ["repo", "gist"],+ commaSeparated: true+ });+ expect(parseGrantedScopes("repo,admin", ["repo", "gist"])).toEqual({+ scopes: ["repo,admin"],+ commaSeparated: false+ });+ });++ test("no scope parameter is no scopes", () => {+ expect(parseGrantedScopes(undefined, ["read"])).toEqual({ commaSeparated: false });+ });++ test("each fallback is recorded once", () => {+ expect(+ withTokenCompatibility([AgentVaultOauthCompatibility.ResourceRejected], {+ resourceDropped: true,+ scopesCommaSeparated: true+ })+ ).toEqual([AgentVaultOauthCompatibility.ResourceRejected, AgentVaultOauthCompatibility.ScopeCommaSeparated]);+ const unchanged: AgentVaultOauthCompatibility[] = [];+ expect(withTokenCompatibility(unchanged, { resourceDropped: false })).toBe(unchanged);+ });+});++describe("client registration", () => {+ const args = {+ serverUrl: "https://mcp.example.com/mcp",+ registrationEndpoint: "https://mcp.example.com/register",+ redirectUri: "https://app.infisical.com/agent-vault/oauth/callback"+ };++ test("sends the full metadata and keeps the method the server assigned", async () => {+ const { http, calls } = stubPosts([+ json(201, { client_id: "c-1", client_secret: "s-1", token_endpoint_auth_method: "client_secret_post" })+ ]);+ expect(await registerOauthClient({ http, ...args })).toEqual({+ client: {+ clientId: "c-1",+ clientSecret: "s-1",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretPost+ },+ compatibility: []+ });+ expect(calls[0].json).toEqual({+ client_name: "Infisical Agent Vault",+ redirect_uris: [args.redirectUri],+ token_endpoint_auth_method: "none",+ application_type: "web",+ grant_types: ["authorization_code", "refresh_token"],+ response_types: ["code"]+ });+ });++ test("a rejected registration is retried once with only the required fields", async () => {+ const { http, calls } = stubPosts([+ json(400, { error: "invalid_client_metadata" }),+ json(201, { client_id: "c-2" })+ ]);+ const result = await registerOauthClient({ http, ...args });+ expect(result.client).toEqual({ clientId: "c-2", tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None });+ expect(result.compatibility).toEqual([AgentVaultOauthCompatibility.RegistrationMinimal]);+ expect(Object.keys(calls[1].json as object).sort()).toEqual([+ "client_name",+ "redirect_uris",+ "token_endpoint_auth_method"+ ]);+ });++ test("two refusals, or a server error, end in a registration error", async () => {+ const refused = stubPosts([json(400, {}), json(403, {})]);+ await expect(registerOauthClient({ http: refused.http, ...args })).rejects.toBeInstanceOf(OauthRegistrationError);++ const broken = stubPosts([json(503, {})]);+ await expect(registerOauthClient({ http: broken.http, ...args })).rejects.toThrow(/HTTP 503/);+ expect(broken.calls).toHaveLength(1);+ });++ test("the server's reason for refusing is passed on", async () => {+ const { http } = stubPosts([+ json(400, { error: "invalid_redirect_uri", error_description: "Plaintext HTTP is allowed only for loopback." }),+ json(400, { error: "invalid_redirect_uri", error_description: "Plaintext HTTP is allowed only for loopback." })+ ]);+ await expect(registerOauthClient({ http, ...args })).rejects.toThrow(+ "its registration endpoint refused to register Infisical as a client (Plaintext HTTP is allowed only for loopback.)."+ );+ });++ test("a client ID or secret that isn't printable ASCII is no usable client", async () => {+ const badId = stubPosts([json(201, { client_id: "c\u0000" })]);+ await expect(registerOauthClient({ http: badId.http, ...args })).rejects.toThrow(/no usable client ID/);++ const badSecret = stubPosts([json(201, { client_id: "c", client_secret: "s\ud800" })]);+ await expect(registerOauthClient({ http: badSecret.http, ...args })).rejects.toThrow(/no usable client ID/);+ });++ test("the refusal reason is normalized, the error code included", async () => {+ const { http } = stubPosts([json(400, { error: "bad\u0000request" }), json(400, { error: "bad\u0000request" })]);+ await expect(registerOauthClient({ http, ...args })).rejects.toThrow(+ "its registration endpoint refused to register Infisical as a client (bad request)."+ );+ });++ test("a manual client picks basic unless the server lists only post", () => {+ expect(manualOauthClient({ clientId: "c", tokenEndpointAuthMethodsSupported: null })).toEqual({+ clientId: "c",+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None+ });+ expect(+ manualOauthClient({ clientId: "c", clientSecret: "s", tokenEndpointAuthMethodsSupported: null })+ .tokenEndpointAuthMethod+ ).toBe(AgentVaultOauthClientAuthMethod.ClientSecretBasic);+ expect(+ manualOauthClient({+ clientId: "c",+ clientSecret: "s",+ tokenEndpointAuthMethodsSupported: ["client_secret_post"]+ }).tokenEndpointAuthMethod+ ).toBe(AgentVaultOauthClientAuthMethod.ClientSecretPost);+ });+});++describe("refresh decisions", () => {+ const now = new Date("2026-10-15T12:00:00Z");+ const base = {+ status: AgentVaultOauthStatus.Connected,+ expiresAt: "2026-10-15T13:00:00Z",+ accessTokenHash: "current",+ hasRefreshToken: true,+ now+ };++ test("lazy: a token valid past the horizon is left alone", () => {+ expect(decideRefresh({ ...base, expiresWithinSeconds: 120 })).toEqual({ action: "return-current" });+ });++ test("lazy: a token expiring within the horizon is refreshed", () => {+ expect(decideRefresh({ ...base, expiresAt: "2026-10-15T12:01:00Z", expiresWithinSeconds: 120 })).toEqual({+ action: "refresh"+ });+ });++ test("lazy: no expiry means refresh only on rejection", () => {+ expect(decideRefresh({ ...base, expiresAt: null, expiresWithinSeconds: 120 })).toEqual({+ action: "return-current"+ });+ });++ test("lazy: no refresh token works until expiry, then needs reauthorization", () => {+ expect(+ decideRefresh({ ...base, hasRefreshToken: false, expiresAt: "2026-10-15T12:01:00Z", expiresWithinSeconds: 120 })+ ).toEqual({ action: "return-current" });+ expect(+ decideRefresh({ ...base, hasRefreshToken: false, expiresAt: "2026-10-15T11:59:00Z", expiresWithinSeconds: 120 })+ .action+ ).toBe("needs-reauthorization");+ });++ test("on demand: a rejected token that is no longer current returns the current one", () => {+ expect(decideRefresh({ ...base, rejectedTokenHash: "older" })).toEqual({ action: "return-current" });+ });++ test("on demand: the current token rejected is refreshed, or needs reauthorization without a refresh token", () => {+ expect(decideRefresh({ ...base, rejectedTokenHash: "current" })).toEqual({ action: "refresh" });+ expect(decideRefresh({ ...base, hasRefreshToken: false, rejectedTokenHash: "current" }).action).toBe(+ "needs-reauthorization"+ );+ });++ test("a service that needs reauthorization is never refreshed", () => {+ expect(+ decideRefresh({ ...base, status: AgentVaultOauthStatus.NeedsReauthorization, rejectedTokenHash: "current" })+ ).toEqual({ action: "return-current" });+ });+});diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.tsnew file mode 100644index 0000000000..4e8fa35621--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts@@ -0,0 +1,434 @@+import crypto from "node:crypto";++import * as oauth from "oauth4webapi";+import RE2 from "re2";++import { sanitizeUrlForLog } from "@app/lib/logger";++import { AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";+import { describeServer, splitScopes, stripTrailingSlash } from "./agent-vault-oauth-discovery-fns";+import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";+import { AgentVaultOauthClientAuthMethod, AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";++const base64Url = (buffer: Buffer) => buffer.toString("base64url");++export const hashAccessToken = (accessToken: string) => crypto.createHash("sha256").update(accessToken).digest("hex");++export const generatePkce = () => {+ const codeVerifier = base64Url(crypto.randomBytes(32));+ const codeChallenge = base64Url(crypto.createHash("sha256").update(codeVerifier).digest());+ return { codeVerifier, codeChallenge };+};++// The part before the first `.` is the authorization id, so the callback page can find the authorization+// without a lookup. The whole value is still compared in constant time.+export const generateState = (authorizationId: string) => `${authorizationId}.${base64Url(crypto.randomBytes(32))}`;++export const isSameState = (expected: string, received: string) => {+ const a = Buffer.from(expected);+ const b = Buffer.from(received);+ return a.length === b.length && crypto.timingSafeEqual(a, b);+};++export const buildAuthorizeUrl = ({+ authorizationEndpoint,+ clientId,+ redirectUri,+ codeChallenge,+ state,+ resource,+ scopes+}: {+ authorizationEndpoint: string;+ clientId: string;+ redirectUri: string;+ codeChallenge: string;+ state: string;+ resource: string | null;+ scopes: string[];+}) => {+ const url = new URL(authorizationEndpoint);+ url.searchParams.set("response_type", "code");+ url.searchParams.set("client_id", clientId);+ url.searchParams.set("redirect_uri", redirectUri);+ url.searchParams.set("code_challenge", codeChallenge);+ url.searchParams.set("code_challenge_method", "S256");+ url.searchParams.set("state", state);+ if (resource) url.searchParams.set("resource", resource);+ if (scopes.length) url.searchParams.set("scope", scopes.join(" "));+ return url.toString();+};++// RFC 9207 section 2.4, as the MCP spec applies it: an `iss` that arrives must match, and one that a server+// advertises must arrive. A server that never mentions it is trusted on the code alone.+export const validateCallbackIssuer = ({+ iss,+ expectedIssuer,+ issParameterSupported,+ serverUrl+}: {+ iss?: string;+ expectedIssuer: string;+ issParameterSupported: boolean;+ serverUrl: string;+}): string | null => {+ const host = describeServer(serverUrl);+ if (iss === undefined || iss === "") {+ return issParameterSupported+ ? `The authorization response from '${host}' didn't say which server issued it, though that server promises to. Authorize again.`+ : null;+ }+ if (stripTrailingSlash(iss) !== stripTrailingSlash(expectedIssuer)) {+ return `The authorization response came from a different server than '${host}' uses, so it was rejected. Authorize again.`;+ }+ return null;+};++export type TOauthTokens = {+ accessToken: string;+ refreshToken?: string;+ expiresIn?: number;+ scopes?: string[];+ // True when `scopes` came from the comma-separated fallback rather than RFC 6749's space-separated list.+ scopesCommaSeparated?: boolean;+};++export type TTokenRequestResult =+ | { ok: true; tokens: TOauthTokens; resourceDropped: boolean }+ | { ok: false; errorCode: string | null; message: string; resourceDropped: boolean };++const parseTokenBody = (contentType: string, body: string): Record<string, unknown> | null => {+ if (contentType.includes("application/x-www-form-urlencoded")) {+ return Object.fromEntries(new URLSearchParams(body));+ }+ try {+ const parsed: unknown = JSON.parse(body);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as Record<string, unknown>;+ } catch {+ // Some servers send form encoding labelled as something else.+ if (body.includes("=")) return Object.fromEntries(new URLSearchParams(body));+ }+ return null;+};++const MAX_TOKEN_LENGTH = 16_384;+// RFC 6749 appendix A.12 and A.17: tokens are VSCHAR. The access token is injected into a header by the proxy, so a+// line break or NUL in it must never get that far.+const TOKEN_PATTERN = new RE2(/^[\x20-\x7e]+$/);+const isUsableToken = (value: unknown): value is string =>+ typeof value === "string" && value.length <= MAX_TOKEN_LENGTH && TOKEN_PATTERN.test(value);++// One year. A longer lifetime is treated as none given, so the token is refreshed only when the upstream rejects+// it, which is what a server meaning "doesn't expire" wants. Clamping instead would mark a token that has no+// refresh token as expired after a year while it still works.+export const MAX_EXPIRES_IN_SECONDS = 365 * 24 * 60 * 60;++export const parseExpiresIn = (value: unknown): number | undefined => {+ const seconds = typeof value === "string" && value.trim() ? Number(value) : value;+ if (typeof seconds !== "number" || !Number.isFinite(seconds)) return undefined;+ const whole = Math.floor(seconds);+ return whole >= 1 && whole <= MAX_EXPIRES_IN_SECONDS ? whole : undefined;+};++// RFC 6749 section 3.3 separates scopes with spaces, and a comma is legal inside a scope token. Some servers+// (GitHub) join them with commas instead, so a value with no spaces is split on commas only when every part is a+// scope that was asked for and the whole value isn't.+export const parseGrantedScopes = (+ scope: unknown,+ requestedScopes: string[] = []+): { scopes?: string[]; commaSeparated: boolean } => {+ if (typeof scope !== "string") return { commaSeparated: false };+ if (!scope.includes(" ") && scope.includes(",") && !requestedScopes.includes(scope)) {+ const parts = scope.split(",").filter(Boolean);+ if (parts.length > 1 && parts.every((part) => requestedScopes.includes(part))) {+ return { scopes: splitScopes(scope, ","), commaSeparated: true };+ }+ }+ return { scopes: splitScopes(scope), commaSeparated: false };+};++export const parseTokenResponse = (+ body: Record<string, unknown>,+ requestedScopes: string[] = []+): TOauthTokens | null => {+ const accessToken = body.access_token;+ if (!isUsableToken(accessToken)) return null;+ // Only bearer tokens can be injected as a header; DPoP and MAC tokens need proof the proxy can't give.+ if (typeof body.token_type === "string" && body.token_type.toLowerCase() !== "bearer") return null;++ const refreshToken = isUsableToken(body.refresh_token) ? body.refresh_token : undefined;+ const { scopes, commaSeparated } = parseGrantedScopes(body.scope, requestedScopes);+ return {+ accessToken,+ refreshToken,+ expiresIn: parseExpiresIn(body.expires_in),+ scopes,+ ...(commaSeparated ? { scopesCommaSeparated: true } : {})+ };+};++const MAX_PROVIDER_TEXT_LENGTH = 500;+export const MAX_ERROR_CODE_LENGTH = 100;+export const MAX_ERROR_DESCRIPTION_LENGTH = 300;+// RE2's \s omits Unicode whitespace and vertical tabs.+// eslint-disable-next-line no-control-regex+const PROVIDER_WHITESPACE_RE = new RE2(/[\s\p{Z}\ufeff\x00-\x1f\x7f]+/gu);+const PROVIDER_FORMATTING_RE = new RE2(/[\p{Cc}\p{Cf}\p{Co}]/gu);+const REPEATED_SPACES_RE = new RE2(/ {2,}/g);+const PROVIDER_URL_RE = new RE2(/https?:\/\/[^\s\v\p{Z}\ufeff<>"']+/giu);++// Anything a provider sends that can end up in a message, a log line, `lastError` or an authorization's `error`+// goes through here: line breaks and tabs become spaces, other control and formatting characters (NUL, lone+// surrogates and bidi overrides included) are dropped, since jsonb can't hold the first two, and it is cut to a+// readable length.+export const normalizeProviderText = (+ text: unknown,+ maxLength = MAX_PROVIDER_TEXT_LENGTH,+ sensitiveValues: (string | undefined)[] = []+) => {+ if (typeof text !== "string" || !text) return "";+ // Providers can echo request credentials in their descriptions. Redact literal and form-encoded values before+ // truncating, so a partial secret is never left at the cut.+ let redacted = text;+ sensitiveValues+ .filter((value): value is string => Boolean(value))+ .forEach((value) => {+ const encoded = new URLSearchParams({ value }).toString().slice("value=".length);+ [...new Set([value, encoded, encoded.replaceAll("+", "%20")])].forEach((secret) => {+ redacted = redacted.split(secret).join("[redacted]");+ });+ });+ // RE2 turns lone surrogates into replacement characters before matching; drop them while still in UTF-16.+ const wellFormed = [...redacted]+ .filter((character) => {+ const codePoint = character.codePointAt(0)!;+ return codePoint < 0xd800 || codePoint > 0xdfff;+ })+ .join("");+ const normalized = wellFormed+ .replace(PROVIDER_WHITESPACE_RE, " ")+ .replace(PROVIDER_FORMATTING_RE, "")+ .replace(REPEATED_SPACES_RE, " ")+ .replace(PROVIDER_URL_RE, (url) => sanitizeUrlForLog(url))+ .trim();+ return [...normalized].slice(0, maxLength).join("");+};++// One deadline for the request and its invalid_target retry together: the proxy's credential refresh has to answer+// inside its own 15 second timeout, lock wait and database reads included.+export const TOKEN_REQUEST_BUDGET_MS = 7_000;+const MIN_RETRY_BUDGET_MS = 500;++// Also bounds what the HTTP client's own timeout doesn't cover, such as resolving and validating the host.+const withTimeout = <T>(promise: Promise<T>, ms: number) => {+ let timer: NodeJS.Timeout | undefined;+ return Promise.race([+ promise,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error("Token request timed out")), ms);+ })+ ]).finally(() => clearTimeout(timer));+};++export const requestToken = async ({+ http,+ serverUrl,+ issuer,+ tokenEndpoint,+ params,+ clientId,+ clientSecret,+ tokenEndpointAuthMethod,+ resource,+ requestedScopes = [],+ sensitiveValues = [],+ budgetMs = TOKEN_REQUEST_BUDGET_MS+}: {+ http: TOauthHttpClient;+ serverUrl: string;+ issuer: string;+ tokenEndpoint: string;+ params: Record<string, string>;+ clientId: string;+ clientSecret?: string;+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod;+ resource: string | null;+ // What the grant asked for, which decides whether a comma-joined `scope` is split.+ requestedScopes?: string[];+ sensitiveValues?: string[];+ budgetMs?: number;+}): Promise<TTokenRequestResult> => {+ const host = describeServer(serverUrl);+ const deadline = Date.now() + budgetMs;+ const authorizationServer = { issuer, token_endpoint: tokenEndpoint };+ const client = { client_id: clientId };+ let clientAuthentication = oauth.None();+ if (clientSecret && tokenEndpointAuthMethod === AgentVaultOauthClientAuthMethod.ClientSecretBasic) {+ clientAuthentication = oauth.ClientSecretBasic(clientSecret);+ }+ if (clientSecret && tokenEndpointAuthMethod === AgentVaultOauthClientAuthMethod.ClientSecretPost) {+ clientAuthentication = oauth.ClientSecretPost(clientSecret);+ }+ const encodedClientId = new URLSearchParams({ value: clientId }).toString().slice("value=".length);+ const encodedClientSecret = new URLSearchParams({ value: clientSecret ?? "" }).toString().slice("value=".length);+ const requestSecrets = [+ ...sensitiveValues,+ clientSecret,+ params.code,+ params.code_verifier,+ params.refresh_token,+ ...(clientSecret ? [Buffer.from(`${encodedClientId}:${encodedClientSecret}`).toString("base64")] : [])+ ];++ const send = async (withResource: boolean): Promise<TTokenRequestResult> => {+ const form = new URLSearchParams(params);+ if (withResource && resource) form.set("resource", resource);++ let response;+ try {+ const remainingMs = Math.max(1, deadline - Date.now());+ response = await withTimeout(+ oauth.genericTokenEndpointRequest(authorizationServer, client, clientAuthentication, params.grant_type, form, {+ // All egress stays on the SSRF-safe client, including DNS pinning and redirect restrictions.+ [oauth.customFetch]: async (url, options) => {+ const result = await http.postForm(url, options.body, options.headers, {+ timeoutMs: Math.max(1, deadline - Date.now())+ });+ return new Response(result.body || null, {+ status: result.status,+ headers: { "Content-Type": result.contentType }+ });+ }+ }),+ remainingMs+ );+ } catch {+ return {+ ok: false,+ errorCode: null,+ message: `Couldn't reach the token endpoint of '${host}'. Try again in a moment.`,+ resourceDropped: !withResource+ };+ }++ const body = parseTokenBody(response.headers.get("content-type") ?? "", await response.text());+ // GitHub answers a failed exchange with a 200 and an `error` field.+ if (response.status >= 200 && response.status < 300 && body && body.error === undefined) {+ const tokens = parseTokenResponse(body, requestedScopes);+ if (tokens) return { ok: true, tokens, resourceDropped: !withResource };+ return {+ ok: false,+ errorCode: null,+ message: `'${host}' returned a token Infisical can't use (it must be a bearer token of printable characters).`,+ resourceDropped: !withResource+ };+ }++ const errorCode = normalizeProviderText(body?.error, MAX_ERROR_CODE_LENGTH) || null;+ const description = normalizeProviderText(body?.error_description, MAX_ERROR_DESCRIPTION_LENGTH, requestSecrets);+ const detail =+ description ||+ normalizeProviderText(errorCode, MAX_ERROR_CODE_LENGTH, requestSecrets) ||+ `HTTP ${response.status}`;+ return {+ ok: false,+ errorCode,+ message: `'${host}' refused the token request: ${detail}`,+ resourceDropped: !withResource+ };+ };++ const result = await send(true);+ if (!result.ok && result.errorCode === "invalid_target" && resource && deadline - Date.now() >= MIN_RETRY_BUDGET_MS) {+ return send(false);+ }+ return result;+};++export const exchangeAuthorizationCode = (+ args: Omit<Parameters<typeof requestToken>[0], "params"> & { code: string; codeVerifier: string; redirectUri: string }+) =>+ requestToken({+ ...args,+ params: {+ grant_type: "authorization_code",+ code: args.code,+ code_verifier: args.codeVerifier,+ redirect_uri: args.redirectUri+ }+ });++export const refreshAccessToken = (+ args: Omit<Parameters<typeof requestToken>[0], "params"> & { refreshToken: string }+) => requestToken({ ...args, params: { grant_type: "refresh_token", refresh_token: args.refreshToken } });++export const withTokenCompatibility = (+ compatibility: AgentVaultOauthCompatibility[],+ { resourceDropped, scopesCommaSeparated }: { resourceDropped: boolean; scopesCommaSeparated?: boolean }+): AgentVaultOauthCompatibility[] => {+ const used = [+ ...(resourceDropped ? [AgentVaultOauthCompatibility.ResourceRejected] : []),+ ...(scopesCommaSeparated ? [AgentVaultOauthCompatibility.ScopeCommaSeparated] : [])+ ].filter((entry) => !compatibility.includes(entry));+ return used.length ? [...compatibility, ...used] : compatibility;+};++// Never throws: `parseExpiresIn` bounds what a provider sends, and anything that still isn't a date is no expiry.+export const expiresAtFrom = (expiresIn: number | undefined, now: Date) => {+ if (expiresIn === undefined) return null;+ const expiresAt = new Date(now.getTime() + expiresIn * 1000);+ return Number.isNaN(expiresAt.getTime()) ? null : expiresAt.toISOString();+};++export type TRefreshDecision =+ | { action: "return-current" }+ | { action: "refresh" }+ | { action: "needs-reauthorization"; reason: string };++// One decision for both callers. Resolve passes `expiresWithinSeconds`; the proxy, after a 401, passes the hash+// of the token it sent.+export const decideRefresh = ({+ status,+ expiresAt,+ accessTokenHash,+ hasRefreshToken,+ rejectedTokenHash,+ expiresWithinSeconds,+ now+}: {+ status: AgentVaultOauthStatus;+ expiresAt: string | null;+ accessTokenHash: string;+ hasRefreshToken: boolean;+ rejectedTokenHash?: string;+ expiresWithinSeconds?: number;+ now: Date;+}): TRefreshDecision => {+ if (status === AgentVaultOauthStatus.NeedsReauthorization) return { action: "return-current" };++ if (rejectedTokenHash !== undefined) {+ // Someone else already replaced the rejected token, so the current one is the answer.+ if (rejectedTokenHash !== accessTokenHash) return { action: "return-current" };+ if (!hasRefreshToken) {+ return {+ action: "needs-reauthorization",+ reason: "The MCP server rejected the access token and issued no refresh token. Reauthorize this service."+ };+ }+ return { action: "refresh" };+ }++ // Without an expiry the token is refreshed only when the upstream rejects it.+ if (!expiresAt || expiresWithinSeconds === undefined) return { action: "return-current" };+ const expiresAtMs = new Date(expiresAt).getTime();+ if (expiresAtMs > now.getTime() + expiresWithinSeconds * 1000) return { action: "return-current" };+ if (!hasRefreshToken) {+ return expiresAtMs <= now.getTime()+ ? {+ action: "needs-reauthorization",+ reason: "The access token expired and the MCP server issued no refresh token. Reauthorize this service."+ }+ : { action: "return-current" };+ }+ return { action: "refresh" };+};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.tsnew file mode 100644index 0000000000..bb20fc2624--- /dev/null+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.ts@@ -0,0 +1,169 @@+import { TGenericPermission } from "@app/lib/types";++import {+ AgentVaultCredentialType,+ AgentVaultOauthAuthorizationStatus,+ AgentVaultOauthStatus+} from "../agent-vault/agent-vault-enums";++export enum AgentVaultOauthRegistration {+ Dynamic = "dynamic",+ Manual = "manual"+}++export enum AgentVaultOauthClientAuthMethod {+ None = "none",+ ClientSecretBasic = "client_secret_basic",+ ClientSecretPost = "client_secret_post"+}++// Each non-conforming server fallback that was used, recorded on the credential so support can see why a+// server works the way it does.+export enum AgentVaultOauthCompatibility {+ NoProtectedResourceMetadata = "no-protected-resource-metadata",+ ResourceMissing = "resource-missing",+ ResourcePrefix = "resource-prefix",+ NoAuthorizationServerMetadata = "no-authorization-server-metadata",+ IssuerTrailingSlash = "issuer-trailing-slash",+ PkceUnadvertised = "pkce-unadvertised",+ RegistrationMinimal = "registration-minimal",+ ResourceRejected = "resource-rejected",+ ScopeCommaSeparated = "scope-comma-separated"+}++export const AGENT_VAULT_OAUTH_GRANT_TYPE = "authorization_code";++// The MCP authorization spec puts the access token in `Authorization: Bearer`, so it isn't configurable.+export const AGENT_VAULT_OAUTH_HEADER_NAME = "Authorization";+export const AGENT_VAULT_OAUTH_HEADER_PREFIX = "Bearer";++export type TAgentVaultOauthConfig = {+ type: AgentVaultCredentialType.OAuth;+ grantType: typeof AGENT_VAULT_OAUTH_GRANT_TYPE;+ // The server URL the tokens were authorized for.+ serverUrl: string;+ issuer: string;+ authorizationEndpoint: string;+ tokenEndpoint: string;+ // Null once the server rejected it (`resource-rejected`), so refresh stops sending it.+ resource: string | null;+ clientId: string;+ registration: AgentVaultOauthRegistration;+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod;+ compatibility: AgentVaultOauthCompatibility[];+ requestedScopes: string[];+ grantedScopes: string[];+ requiredScopes: string[];+ status: AgentVaultOauthStatus;+ expiresAt: string | null;+ accessTokenHash: string;+ authorizedBy: { userId: string; username: string } | null;+ authorizedAt: string | null;+ lastRefreshedAt: string | null;+ lastError: string | null;+};++// Sealed with the project cipher in `encryptedCredential`.+export type TAgentVaultOauthSecret = {+ accessToken: string;+ refreshToken?: string;+ clientSecret?: string;+};++export type TAgentVaultOauthAuthorization = {+ id: string;+ projectId: string;+ accessBundleId: string;+ // The service being reauthorized, null for a new service.+ serviceId: string | null;+ actorUserId: string;+ serverUrl: string;+ state: string;+ redirectUri: string;+ status: AgentVaultOauthAuthorizationStatus;+ error: string | null;+ issuer: string;+ issParameterSupported: boolean;+ authorizationEndpoint: string;+ tokenEndpoint: string;+ resource: string | null;+ clientId: string;+ registration: AgentVaultOauthRegistration;+ tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod;+ compatibility: AgentVaultOauthCompatibility[];+ requestedScopes: string[];+ grantedScopes: string[];+ expiresAt: string | null;+ accessTokenHash: string | null;+ // base64 of the project-cipher blob of `{ codeVerifier, clientSecret? }`.+ sealedPending: string;+ // base64 of the project-cipher blob of a TAgentVaultOauthSecret, set once authorized.+ sealedCredential: string | null;+};++export type TAgentVaultOauthAuthorizationView = {+ id: string;+ status: AgentVaultOauthAuthorizationStatus;+ error: string | null;+ scopes: string[];+};++export type TCreateAuthorizationDTO = {+ projectId: string;+ ctx: TGenericPermission;+ accessBundleId: string;+ serverUrl: string;+ serviceId?: string;+ clientId?: string;+ clientSecret?: string;+};++export type TCompleteAuthorizationDTO = {+ projectId: string;+ ctx: TGenericPermission;+ authorizationId: string;+ state: string;+ code?: string;+ iss?: string;+ error?: string;+ errorDescription?: string;+};++export type TGetAuthorizationDTO = {+ projectId: string;+ ctx: TGenericPermission;+ authorizationId: string;+};++export type TClaimAuthorizationDTO = {+ authorizationId: string;+ projectId: string;+ accessBundleId: string;+ // The service the PATCH is for, or undefined on create.+ serviceId?: string;+ ctx: TGenericPermission;+ serverUrl: string;+};++export type TResolvedOauthCredential = {+ type: "bearer";+ headerName: string;+ headerPrefix: string;+ value: string;+ source: "oauth";+ expiresAt: string | null;+};++export type TRefreshServiceTokenDTO = {+ serviceId: string;+ projectId: string;+ // On demand: the sha256 of the token the upstream rejected.+ rejectedTokenHash?: string;+ // From a `403 insufficient_scope` challenge.+ requiredScopes?: string[];+ // Lazy, from resolve: refresh when the token expires within this many seconds.+ expiresWithinSeconds?: number;+ // Where the caller will send the token. A service that moved since is a 409, never a token for the new server.+ // `serverUrl` undefined skips that half of the check.+ destination: { hostPattern: string; serverUrl?: string | null };+};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsnew file mode 100644index 0000000000..b27633f8ab--- /dev/null+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts@@ -0,0 +1,185 @@+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 {+ 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() }+}));++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",+ accessBundleId: "22222222-2222-4222-8222-222222222222",+ 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,+ position: 0,+ ...overrides+});++const setup = (refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>, rows = [serviceRow()]) => {+ const refreshServiceToken = vi.fn(refresh);+ 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 () => [] },+ 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()+ })+ },+ 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 }+ });+ return { service, refreshServiceToken };+};++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("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("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 --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 46cc6e2ee0..199b4b7a7e 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -10,6 +10,7 @@ import {import { PgSqlLock } from "@app/keystore/keystore";import {BadRequestError,+ ConflictError,ForbiddenRequestError,InternalServerError,NotFoundError,@@ -23,12 +24,27 @@ import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";-import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultOauthStatus,+ AgentVaultServiceType,+ AgentVaultTrafficPolicy+} from "../agent-vault/agent-vault-enums";import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";+import { TAgentVaultServiceConfig } from "../agent-vault/agent-vault-service-types";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 { TAgentVaultVariableDALFactory } from "../agent-vault-access-bundle/agent-vault-variable-dal";+import {+ AGENT_VAULT_SERVICE_MOVED_MESSAGE,+ TAgentVaultOauthServiceFactory+} from "../agent-vault-oauth/agent-vault-oauth-service";+import {+ AGENT_VAULT_OAUTH_HEADER_NAME,+ AGENT_VAULT_OAUTH_HEADER_PREFIX,+ TAgentVaultOauthConfig+} from "../agent-vault-oauth/agent-vault-oauth-types";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";@@ -50,6 +66,7 @@ import {THeartbeatDTO,TListProxiesDTO,TProxyByIdDTO,+ TRefreshCredentialDTO,TResolvedService,TResolveSessionDTO,TUpdateProxyDTO@@ -61,6 +78,8 @@ export const AGENT_VAULT_MAX_PROXIES_PER_ORG = 10;// Health is derived from the last heartbeat and the poll interval, never stored.const HEARTBEAT_MISSES_BEFORE_UNHEALTHY = 3;+const RESOLVE_REFRESH_BUDGET_MS = 4_000;+type TAgentVaultProxyServiceFactoryDep = {agentVaultProxyDAL: TAgentVaultProxyDALFactory;agentVaultResolveDAL: TAgentVaultResolveDALFactory;@@ -78,6 +97,7 @@ type TAgentVaultProxyServiceFactoryDep = {TResourceAuthMethodServiceFactory,"initAtCreate" | "mintToken" | "loginWithToken" | "revokeAccess">;+ agentVaultOauthService: Pick<TAgentVaultOauthServiceFactory, "refreshServiceToken">;};export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;@@ -95,7 +115,8 @@ export const agentVaultProxyServiceFactory = ({permissionService,kmsService,licenseService,- resourceAuthMethodService+ resourceAuthMethodService,+ agentVaultOauthService}: TAgentVaultProxyServiceFactoryDep) => {const isHealthy = (proxy: Pick<TAgentVaultProxies, "heartbeat" | "pollInterval" | "heartbeatTTL">) => {if (!proxy.heartbeat) return false;@@ -337,6 +358,19 @@ export const agentVaultProxyServiceFactory = ({value: secret.value};}+ // Sent in the bearer shape so a proxy that predates OAuth injects it unchanged; `source` is what tells a+ // newer one it may ask for a refresh.+ if (row.credentialType === AgentVaultCredentialType.OAuth) {+ const oauth = row.credentialConfig as TAgentVaultOauthConfig;+ return {+ type: "bearer",+ headerName: AGENT_VAULT_OAUTH_HEADER_NAME,+ headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,+ value: secret.accessToken,+ source: "oauth",+ expiresAt: oauth.expiresAt ?? null+ };+ }return { type: "basic", username: secret.username ?? "", password: secret.password ?? "" };};@@ -354,8 +388,9 @@ export const agentVaultProxyServiceFactory = ({accessBundleIdOf: Map<string, string>;decryptValue: (encryptedValue: Buffer) => string;}): Promise<TResolvedService[]> => {+ // An OAuth token is issued by the provider, never typed, so it holds no reference to expand.const sealedTextsOf = ({ credential, customHeaders, substitutions }: TResolvedService) => [- ...(credential.type === AgentVaultCredentialType.Bearer ? [credential.value] : []),+ ...(credential.type === AgentVaultCredentialType.Bearer && !credential.source ? [credential.value] : []),...(credential.type === AgentVaultCredentialType.Basic ? [credential.username, credential.password] : []),...customHeaders.map((header) => header.value),...substitutions.map((substitution) => substitution.value)@@ -396,7 +431,7 @@ export const agentVaultProxyServiceFactory = ({const expand = (text: string) => expandStoredVariableReferences(text, valueOf);let { credential } = service;- if (credential.type === AgentVaultCredentialType.Bearer) {+ if (credential.type === AgentVaultCredentialType.Bearer && !credential.source) {credential = { ...credential, value: expand(credential.value) };}// A typed username is trimmed on save, and a username can't start or end with a space (RFC 8265), so one a@@ -428,8 +463,12 @@ export const agentVaultProxyServiceFactory = ({return expanded;};- /** 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" });@@ -503,12 +542,85 @@ export const agentVaultProxyServiceFactory = ({groupIds: liveGroupIds});+ return { session, proxy, accessBundleIds };+ };++ /** Resolve services and decrypt their credentials. The proxy's JWT authorizes; the session token is a selector. */+ const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {+ const { session, proxy, accessBundleIds } = await $authorizeSession({ proxyId, orgId, sessionToken });+const rows = await agentVaultResolveDAL.findResolvableServices({sessionId: session.id,projectId: session.projectId,accessBundleIds});+ // A token that expires before the proxy's next poll is refreshed now, which also keeps proxies that can't+ // refresh on their own working. The proxy gives up on resolve after 15 seconds, and one refresh can wait on+ // another's lock and then on a slow provider, so resolve waits for all of them together for a short budget+ // only. A refresh that fails or is still running sends the stored token; one still running finishes in the+ // background and stores its result for the next poll.+ const refreshWithinSeconds = proxy.pollInterval + 60;+ const refreshedCredentials = new Map<string, TResolvedService["credential"]>();+ const dueForRefresh = rows.filter((row) => {+ if (row.credentialType !== AgentVaultCredentialType.OAuth) return false;+ const oauth = row.credentialConfig as TAgentVaultOauthConfig;+ return (+ oauth.status !== AgentVaultOauthStatus.NeedsReauthorization &&+ Boolean(oauth.expiresAt) &&+ new Date(oauth.expiresAt!).getTime() <= Date.now() + refreshWithinSeconds * 1000+ );+ });+ if (dueForRefresh.length) {+ let budgetSpent = false;+ const pending = new Set(dueForRefresh.map((row) => row.id));+ const refreshes = dueForRefresh.map((row) =>+ agentVaultOauthService+ .refreshServiceToken({+ serviceId: row.id,+ projectId: session.projectId,+ expiresWithinSeconds: refreshWithinSeconds,+ // The answer pairs this row's host with the credential, so a refreshed one has to be for the same server.+ destination: {+ hostPattern: row.hostPattern,+ serverUrl: (row.config as TAgentVaultServiceConfig | null)?.serverUrl ?? null+ }+ })+ .then(({ credential }) => {+ if (!budgetSpent) refreshedCredentials.set(row.id, credential);+ })+ .catch((error) => {+ if (error instanceof ConflictError) {+ logger.info(+ `agentVaultResolve: service moved during its OAuth refresh, sending the stored token until the next poll [sessionId=${session.id}] [serviceId=${row.id}]`+ );+ return;+ }+ logger.error(+ error,+ `agentVaultResolve: OAuth refresh failed, sending the stored token [sessionId=${session.id}] [serviceId=${row.id}]`+ );+ })+ .finally(() => pending.delete(row.id))+ );++ let budgetTimer: NodeJS.Timeout | undefined;+ await Promise.race([+ Promise.all(refreshes),+ new Promise<void>((resolve) => {+ budgetTimer = setTimeout(resolve, RESOLVE_REFRESH_BUDGET_MS);+ })+ ]);+ clearTimeout(budgetTimer);+ budgetSpent = true;++ if (pending.size) {+ logger.warn(+ `agentVaultResolve: OAuth refresh still running, sending the stored token [sessionId=${session.id}] [serviceIds=${[...pending].join(",")}]`+ );+ }+ }+const serviceIds = rows.map((row) => row.id);const [customHeaderRows, substitutionRows] = await Promise.all([agentVaultServiceCustomHeaderDAL.findByServiceIds(serviceIds),@@ -549,10 +661,11 @@ export const agentVaultProxyServiceFactory = ({id: row.id,name: row.name,accessBundleName: row.accessBundleName,+ type: row.type as AgentVaultServiceType,hostPattern: row.hostPattern,allowedMethods: row.allowedMethods,allowedPathPrefixes: row.allowedPathPrefixes,- credential: $decryptCredential(row, decryptor),+ credential: refreshedCredentials.get(row.id) ?? $decryptCredential(row, decryptor),customHeaders: customHeaderRows.filter((header) => header.serviceId === row.id).map((header) => ({ name: header.name, prefix: header.prefix, value: $decryptValue(header.encryptedValue) })),@@ -605,6 +718,47 @@ export const agentVaultProxyServiceFactory = ({};};+ // After the upstream rejected a token. Never audited, like resolve: it is proxy-driven and per request.+ const refreshCredential = async ({+ proxyId,+ orgId,+ sessionToken,+ serviceId,+ hostPattern,+ rejectedTokenHash,+ requiredScopes+ }: TRefreshCredentialDTO) => {+ const { session, accessBundleIds } = await $authorizeSession({ proxyId, orgId, sessionToken });+ const [row] = await agentVaultResolveDAL.findResolvableServices({+ sessionId: session.id,+ projectId: session.projectId,+ accessBundleIds,+ serviceId+ });+ if (!row) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found in this session` });+ if (row.credentialType !== AgentVaultCredentialType.OAuth) {+ throw new BadRequestError({+ message: `The service '${row.name}' doesn't use OAuth, so Infisical can't refresh its credential.`+ });+ }+ // The proxy retries with whatever comes back against the host it cached, so a service that moved since must+ // not hand it the new server's token. The refresh re-checks against the primary, which this replica read may+ // trail.+ if (row.hostPattern !== hostPattern) throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });++ const result = await agentVaultOauthService.refreshServiceToken({+ serviceId: row.id,+ projectId: session.projectId,+ rejectedTokenHash: rejectedTokenHash.toLowerCase(),+ requiredScopes,+ destination: { hostPattern }+ });+ logger.info(+ `agentVaultCredentialRefresh: answered [sessionId=${session.id}] [proxyId=${proxyId}] [serviceId=${row.id}] [status=${result.status}]`+ );+ return result;+ };+return {getProxyForAuth,listProxies,@@ -615,6 +769,7 @@ export const agentVaultProxyServiceFactory = ({revokeProxyAccess,enroll,heartbeat,- resolveSession+ resolveSession,+ refreshCredential};};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex ed74325f31..5f5954ec89 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -1,6 +1,6 @@import { TGenericPermission } from "@app/lib/types";-import { AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";+import { AgentVaultServiceType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";export type TAgentVaultProxyScoped = { projectId: string; ctx: TGenericPermission };@@ -51,15 +51,35 @@ export type TResolveSessionDTO = {hasSessionLogKey: boolean;};+export type TRefreshCredentialDTO = {+ proxyId: string;+ orgId: string;+ sessionToken: string;+ serviceId: string;+ // The host pattern of the cached service the proxy injected the rejected token into.+ hostPattern: string;+ rejectedTokenHash: string;+ requiredScopes?: string[];+};+export type TResolvedService = {id: string;name: string;accessBundleName: string;+ type: AgentVaultServiceType;hostPattern: string;allowedMethods: string[] | null;allowedPathPrefixes: string[] | null;credential:- | { type: "bearer"; headerName: string; headerPrefix: string; value: string }+ | {+ type: "bearer";+ headerName: string;+ headerPrefix: string;+ value: string;+ // Set only for an OAuth credential, which the proxy may ask to refresh.+ source?: "oauth";+ expiresAt?: string | null;+ }| { type: "basic"; username: string; password: string }| { type: "passthrough" };customHeaders: { name: string; prefix: string; value: string }[];diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.tsindex f635534972..857bd0996a 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts@@ -11,7 +11,9 @@ export type TResolveServiceRow = {name: string;accessBundleId: string;accessBundleName: string;+ type: string;hostPattern: string;+ config: unknown;credentialType: string;credentialConfig: unknown;encryptedCredential: Buffer | null;@@ -31,11 +33,14 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {{sessionId,projectId,- accessBundleIds+ accessBundleIds,+ serviceId}: {sessionId: string;projectId: string;accessBundleIds: string[] | null;+ // Narrows to one service, for a credential refresh that must stay inside the session's resolved set.+ serviceId?: string;},tx?: Knex): Promise<TResolveServiceRow[]> => {@@ -59,12 +64,15 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {);if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);+ if (serviceId) void query.where(`${TableName.AgentVaultService}.id`, serviceId);return (await query.select(db.ref("id").withSchema(TableName.AgentVaultService),db.ref("name").withSchema(TableName.AgentVaultService),+ db.ref("type").withSchema(TableName.AgentVaultService),db.ref("hostPattern").withSchema(TableName.AgentVaultService),+ db.ref("config").withSchema(TableName.AgentVaultService),db.ref("credentialType").withSchema(TableName.AgentVaultService),db.ref("credentialConfig").withSchema(TableName.AgentVaultService),db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 4b21f40d9d..fc8d2dadf8 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -21,7 +21,8 @@ agent-vault-access-bundle/ bundles, services, variables, credential encryptionagent-vault-member/ product membership (list, add, role, remove)agent-vault-session/ mint, revoke, list, getagent-vault-project/ the per-org project's lazy bootstrap and resolver-agent-vault-proxy/ login (enrollment), heartbeat, resolve+agent-vault-proxy/ login (enrollment), heartbeat, resolve, credential refresh+agent-vault-oauth/ OAuth for MCP services: discovery, client registration, authorizations, refreshagent-vault-session-log/ storage settings, chunk ingest, playback```@@ -232,8 +233,9 @@ path decides what a service can reach, so it stays literal.- The KMS cipher pair is project-scoped (`KmsDataKey.SecretManager`) and built once per resolve.- `credentialType` is a column and `credentialConfig` the plaintext half (header name, prefix), so a list page- renders without a decrypt and a new credential type is a config entry, not a migration. For basic, the- username is sealed with the password: some APIs put the whole key in the username.+ renders without a decrypt. The column has a CHECK constraint, so a new credential type needs a migration that+ drops and re-adds `agent_vault_services_credential_type_check`. For basic, the username is sealed with the+ password: some APIs put the whole key in the username.- A service update is a patch. `AgentVaultCredentialUpdateSchema` makes every field optional and`mergeCredential` overlays what arrived. Never reuse `AgentVaultBearerConfigSchema` on that path: its`.default()`s would reset an omitted `headerName` to `Authorization`.@@ -241,6 +243,66 @@ path decides what a service can reach, so it stays literal.leaves 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, and a client is reused only with the issuer it was+ registered at.+- **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 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` takes the host pattern the proxy+ cached and answers 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`. `invalid_grant` moves the service to needs reauthorization.+- **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. A refresh waits+ about 3 seconds for another's lock, then answers with what is stored, and its token requests (the+ `invalid_target` retry included) share one 7 second budget. Keep that sum under the proxy's timeout.+- **Neither refreshes nor resolve are audited.** Connect and reauthorize are (`AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE`).+- **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.+## Session logsMetadata only (method, host, path, status, decision), never bodies, headers or the query string. The agent isdiff --git a/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.tsindex 9f0bf11ea2..8bcb66e632 100644--- a/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts@@ -1,11 +1,12 @@import RE2 from "re2";import { z } from "zod";+import type { TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";import { AgentVaultCredentialType } from "./agent-vault-enums";// credentialConfig is plaintext jsonb, read on the list page without a decrypt; encryptedCredential is-// the KMS-sealed secret, NULL exactly when the type is passthrough. The discriminator is a column rather-// than a field inside the blob, so a new credential type needs no migration.+// the KMS-sealed secret, NULL exactly when the type is passthrough. The discriminator is a column with a+// CHECK constraint, so a new credential type needs a migration that widens it.// The characters RFC 7230 allows. Go's HTTP client refuses to send anything else, so a name saved// without this check 502s every request through the service.@@ -67,7 +68,9 @@ export const AgentVaultCredentialConfigSchema = z.discriminatedUnion("type", [AgentVaultPassthroughConfigSchema.extend({ type: z.literal(AgentVaultCredentialType.Passthrough) })]);-export type TAgentVaultCredentialConfig = z.infer<typeof AgentVaultCredentialConfigSchema>;+// OAuth's config is written whole from a completed authorization and patched by refresh, never parsed from a+// request, so it has a type rather than a schema.+export type TAgentVaultCredentialConfig = z.infer<typeof AgentVaultCredentialConfigSchema> | TAgentVaultOauthConfig;export const AgentVaultSecretSchema = z.discriminatedUnion("type", [z.object({ type: z.literal(AgentVaultCredentialType.Bearer), value: z.string().min(1).max(8192) }),diff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.tsindex 1316ba44cb..15870bfae8 100644--- a/backend/src/ee/services/agent-vault/agent-vault-enums.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts@@ -1,7 +1,30 @@export enum AgentVaultCredentialType {Bearer = "bearer",Basic = "basic",- Passthrough = "passthrough"+ Passthrough = "passthrough",+ OAuth = "oauth"+}++export enum AgentVaultOauthStatus {+ Connected = "connected",+ NeedsReauthorization = "needs-reauthorization",+ NeedsAdditionalScopes = "needs-additional-scopes"+}++export enum AgentVaultOauthAuthorizationStatus {+ Pending = "pending",+ Authorized = "authorized",+ Failed = "failed"+}++export enum AgentVaultServiceType {+ Http = "http",+ Mcp = "mcp"+}++export enum AgentVaultMcpTransport {+ StreamableHttp = "streamable-http",+ Sse = "sse"}export enum AgentVaultMemberType {diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-types.test.ts b/backend/src/ee/services/agent-vault/agent-vault-service-types.test.tsnew file mode 100644index 0000000000..ab8bea022e--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-service-types.test.ts@@ -0,0 +1,166 @@+import { describe, expect, test } from "vitest";++import { AgentVaultCredentialType, AgentVaultMcpTransport, AgentVaultServiceType } from "./agent-vault-enums";+import {+ AGENT_VAULT_SERVICE_TYPES,+ agentVaultMcpServerUrlSchema,+ assertCredentialTypeSupported,+ assertServiceFieldsSupported,+ buildServiceConfig,+ deriveMcpHostPattern,+ findUnsupportedServiceFields,+ resolveServiceHostPattern+} from "./agent-vault-service-types";++const http = AGENT_VAULT_SERVICE_TYPES[AgentVaultServiceType.Http];+const mcp = AGENT_VAULT_SERVICE_TYPES[AgentVaultServiceType.Mcp];++describe("deriving an MCP service's host pattern", () => {+ test.each([+ { url: "https://mcp.linear.app/mcp", pattern: "mcp.linear.app", why: "no port means 443" },+ { url: "https://MCP.Linear.App/mcp", pattern: "mcp.linear.app", why: "lowercased" },+ { url: "https://mcp.linear.app:443/mcp", pattern: "mcp.linear.app", why: "an explicit 443 is dropped" },+ { url: "https://mcp.example.com:8443/mcp", pattern: "mcp.example.com:8443", why: "another port is kept" },+ { url: "https://mcp.example.com.:8443/", pattern: "mcp.example.com:8443", why: "trailing dot" },+ { url: "https://10.0.1.5:8200/mcp", pattern: "10.0.1.5:8200", why: "IPv4 literal" },+ { url: "https://[::1]:8443/mcp", pattern: "[::1]:8443", why: "IPv6 literal" },+ { url: "https://api.githubcopilot.com/mcp/", pattern: "api.githubcopilot.com", why: "path ignored" }+ ])("$url -> $pattern ($why)", ({ url, pattern }) => {+ expect(deriveMcpHostPattern(url)).toBe(pattern);+ expect(resolveServiceHostPattern(mcp, buildServiceConfig(mcp, { serverUrl: url, transport: "sse" }), "x.com")).toBe(+ pattern+ );+ });+});++describe("the server URL", () => {+ test.each([+ "https://mcp.linear.app/mcp",+ " https://mcp.notion.com/mcp ",+ "https://mcp.example.com:8443/sse",+ "HTTPS://mcp.example.com/mcp",+ "https://mcp.example.com/日本語/😀"+ ])("accepts %s", (url) => {+ expect(agentVaultMcpServerUrlSchema.safeParse(url).success).toBe(true);+ });++ test.each([+ { url: "", why: "empty" },+ { url: "http://mcp.example.com/mcp", why: "plaintext http" },+ { url: "mcp.example.com/mcp", why: "no scheme" },+ { url: "https:mcp.example.com", why: "the URL parser would accept this as https://" },+ { url: "https://user:[email protected]/mcp", why: "userinfo" },+ { url: "https://[email protected]/mcp", why: "username only" },+ { url: "https://mcp.example.com/mcp#frag", why: "fragment" },+ { url: "https://mcp.example.com/mcp#", why: "empty fragment" },+ { url: "https://*.example.com/mcp", why: "wildcard host" },+ { url: "https://mcp.exa mple.com/", why: "space" },+ { url: "https://mcp.example.com/\nmcp", why: "newline the URL parser would strip" },+ { url: "https://mcp.example.com/\ud800", why: "a lone high surrogate that jsonb cannot store" },+ { url: "https://mcp.example.com/\udfff", why: "a lone low surrogate that jsonb cannot store" },+ { url: "https://mcp_x.example.com/", why: "a host the host grammar can't match" },+ { url: `https://mcp.example.com/${"a".repeat(2048)}`, why: "too long" }+ ])("rejects $why", ({ url }) => {+ expect(agentVaultMcpServerUrlSchema.safeParse(url).success).toBe(false);+ });+});++describe("type config", () => {+ test("an MCP config needs both fields", () => {+ expect(() => buildServiceConfig(mcp, { serverUrl: "https://mcp.example.com/mcp" })).toThrow(/transport/);+ expect(() => buildServiceConfig(mcp, { transport: AgentVaultMcpTransport.Sse })).toThrow(/serverUrl/);+ });++ test("an update overlays what was sent on what is stored", () => {+ const stored = { serverUrl: "https://mcp.example.com/mcp", transport: AgentVaultMcpTransport.StreamableHttp };+ expect(buildServiceConfig(mcp, { transport: AgentVaultMcpTransport.Sse, serverUrl: undefined }, stored)).toEqual({+ serverUrl: "https://mcp.example.com/mcp",+ transport: AgentVaultMcpTransport.Sse+ });+ });++ test("an invalid URL is a readable error naming the field", () => {+ expect(() =>+ buildServiceConfig(mcp, { serverUrl: "http://mcp.example.com", transport: AgentVaultMcpTransport.Sse })+ ).toThrow(/'serverUrl': The server URL must start with https:\/\//);+ });++ test("a query string is refused, since the URL is stored and shown in plaintext", () => {+ expect(() =>+ buildServiceConfig(mcp, {+ serverUrl: "https://mcp.example.com/mcp?token=abc",+ transport: AgentVaultMcpTransport.StreamableHttp+ })+ ).toThrow(+ "'serverUrl': Server URLs can't include a query string, since it is stored and shown in plaintext. Put a token in the Bearer token or a custom header instead."+ );+ expect(agentVaultMcpServerUrlSchema.safeParse("https://mcp.example.com/mcp?").success).toBe(false);+ });++ test("an HTTP service's config is empty and its host pattern is what was entered", () => {+ const config = buildServiceConfig(http, {});+ expect(config).toEqual({});+ expect(resolveServiceHostPattern(http, config, "api.github.com")).toBe("api.github.com");+ expect(() => resolveServiceHostPattern(http, config, undefined)).toThrow(/host pattern/);+ });+});++describe("fields a type does not take", () => {+ test("an MCP service refuses the HTTP-only fields", () => {+ expect(+ findUnsupportedServiceFields(mcp, {+ hostPattern: "api.github.com",+ allowedMethods: null,+ allowedPathPrefixes: ["/v1"],+ substitutions: [],+ customHeaders: [],+ serverUrl: "https://mcp.example.com/mcp",+ transport: AgentVaultMcpTransport.Sse+ })+ ).toEqual(["hostPattern", "allowedMethods", "allowedPathPrefixes", "substitutions"]);+ expect(() => assertServiceFieldsSupported(mcp, { hostPattern: "api.github.com" })).toThrow(+ "An MCP service doesn't take 'hostPattern'."+ );+ });++ test("an HTTP service refuses the MCP-only fields", () => {+ expect(+ findUnsupportedServiceFields(http, {+ hostPattern: "api.github.com",+ allowedMethods: ["GET"],+ substitutions: [],+ serverUrl: "https://mcp.example.com/mcp",+ transport: AgentVaultMcpTransport.Sse+ })+ ).toEqual(["serverUrl", "transport"]);+ expect(() => assertServiceFieldsSupported(http, { serverUrl: "x", transport: "sse" })).toThrow(+ "An HTTP service doesn't take 'serverUrl' or 'transport'. A server URL and transport apply only to MCP services."+ );+ });++ test("fields left out are not refused", () => {+ expect(findUnsupportedServiceFields(mcp, { hostPattern: undefined, substitutions: undefined })).toEqual([]);+ });+});++describe("credential types", () => {+ test("an MCP service takes a bearer token or OAuth", () => {+ expect(() => assertCredentialTypeSupported(mcp, AgentVaultCredentialType.Bearer)).not.toThrow();+ expect(() => assertCredentialTypeSupported(mcp, AgentVaultCredentialType.OAuth)).not.toThrow();+ expect(() => assertCredentialTypeSupported(mcp, AgentVaultCredentialType.Basic)).toThrow(+ "An MCP service can't use basic auth as its credential. Use a bearer token or OAuth."+ );+ expect(() => assertCredentialTypeSupported(mcp, AgentVaultCredentialType.Passthrough)).toThrow();+ });++ test("an HTTP service takes every credential type but OAuth", () => {+ Object.values(AgentVaultCredentialType)+ .filter((type) => type !== AgentVaultCredentialType.OAuth)+ .forEach((type) => {+ expect(() => assertCredentialTypeSupported(http, type)).not.toThrow();+ });+ expect(() => assertCredentialTypeSupported(http, AgentVaultCredentialType.OAuth)).toThrow(+ "An HTTP service can't use OAuth as its credential."+ );+ });+});diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-types.ts b/backend/src/ee/services/agent-vault/agent-vault-service-types.tsnew file mode 100644index 0000000000..f757e7e9aa--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-service-types.ts@@ -0,0 +1,229 @@+import RE2 from "re2";+import { z } from "zod";++import { BadRequestError } from "@app/lib/errors";++import {+ AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,+ AGENT_VAULT_NO_CONTROL_CHARS_RE+} from "./agent-vault-credential-schemas";+import { AgentVaultCredentialType, AgentVaultMcpTransport, AgentVaultServiceType } from "./agent-vault-enums";+import { AGENT_VAULT_DEFAULT_PORT, parseHostPatterns } from "./agent-vault-host-pattern-fns";++export const AGENT_VAULT_MAX_SERVER_URL_LENGTH = 2048;++const SERVER_URL_EXAMPLE = "https://mcp.example.com/mcp";+const SERVER_URL_SCHEME_RE = new RE2(/^https:\/\//i);+const TRAILING_HOST_DOT_RE = new RE2(/\.$/);++const describeServerUrlProblem = (raw: string): string | null => {+ if (!AGENT_VAULT_NO_CONTROL_CHARS_RE.test(raw)) return AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE;+ // URL replaces lone surrogates, but keeping the raw value would make jsonb reject the write.+ if (+ [...raw].some((character) => {+ const codePoint = character.codePointAt(0)!;+ return codePoint >= 0xd800 && codePoint <= 0xdfff;+ })+ )+ return "The server URL contains invalid text. Copy the URL from the browser and try again.";+ if ([...raw].some((character) => !character.trim())) return "The server URL can't contain spaces.";+ // Checked on the raw text because the URL parser accepts "https:host" and backslashes as if they were "https://".+ if (!SERVER_URL_SCHEME_RE.test(raw)) {+ return `The server URL must start with https://, as in ${SERVER_URL_EXAMPLE}. Agent Vault only brokers MCP servers over HTTPS.`;+ }++ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ return `The server URL isn't a valid URL. Enter the full address, as in ${SERVER_URL_EXAMPLE}.`;+ }++ if (url.username || url.password) {+ return "The server URL can't contain a username or password. Put the secret in the service's credential instead.";+ }+ if (raw.includes("#")) return "The server URL can't contain a fragment (the part after #).";+ if (raw.includes("?")) {+ return "Server URLs can't include a query string, since it is stored and shown in plaintext. Put a token in the Bearer token or a custom header instead.";+ }++ const { patterns, errors } = parseHostPatterns(url.hostname, "server URL");+ if (errors.length || patterns.length !== 1) {+ return `The server URL's host "${url.hostname}" isn't a host name or IP address Agent Vault can match.`;+ }+ if (patterns[0].isWildcard) return "The server URL must name a specific host, not a wildcard.";++ return null;+};++export const agentVaultMcpServerUrlSchema = z+ .string()+ .trim()+ .min(1, "Enter the MCP server's URL.")+ .max(+ AGENT_VAULT_MAX_SERVER_URL_LENGTH,+ `The server URL can be at most ${AGENT_VAULT_MAX_SERVER_URL_LENGTH} characters.`+ )+ .superRefine((raw, ctx) => {+ const problem = describeServerUrlProblem(raw);+ if (problem) ctx.addIssue({ code: z.ZodIssueCode.custom, message: problem });+ });++// Path and query are not part of the match: the SSE transport posts to a message endpoint the server only+// announces at runtime. A portless pattern means 443, so an explicit :443 is dropped to keep one spelling.+export const deriveMcpHostPattern = (serverUrl: string): string => {+ const url = new URL(serverUrl);+ const host = url.hostname.replace(TRAILING_HOST_DOT_RE, "").toLowerCase();+ return url.port && url.port !== AGENT_VAULT_DEFAULT_PORT ? `${host}:${url.port}` : host;+};++export const AgentVaultHttpServiceConfigSchema = z.object({});++export const AgentVaultMcpServiceConfigSchema = z.object({+ serverUrl: agentVaultMcpServerUrlSchema,+ transport: z.nativeEnum(AgentVaultMcpTransport)+});++export type TAgentVaultMcpServiceConfig = z.infer<typeof AgentVaultMcpServiceConfigSchema>;++export type TAgentVaultServiceConfig =+ | TAgentVaultMcpServiceConfig+ | { [K in keyof TAgentVaultMcpServiceConfig]?: never };++export type TAgentVaultServiceTypeDefinition = {+ type: AgentVaultServiceType;+ label: string;+ configSchema: z.ZodObject<z.ZodRawShape>;+ allowedCredentialTypes: AgentVaultCredentialType[];+ // Null when the caller enters the host pattern itself.+ deriveHostPattern: ((config: Record<string, unknown>) => string) | null;+ supportsRequestRules: boolean;+ supportsTransformations: { customHeaders: boolean; substitutions: boolean };+ // Appended to the refusal when a request sends a field this type does not take.+ unsupportedFieldHint: string;+};++export const AGENT_VAULT_SERVICE_TYPES: Record<AgentVaultServiceType, TAgentVaultServiceTypeDefinition> = {+ [AgentVaultServiceType.Http]: {+ type: AgentVaultServiceType.Http,+ label: "HTTP",+ configSchema: AgentVaultHttpServiceConfigSchema,+ allowedCredentialTypes: [+ AgentVaultCredentialType.Bearer,+ AgentVaultCredentialType.Basic,+ AgentVaultCredentialType.Passthrough+ ],+ deriveHostPattern: null,+ supportsRequestRules: true,+ supportsTransformations: { customHeaders: true, substitutions: true },+ unsupportedFieldHint: "A server URL and transport apply only to MCP services."+ },+ [AgentVaultServiceType.Mcp]: {+ type: AgentVaultServiceType.Mcp,+ label: "MCP",+ configSchema: AgentVaultMcpServiceConfigSchema,+ allowedCredentialTypes: [AgentVaultCredentialType.Bearer, AgentVaultCredentialType.OAuth],+ deriveHostPattern: (config) => deriveMcpHostPattern((config as TAgentVaultMcpServiceConfig).serverUrl),+ supportsRequestRules: false,+ supportsTransformations: { customHeaders: true, substitutions: false },+ unsupportedFieldHint:+ "Its host comes from 'serverUrl', and method, path and substitution rules apply only to HTTP services."+ }+};++export const getAgentVaultServiceType = (type: string): TAgentVaultServiceTypeDefinition => {+ const definition = AGENT_VAULT_SERVICE_TYPES[type as AgentVaultServiceType];+ if (!definition) throw new BadRequestError({ message: `Unknown service type '${type}'` });+ return definition;+};++const CONFIG_FIELDS = [+ ...new Set(+ Object.values(AGENT_VAULT_SERVICE_TYPES).flatMap((definition) => Object.keys(definition.configSchema.shape))+ )+];++// Every field a service request can carry whose acceptance depends on the type. Common fields (name, credential)+// are not listed: every type takes them.+export type TAgentVaultServiceTypedFields = {+ hostPattern?: unknown;+ allowedMethods?: unknown;+ allowedPathPrefixes?: unknown;+ customHeaders?: unknown;+ substitutions?: unknown;+} & Record<string, unknown>;++export const findUnsupportedServiceFields = (+ definition: TAgentVaultServiceTypeDefinition,+ fields: TAgentVaultServiceTypedFields+): string[] => {+ const supported: Record<string, boolean> = {+ hostPattern: definition.deriveHostPattern === null,+ allowedMethods: definition.supportsRequestRules,+ allowedPathPrefixes: definition.supportsRequestRules,+ customHeaders: definition.supportsTransformations.customHeaders,+ substitutions: definition.supportsTransformations.substitutions,+ ...Object.fromEntries(CONFIG_FIELDS.map((field) => [field, field in definition.configSchema.shape]))+ };+ return Object.keys(supported).filter((field) => !supported[field] && fields[field] !== undefined);+};++const quoteList = (fields: string[]) => {+ const quoted = fields.map((field) => `'${field}'`);+ return quoted.length > 1 ? `${quoted.slice(0, -1).join(", ")} or ${quoted[quoted.length - 1]}` : quoted[0];+};++export const assertServiceFieldsSupported = (+ definition: TAgentVaultServiceTypeDefinition,+ fields: TAgentVaultServiceTypedFields+) => {+ const unsupported = findUnsupportedServiceFields(definition, fields);+ if (!unsupported.length) return;+ throw new BadRequestError({+ message: `An ${definition.label} service doesn't take ${quoteList(unsupported)}. ${definition.unsupportedFieldHint}`+ });+};++const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {+ [AgentVaultCredentialType.Bearer]: "a bearer token",+ [AgentVaultCredentialType.Basic]: "basic auth",+ [AgentVaultCredentialType.Passthrough]: "pass-through",+ [AgentVaultCredentialType.OAuth]: "OAuth"+};++export const assertCredentialTypeSupported = (+ definition: TAgentVaultServiceTypeDefinition,+ credentialType: AgentVaultCredentialType+) => {+ if (definition.allowedCredentialTypes.includes(credentialType)) return;+ const allowed = definition.allowedCredentialTypes.map((type) => CREDENTIAL_LABELS[type]);+ throw new BadRequestError({+ message: `An ${definition.label} service can't use ${CREDENTIAL_LABELS[credentialType]} as its credential. Use ${allowed.join(" or ")}.`+ });+};++// `incoming` holds only the config fields the request sent; on an update the rest come from what is stored.+export const buildServiceConfig = (+ definition: TAgentVaultServiceTypeDefinition,+ incoming: Record<string, unknown>,+ stored: unknown = {}+): TAgentVaultServiceConfig => {+ const sent = Object.fromEntries(Object.entries(incoming).filter(([, value]) => value !== undefined));+ const parsed = definition.configSchema.safeParse({ ...((stored ?? {}) as Record<string, unknown>), ...sent });+ if (!parsed.success) {+ const [issue] = parsed.error.issues;+ const field = issue.path.join(".");+ throw new BadRequestError({ message: field ? `'${field}': ${issue.message}` : issue.message });+ }+ return parsed.data as TAgentVaultServiceConfig;+};++export const resolveServiceHostPattern = (+ definition: TAgentVaultServiceTypeDefinition,+ config: TAgentVaultServiceConfig,+ hostPattern: string | undefined+): string => {+ if (definition.deriveHostPattern) return definition.deriveHostPattern(config);+ if (!hostPattern) throw new BadRequestError({ message: `An ${definition.label} service needs a host pattern.` });+ return hostPattern;+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 30faead9fb..a20665bc7d 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -815,6 +815,7 @@ export enum EventType {AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",+ AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE = "agent-vault-service-credential-authorize",AGENT_VAULT_VARIABLE_CREATE = "agent-vault-variable-create",AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",@@ -6472,8 +6473,15 @@ interface AgentVaultServiceCreateEvent {accessBundleName: string;serviceId: string;name: string;+ serviceType: string;+ // MCP services only.+ serverUrl?: string;+ transport?: string;hostPattern: string;credentialType: string;+ // OAuth credentials only.+ oauthIssuer?: string;+ oauthScopes?: string[];headerName?: string;headerPrefix?: string;allowedMethods?: string[] | null;@@ -6492,8 +6500,15 @@ interface AgentVaultServiceUpdateEvent {accessBundleName: string;serviceId: string;name?: string;+ // The service's type, which never changes, so present on every update.+ serviceType: string;+ serverUrl?: string;+ transport?: string;hostPattern?: string;credentialType?: string;+ // Present when the update connected or reauthorized an OAuth credential.+ oauthIssuer?: string;+ oauthScopes?: string[];headerName?: string;headerPrefix?: string;allowedMethods?: string[] | null;@@ -6508,6 +6523,21 @@ interface AgentVaultServiceUpdateEvent {};}+// On connect (create) and reauthorize (update). Refreshes are proxy-driven and not audited, like resolve.+interface AgentVaultServiceCredentialAuthorizeEvent {+ type: EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE;+ metadata: {+ accessBundleId: string;+ accessBundleName: string;+ serviceId: string;+ name: string;+ serverUrl?: string;+ oauthIssuer: string;+ oauthScopes: string[];+ reauthorization: boolean;+ };+}+interface AgentVaultServiceDeleteEvent {type: EventType.AGENT_VAULT_SERVICE_DELETE;metadata: {@@ -8549,6 +8579,7 @@ export type Event =| AgentVaultServiceCreateEvent| AgentVaultServiceUpdateEvent| AgentVaultServiceDeleteEvent+ | AgentVaultServiceCredentialAuthorizeEvent| AgentVaultVariableCreateEvent| AgentVaultVariableUpdateEvent| AgentVaultVariableDeleteEventdiff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex c78303d43f..6b2018c6f3 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -168,6 +168,11 @@ 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,CertDashboardStats: (projectId: string) => `cert-dashboard-stats:${projectId}` as const,OrgSecretScanningFindingsCount: (orgId: string) => `org-secret-scanning-findings-count:${orgId}` as const,diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex ae0c819636..167554da43 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4426,6 +4426,30 @@ export const AGENT_VAULT = {SERVICE: {serviceId: "The ID of the service.",name: "The name of the service.",+ type: "The kind of service. `http`, the default, brokers an HTTP API matched by host pattern. `mcp` brokers a remote MCP server, matched by the host of its server URL. Can't be changed after the service is created.",+ config:+ "Settings specific to the service's type. Empty for an `http` service. For an `mcp` service, its `serverUrl` and `transport`.",+ serverUrl:+ "The MCP server's full URL, as in `https://mcp.example.com/mcp`. Must use `https`, with no username, password, query string or fragment. The service covers this URL's host, plus its port when that is not 443, which is returned as `hostPattern`.",+ transport: "How the agent talks to the MCP server: `streamable-http`, or `sse` for the legacy HTTP+SSE transport.",+ mcpCredential:+ "The credential the proxy attaches to requests to the MCP server. An MCP service takes a bearer token, or `oauth` with the `authorizationId` of a completed OAuth authorization. An OAuth token is always sent as `Authorization: Bearer <token>`.",+ authorizationId:+ "The ID of a completed OAuth authorization for this service's server URL, started by the same user. Each authorization can be used once.",+ updateAuthorizationId:+ "The ID of a completed OAuth authorization, to reauthorize the service or switch it to OAuth. To keep the stored tokens, leave `credential` out.",+ oauthStatus:+ "Whether the OAuth connection works: `connected`, `needs-reauthorization` (the tokens can no longer be refreshed), or `needs-additional-scopes` (the MCP server asked for scopes the connection lacks).",+ oauthIssuer: "The OAuth authorization server that issued the tokens.",+ oauthGrantedScopes: "The scopes the authorization server granted.",+ oauthRequiredScopes: "Scopes the MCP server asked for that the connection lacks. Reauthorize to request them.",+ oauthExpiresAt:+ "When the current access token expires, or null if the server didn't say. Infisical refreshes it before then.",+ oauthAuthorizedBy: "The user who authorized the connection.",+ oauthAuthorizedByUserId: "The ID of the user who authorized the connection.",+ oauthAuthorizedByUsername: "The username of the user who authorized the connection.",+ oauthAuthorizedAt: "When the connection was last authorized.",+ oauthLastError: "The last refresh failure, if any. Never contains a token.",hostPattern:"A comma-separated set of hosts this service covers, each optionally with a port (defaults to `443`). A leading `*.` wildcard matches exactly one label. Paths are not supported.",headerName: "The header the credential is written to. Defaults to `Authorization`.",@@ -4469,6 +4493,41 @@ export const AGENT_VAULT = {referenceCustomHeaderId: "The custom header whose value uses the variable.",referenceSubstitutionId: "The substitution whose value uses the variable."},+ 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 MCP service being reauthorized. Its OAuth client is reused, and its granted and required scopes are requested.",+ 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.",+ registrationRequired:+ "True when the server can't register Infisical as a client by itself. 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.",+ registrationError:+ "Why the server's registration endpoint refused to register Infisical, when it did. Null when the server has no registration endpoint, or when registration wasn't needed.",+ 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.",diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.tsindex c52daf13d8..afb744bd37 100644--- a/backend/src/server/config/rateLimiter.ts+++ b/backend/src/server/config/rateLimiter.ts@@ -107,6 +107,18 @@ export const agentVaultResolveLimit: RateLimitOptions = {}};+// Its own bucket, so a proxy retrying refreshes against a failing provider can't eat into resolve. A refresh+// follows an upstream 401 or 403, so steady traffic needs few; this leaves room for many sessions at once.+export const agentVaultCredentialRefreshLimit: RateLimitOptions = {+ timeWindow: 60 * 1000,+ hook: "preValidation",+ max: 600,+ keyGenerator: (req) => {+ const actorId = (req as { permission?: { id?: string } }).permission?.id;+ return actorId ? `agent-vault-credential-refresh:${actorId}` : req.realIp;+ }+};+export const agentVaultSessionLogChunkLimit: RateLimitOptions = {timeWindow: 60 * 1000,hook: "preValidation",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 7fe458cf23..740492798c 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -33,6 +33,7 @@ import { agentVaultServiceVariableReferenceDALFactory } from "@app/ee/services/aimport { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-variable-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 { 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";@@ -1981,6 +1982,15 @@ export const registerRoutes = async (const agentVaultResolveDAL = agentVaultResolveDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);+ const agentVaultOauthService = agentVaultOauthServiceFactory({+ keyStore,+ kmsService,+ agentVaultServiceDAL,+ agentVaultAccessBundleDAL,+ permissionService,+ membershipDAL+ });+const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({agentVaultAccessBundleDAL,agentVaultServiceDAL,@@ -1995,6 +2005,7 @@ export const registerRoutes = async (agentVaultMemberDAL,userGroupMembershipDAL,identityGroupMembershipDAL,+ agentVaultOauthService,userDAL,groupDAL,identityDAL@@ -2123,7 +2134,8 @@ export const registerRoutes = async (permissionService,kmsService,licenseService,- resourceAuthMethodService+ resourceAuthMethodService,+ agentVaultOauthService});const relayService = relayServiceFactory({@@ -4659,6 +4671,7 @@ export const registerRoutes = async (pamProjectResolver,agentVaultProjectResolver,agentVaultAccessBundle: agentVaultAccessBundleService,+ agentVaultOauth: agentVaultOauthService,agentVaultProxy: agentVaultProxyService,agentVaultSession: agentVaultSessionService,agentVaultSessionLog: agentVaultSessionLogService,diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 1277e34dc1..a497097c80 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -2,6 +2,7 @@ import { IdentityAuthMethod, ProjectType, SecretFolderRole } from "@app/db/schemimport {AgentVaultCredentialType,AgentVaultMemberType,+ AgentVaultServiceType,AgentVaultTrafficPolicy} from "@app/ee/services/agent-vault/agent-vault-enums";import {@@ -2448,6 +2449,7 @@ export type TAgentVaultServiceCreatedEvent = {properties: TAgentVaultEventBase & {accessBundleId: string;serviceId: string;+ serviceType: AgentVaultServiceType;credentialType: AgentVaultCredentialType;hostPatternCount: number;allowedMethodCount: number;@@ -2463,6 +2465,7 @@ export type TAgentVaultServiceUpdatedEvent = {properties: TAgentVaultEventBase & {accessBundleId: string;serviceId: string;+ serviceType: AgentVaultServiceType;credentialType: AgentVaultCredentialType;hostPatternCount: number;allowedMethodCount: number;diff --git a/frontend/src/components/agent-vault/ServiceIconStack.tsx b/frontend/src/components/agent-vault/ServiceIconStack.tsxindex 0977eb06d4..f9612b9dc6 100644--- a/frontend/src/components/agent-vault/ServiceIconStack.tsx+++ b/frontend/src/components/agent-vault/ServiceIconStack.tsx@@ -4,7 +4,7 @@ import { GlobeIcon } from "lucide-react";import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";import { cn } from "@app/components/v3/utils";-import { findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";+import { findAnyTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";import { TAgentVaultService } from "@app/hooks/api/agentVault/types";type TServiceIcon = {@@ -22,7 +22,7 @@ const labelOf = (pattern: string) => {};const iconFromHostPattern = (hostPattern: string): TServiceIcon => {- const template = findTemplateForHostPattern(hostPattern);+ const template = findAnyTemplateForHostPattern(hostPattern);return { label: template?.name ?? labelOf(hostPattern), image: template?.image };};@@ -104,7 +104,7 @@ export const ServiceIconStack = ({services? services.map((service) => ({label: service.name,- image: findTemplateForHostPattern(service.hostPattern)?.image+ image: findAnyTemplateForHostPattern(service.hostPattern)?.image})): iconsFromHostPatterns(hostPatterns),[hostPatterns, services]diff --git a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsxindex 5be2c2b9e2..967834b1b0 100644--- a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx+++ b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx@@ -1,14 +1,49 @@-import { useMemo, useState } from "react";+import { ReactNode, useMemo, useState } from "react";import { GlobeIcon, PlusIcon, SearchIcon } from "lucide-react";-import { InputGroup, InputGroupAddon, InputGroupInput } from "@app/components/v3";+import {+ Badge,+ Button,+ CardTitle,+ InputGroup,+ InputGroupAddon,+ InputGroupInput+} from "@app/components/v3";import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";+import { cn } from "@app/components/v3/utils";import {+ AGENT_VAULT_MCP_TEMPLATES,AGENT_VAULT_TEMPLATES,AgentVaultTemplate,AgentVaultTemplateCategory,POPULAR_AGENT_VAULT_TEMPLATES} from "@app/helpers/agentVaultTemplates";+import { AgentVaultServiceType } from "@app/hooks/api/agentVault";++enum TypeFilter {+ All = "all",+ Http = "http",+ Mcp = "mcp"+}++const MCP_SECTION_DESCRIPTION =+ "Remote MCP servers. The proxy attaches the credential and logs each tool call.";+const HTTP_SECTION_DESCRIPTION =+ "Web APIs your agent calls directly. The proxy attaches the credential to requests for their hosts.";++// Each count includes the type's Custom card, so it matches the cards the filter shows.+const TYPE_FILTERS: { value: TypeFilter; label: string; count: number }[] = [+ {+ value: TypeFilter.All,+ label: "All Types",+ count: AGENT_VAULT_TEMPLATES.length + AGENT_VAULT_MCP_TEMPLATES.length + 2+ },+ { value: TypeFilter.Http, label: "HTTP APIs", count: AGENT_VAULT_TEMPLATES.length + 1 },+ { value: TypeFilter.Mcp, label: "MCP Servers", count: AGENT_VAULT_MCP_TEMPLATES.length + 1 }+];++const templateTag = (template: AgentVaultTemplate) =>+ template.serviceType === AgentVaultServiceType.Mcp ? "MCP Server" : template.category;const TemplateCard = ({template,@@ -20,15 +55,16 @@ const TemplateCard = ({const [hasImageError, setHasImageError] = useState(false);return (- <button+ <Buttontype="button"+ variant="outline"onClick={() => onSelect(template)}- className="group flex cursor-pointer flex-col gap-3 rounded-md border border-border bg-card p-4 text-left transition-colors hover:border-mineshaft-500 hover:bg-mineshaft-700/50"+ className="group h-auto w-full flex-col items-stretch gap-3 bg-card p-4 text-left whitespace-normal hover:bg-container-hover"><div className="flex items-start justify-between gap-2">- <div className="flex size-9 items-center justify-center rounded-md bg-mineshaft-700">+ <div className="flex size-9 items-center justify-center rounded-md bg-container">{hasImageError ? (- <GlobeIcon className="size-5 text-bunker-300" />+ <GlobeIcon className="size-5 text-muted" />) : (<ProviderIconicon={template.image}@@ -38,116 +74,228 @@ const TemplateCard = ({/>)}</div>- <span className="text-[10px] font-medium tracking-wider text-muted uppercase">- {template.category}- </span>+ <Badge variant="outline">{templateTag(template)}</Badge></div><div className="flex flex-col gap-1">- <p className="text-sm font-semibold text-foreground">{template.name}</p>+ <CardTitle className="text-sm leading-snug">{template.name}</CardTitle><p className="text-xs leading-relaxed text-muted">{template.description}</p></div>- </button>+ </Button>);};-const CustomCard = ({ onSelect }: { onSelect: () => void }) => (- <button+const CustomCard = ({+ name,+ description,+ onSelect+}: {+ name: string;+ description: string;+ onSelect: () => void;+}) => (+ <Buttontype="button"+ variant="outline"onClick={onSelect}- className="group flex cursor-pointer flex-col gap-3 rounded-md border border-dashed border-mineshaft-500 bg-card p-4 text-left transition-colors hover:border-mineshaft-400 hover:bg-mineshaft-700/50"+ className="group h-auto w-full flex-col items-stretch gap-3 border-dashed bg-card p-4 text-left whitespace-normal hover:bg-container-hover"><div className="flex items-start gap-2">- <div className="flex size-9 items-center justify-center rounded-md bg-mineshaft-700">- <PlusIcon className="size-5 text-bunker-300" />+ <div className="flex size-9 items-center justify-center rounded-md bg-container">+ <PlusIcon className="size-5 text-muted" /></div></div><div className="flex flex-col gap-1">- <p className="text-sm font-semibold text-foreground">Custom</p>- <p className="text-xs leading-relaxed text-muted">Configure the hosts yourself.</p>+ <CardTitle className="text-sm leading-snug">{name}</CardTitle>+ <p className="text-xs leading-relaxed text-muted">{description}</p></div>- </button>+ </Button>);-const Grid = ({ children }: { children: React.ReactNode }) => (+const Grid = ({ children }: { children: ReactNode }) => (<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">{children}</div>);-const SectionLabel = ({ children }: { children: React.ReactNode }) => (+const SectionLabel = ({ children }: { children: ReactNode }) => (<p className="mb-3 text-[11px] font-medium tracking-wider text-muted uppercase">{children}</p>);+const SectionHeader = ({+ title,+ description,+ action+}: {+ title: string;+ description: string;+ action?: ReactNode;+}) => (+ <div className="mb-4 flex items-end justify-between gap-4">+ <div>+ <CardTitle className="text-sm leading-snug">{title}</CardTitle>+ <p className="mt-0.5 text-xs text-muted">{description}</p>+ </div>+ {action}+ </div>+);+type Props = {- onSelect: (template: AgentVaultTemplate | null) => void;+ onSelect: (template: AgentVaultTemplate | null, serviceType: AgentVaultServiceType) => void;};export const ServiceTemplateSelect = ({ onSelect }: Props) => {const [search, setSearch] = useState("");+ const [typeFilter, setTypeFilter] = useState(TypeFilter.All);++ const showsHttp = typeFilter !== TypeFilter.Mcp;+ const showsMcp = typeFilter !== TypeFilter.Http;const filtered = useMemo(() => {const term = search.trim().toLowerCase();if (!term) return null;- return AGENT_VAULT_TEMPLATES.filter((template) =>- [template.name, template.category, template.key, ...(template.aliases ?? [])].some((value) =>- value.toLowerCase().includes(term)+ const candidates: AgentVaultTemplate[] = [+ ...(showsMcp ? AGENT_VAULT_MCP_TEMPLATES : []),+ ...(showsHttp ? AGENT_VAULT_TEMPLATES : [])+ ];+ return candidates.filter((template) =>+ [template.name, templateTag(template), template.key, ...(template.aliases ?? [])].some(+ (value) => value.toLowerCase().includes(term)));- }, [search]);+ }, [search, showsHttp, showsMcp]);const popular = AGENT_VAULT_TEMPLATES.filter((template) =>POPULAR_AGENT_VAULT_TEMPLATES.includes(template.key));- return (- <div className="flex flex-col gap-6">- <InputGroup>- <InputGroupAddon>- <SearchIcon />- </InputGroupAddon>- <InputGroupInput- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search templates (e.g., OpenAI, Anthropic, Slack, GitHub...)"- />- </InputGroup>-- {filtered ? (- <Grid>- <CustomCard onSelect={() => onSelect(null)} />- {filtered.map((template) => (- <TemplateCard key={template.key} template={template} onSelect={onSelect} />- ))}- </Grid>- ) : (- <>- <div>- <SectionLabel>Popular</SectionLabel>- <Grid>- <CustomCard onSelect={() => onSelect(null)} />- {popular.map((template) => (- <TemplateCard key={template.key} template={template} onSelect={onSelect} />- ))}- </Grid>- </div>- {Object.values(AgentVaultTemplateCategory).map((category) => {- const templates = AGENT_VAULT_TEMPLATES.filter(- (template) => template.category === category- );- if (templates.length === 0) return null;+ const select = (template: AgentVaultTemplate) => onSelect(template, template.serviceType);++ const customHttpCard = (+ <CustomCard+ name="Custom"+ description="Configure the hosts yourself."+ onSelect={() => onSelect(null, AgentVaultServiceType.Http)}+ />+ );+ const customMcpCard = (+ <CustomCard+ name="Custom MCP Server"+ description="Connect any remote MCP server by its URL."+ onSelect={() => onSelect(null, AgentVaultServiceType.Mcp)}+ />+ );++ const renderBrowse = () => (+ <>+ {showsMcp && (+ <div>+ <SectionHeader title="MCP Servers" description={MCP_SECTION_DESCRIPTION} />+ <Grid>+ {customMcpCard}+ {AGENT_VAULT_MCP_TEMPLATES.map((template) => (+ <TemplateCard key={template.key} template={template} onSelect={select} />+ ))}+ </Grid>+ </div>+ )}+ {showsHttp && (+ <div>+ <SectionHeader+ title="HTTP APIs"+ description={HTTP_SECTION_DESCRIPTION}+ action={+ typeFilter === TypeFilter.All && (+ <Button variant="ghost" size="xs" onClick={() => setTypeFilter(TypeFilter.Http)}>+ View All+ </Button>+ )+ }+ />+ <SectionLabel>Popular</SectionLabel>+ <Grid>+ {customHttpCard}+ {popular.map((template) => (+ <TemplateCard key={template.key} template={template} onSelect={select} />+ ))}+ </Grid>+ </div>+ )}+ {typeFilter === TypeFilter.Http &&+ Object.values(AgentVaultTemplateCategory).map((category) => {+ const templates = AGENT_VAULT_TEMPLATES.filter(+ (template) => template.category === category+ );+ if (templates.length === 0) return null;+ return (+ <div key={category}>+ <SectionLabel>{category}</SectionLabel>+ <Grid>+ {templates.map((template) => (+ <TemplateCard key={template.key} template={template} onSelect={select} />+ ))}+ </Grid>+ </div>+ );+ })}+ </>+ );++ return (+ <div className="flex min-h-0 flex-1">+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">+ <p className="mb-3 text-[11px] font-medium tracking-wider text-muted uppercase">+ Service Types+ </p>+ <div role="group" aria-label="Service types" className="flex flex-col gap-0.5">+ {TYPE_FILTERS.map((filter) => {+ const isActive = filter.value === typeFilter;return (- <div key={category}>- <SectionLabel>{category}</SectionLabel>- <Grid>- {templates.map((template) => (- <TemplateCard key={template.key} template={template} onSelect={onSelect} />- ))}- </Grid>- </div>+ <Button+ key={filter.value}+ type="button"+ variant="ghost"+ aria-pressed={isActive}+ onClick={() => setTypeFilter(filter.value)}+ className={cn(+ "w-full justify-between text-left",+ isActive+ ? "bg-container-hover text-foreground"+ : "text-muted hover:bg-container-hover/50 hover:text-foreground"+ )}+ >+ {filter.label}+ <span className="text-xs text-muted tabular-nums">{filter.count}</span>+ </Button>);})}- </>- )}+ </div>+ </aside>++ <div className="flex min-w-0 flex-1 flex-col gap-6 overflow-y-auto p-6">+ <InputGroup>+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ aria-label="Search service templates"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search templates (e.g., OpenAI, Anthropic, Linear MCP, GitHub...)"+ />+ </InputGroup>++ {filtered ? (+ <Grid>+ {showsMcp && customMcpCard}+ {showsHttp && customHttpCard}+ {filtered.map((template) => (+ <TemplateCard key={template.key} template={template} onSelect={select} />+ ))}+ </Grid>+ ) : (+ renderBrowse()+ )}+ </div></div>);};diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsxindex ca76823da1..27e0e9501d 100644--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx@@ -28,7 +28,12 @@ import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";import { ReferenceHighlights } from "./ReferenceHighlights";import { SendsPreview } from "./SendsPreview";-import { CREDENTIAL_LABELS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";+import {+ CREDENTIAL_LABELS,+ HTTP_CREDENTIAL_TYPES,+ TServiceForm,+ UNCHANGED_SECRET+} from "./serviceSchema";import { useServiceVariables } from "./ServiceVariablesContext";import { VariableKeyChips } from "./VariableChips";import { useVariableAutocomplete, VariableSuggestions } from "./VariableSuggestions";@@ -293,7 +298,7 @@ export const CredentialFields = ({ storedType }: Props) => {<SelectValue /></SelectTrigger><SelectContent position="popper">- {Object.values(AgentVaultCredentialType).map((value) => (+ {HTTP_CREDENTIAL_TYPES.map((value) => (<SelectItem key={value} value={value}>{CREDENTIAL_LABELS[value]}</SelectItem>diff --git a/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsxnew file mode 100644index 0000000000..1abd710b26--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsx@@ -0,0 +1,178 @@+import { useId } from "react";+import { Controller, useFormContext } from "react-hook-form";+import { KeyRoundIcon, ShieldCheckIcon } from "lucide-react";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ FieldTitle,+ Input,+ RadioGroup,+ RadioGroupItem+} from "@app/components/v3";+import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";++import { SecretInput } from "./CredentialFields";+import { OAuthAuthorizeCard } from "./OAuthAuthorizeCard";+import { SendsPreview } from "./SendsPreview";+import { TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";+import { useServiceVariables } from "./ServiceVariablesContext";+import { TransformationsFields } from "./TransformationsFields";++const AUTH_METHOD_OPTIONS = [+ {+ type: AgentVaultCredentialType.OAuth,+ icon: ShieldCheckIcon,+ title: "OAuth 2.1",+ description: "Authorize once. Infisical stores the token and keeps it fresh."+ },+ {+ type: AgentVaultCredentialType.Bearer,+ icon: KeyRoundIcon,+ title: "Bearer Token",+ description: "A token you provide, sent in a header on every request to the server."+ }+] as const;++type Props = {+ accessBundleId: string;+ service?: TAgentVaultService | null;+ openItem: string;+ onOpenChange: (item: string) => void;+};++export const McpCredentialFields = ({ accessBundleId, service, openItem, onOpenChange }: Props) => {+ const { control, watch, setValue, clearErrors } = useFormContext<TServiceForm>();+ const { storedKeys } = useServiceVariables();+ const secret = watch("secret");+ const credentialType = watch("credentialType");+ const isOAuth = credentialType === AgentVaultCredentialType.OAuth;+ const authMethodLabelId = useId();+ const headerNameInputId = useId();+ const headerPrefixInputId = useId();+ const storedType = service?.credential.type;++ const selectType = (type: AgentVaultCredentialType) => {+ if (type === credentialType) return;+ setValue("credentialType", type, { shouldDirty: true });+ clearErrors(["secret", "oauthAuthorizationId", "headerName", "headerPrefix"]);+ };++ const hasStoredSecret = storedType === AgentVaultCredentialType.Bearer;++ return (+ <div className="flex flex-col gap-5">+ <Field>+ <FieldLabel id={authMethodLabelId}>Auth Method</FieldLabel>+ <FieldContent>+ <RadioGroup+ aria-labelledby={authMethodLabelId}+ value={isOAuth ? AgentVaultCredentialType.OAuth : AgentVaultCredentialType.Bearer}+ onValueChange={(value) => selectType(value as AgentVaultCredentialType)}+ className="gap-3 md:grid-cols-2"+ >+ {AUTH_METHOD_OPTIONS.map(({ type, icon: Icon, title, description }) => {+ const id = `${authMethodLabelId}-${type}`;+ return (+ <FieldLabel key={type} htmlFor={id} variant="av">+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>+ <Icon />+ {title}+ </FieldTitle>+ <FieldDescription>{description}</FieldDescription>+ </FieldContent>+ <RadioGroupItem id={id} value={type} />+ </Field>+ </FieldLabel>+ );+ })}+ </RadioGroup>+ </FieldContent>+ </Field>++ {isOAuth ? (+ <OAuthAuthorizeCard accessBundleId={accessBundleId} service={service} />+ ) : (+ <Controller+ control={control}+ name="secret"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Token</FieldLabel>+ <FieldContent>+ <SecretInput+ field={field}+ label="Token"+ ariaLabel="Token"+ placeholder="Enter the token, or type {{"+ isError={Boolean(fieldState.error)}+ isUntouched={secret === UNCHANGED_SECRET}+ hasStoredSecret={hasStoredSecret}+ canBeCleared={false}+ storedKeys={hasStoredSecret ? storedKeys.secret : undefined}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ )}++ <SendsPreview />++ <TransformationsFields+ openItem={openItem}+ onOpenChange={onOpenChange}+ label="Advanced"+ hasSubstitutions={false}+ >+ {!isOAuth && (+ <div className="flex items-start gap-3">+ <Controller+ control={control}+ name="headerName"+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldLabel htmlFor={headerNameInputId}>Header Name</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ id={headerNameInputId}+ placeholder="Authorization"+ isError={Boolean(fieldState.error)}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="headerPrefix"+ render={({ field, fieldState }) => (+ <Field className="w-40">+ <FieldLabel htmlFor={headerPrefixInputId}>Prefix</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ id={headerPrefixInputId}+ placeholder="Bearer"+ isError={Boolean(fieldState.error)}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ </div>+ )}+ </TransformationsFields>+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsx b/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsxnew file mode 100644index 0000000000..0844669eaa--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsx@@ -0,0 +1,105 @@+import { useId } from "react";+import { Controller, useFormContext } from "react-hook-form";++import {+ Button,+ ButtonGroup,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input+} from "@app/components/v3";+import { AgentVaultMcpTransport } from "@app/hooks/api/agentVault";++import { TRANSPORT_LABELS, TServiceForm } from "./serviceSchema";++const TRANSPORTS = Object.values(AgentVaultMcpTransport);++export const McpDetailsFields = () => {+ const { control } = useFormContext<TServiceForm>();+ const nameInputId = useId();+ const serverUrlInputId = useId();++ return (+ <div className="flex flex-col gap-5">+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel htmlFor={nameInputId}>Name</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ id={nameInputId}+ placeholder="linear-mcp"+ isError={Boolean(fieldState.error)}+ />+ <FieldDescription>Use lowercase letters, numbers, and hyphens.</FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="transport"+ render={({ field }) => (+ <Field>+ <FieldLabel>Transport</FieldLabel>+ <FieldContent>+ <ButtonGroup aria-label="Transport">+ {TRANSPORTS.map((transport) => {+ const isSelected = field.value === transport;+ return (+ <Button+ key={transport}+ type="button"+ size="sm"+ variant={isSelected ? "av" : "outline"}+ aria-pressed={isSelected}+ onClick={() => field.onChange(transport)}+ >+ {TRANSPORT_LABELS[transport]}+ </Button>+ );+ })}+ </ButtonGroup>+ <FieldDescription>+ Most servers use Streamable HTTP. Pick SSE only for a server on the older HTTP+SSE+ transport.+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="serverUrl"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel htmlFor={serverUrlInputId}>Server URL</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ id={serverUrlInputId}+ placeholder="https://mcp.example.com/mcp"+ autoComplete="off"+ spellCheck={false}+ isError={Boolean(fieldState.error)}+ />+ <FieldDescription>+ The URL your agent connects to. The credential is only sent to this host.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsxnew file mode 100644index 0000000000..edb87b5acf--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx@@ -0,0 +1,335 @@+import { useId } from "react";+import { useFormContext, useWatch } from "react-hook-form";+import { format } from "date-fns";+import { CheckIcon, CircleAlertIcon, ShieldCheckIcon } from "lucide-react";++import {+ Alert,+ AlertDescription,+ Badge,+ Button,+ CopyButton,+ Detail,+ DetailLabel,+ DetailValue,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ Spinner+} from "@app/components/v3";+import { AgentVaultOAuthStatus } from "@app/hooks/api/agentVault";+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";++import {+ newOAuthAuthorizationId,+ OAUTH_STATUS_LABELS,+ storedOAuthCredential,+ TServiceForm+} from "./serviceSchema";+import { useOAuthAuthorize } from "./useOAuthAuthorize";++const hostOf = (serverUrl: string) => {+ try {+ return new URL(serverUrl).host;+ } catch {+ return "the server";+ }+};++const ScopeList = ({ scopes }: { scopes: string[] }) =>+ scopes.length ? (+ <div className="flex flex-wrap gap-1.5">+ {scopes.map((scope) => (+ <Badge key={scope} variant="outline" className="font-mono">+ {scope}+ </Badge>+ ))}+ </div>+ ) : (+ <span className="text-muted">None requested</span>+ );++const OAUTH_STATUS_VARIANTS = {+ [AgentVaultOAuthStatus.Connected]: "success",+ [AgentVaultOAuthStatus.NeedsReauthorization]: "danger",+ [AgentVaultOAuthStatus.NeedsAdditionalScopes]: "warning"+} as const;++export const OAuthStatusBadge = ({ status }: { status: AgentVaultOAuthStatus }) => (+ <Badge variant={OAUTH_STATUS_VARIANTS[status]}>+ {status === AgentVaultOAuthStatus.Connected ? <CheckIcon /> : <CircleAlertIcon />}+ {OAUTH_STATUS_LABELS[status]}+ </Badge>+);++type Props = {+ accessBundleId: string;+ service?: TAgentVaultService | null;+};++export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {+ const {+ control,+ register,+ setValue,+ formState: { errors }+ } = useFormContext<TServiceForm>();+ const [serverUrl, authorizationId, authorizedUrl, scopes, clientId = "", clientSecret = ""] =+ useWatch({+ control,+ name: [+ "serverUrl",+ "oauthAuthorizationId",+ "oauthAuthorizedUrl",+ "oauthScopes",+ "oauthClientId",+ "oauthClientSecret"+ ]+ });+ const clientIdInputId = useId();+ const clientSecretInputId = useId();++ const trimmedUrl = serverUrl.trim();+ const host = hostOf(trimmedUrl);+ const isNewlyAuthorized = Boolean(+ newOAuthAuthorizationId({+ serverUrl,+ oauthAuthorizationId: authorizationId,+ oauthAuthorizedUrl: authorizedUrl+ })+ );+ const stored = storedOAuthCredential(service, serverUrl);++ const { state, isClientRequired, redirectUri, registrationError, authorize, cancel } =+ useOAuthAuthorize({+ onAuthorized: (authorization) => {+ setValue("oauthAuthorizedUrl", trimmedUrl, { shouldDirty: true });+ setValue("oauthScopes", authorization.scopes, { shouldDirty: true });+ setValue("oauthAuthorizationId", authorization.id, {+ shouldDirty: true,+ shouldValidate: true+ });+ }+ });++ const isWaiting = state.status === "starting" || state.status === "pending";++ const handleAuthorize = () =>+ authorize({+ accessBundleId,+ serverUrl: trimmedUrl,+ ...(stored && service ? { serviceId: service.id } : {}),+ ...(isClientRequired+ ? { clientId: clientId.trim(), clientSecret: clientSecret || undefined }+ : {})+ });++ const hasAuthorization = isNewlyAuthorized || Boolean(stored);+ const authorizeLabel = hasAuthorization ? "Reauthorize" : "Authorize";++ const renderStatus = () => {+ if (isNewlyAuthorized) {+ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-center gap-2">+ <Badge variant="success">+ <CheckIcon />+ Authorized+ </Badge>+ <span className="text-sm text-muted">+ {stored ? "Saving replaces the stored tokens." : `Connected to ${host}.`}+ </span>+ </div>+ <Detail>+ <DetailLabel>Granted Scopes</DetailLabel>+ <DetailValue>+ <ScopeList scopes={scopes} />+ </DetailValue>+ </Detail>+ </div>+ );+ }++ if (stored) {+ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-center gap-2">+ <OAuthStatusBadge status={stored.status} />+ {stored.status === AgentVaultOAuthStatus.NeedsReauthorization && (+ <span className="text-sm text-muted">+ The server no longer accepts the stored tokens. Reauthorize to restore access.+ </span>+ )}+ {stored.status === AgentVaultOAuthStatus.NeedsAdditionalScopes && (+ <span className="text-sm text-muted">+ A tool call needed scopes this authorization lacks. Reauthorize to grant them.+ </span>+ )}+ </div>+ <div className="flex flex-wrap gap-x-8 gap-y-4">+ <Detail>+ <DetailLabel>Granted Scopes</DetailLabel>+ <DetailValue>+ <ScopeList scopes={stored.grantedScopes} />+ </DetailValue>+ </Detail>+ {stored.status === AgentVaultOAuthStatus.NeedsAdditionalScopes &&+ stored.requiredScopes.length > 0 && (+ <Detail>+ <DetailLabel>Missing Scopes</DetailLabel>+ <DetailValue>+ <ScopeList scopes={stored.requiredScopes} />+ </DetailValue>+ </Detail>+ )}+ <Detail>+ <DetailLabel>Authorized By</DetailLabel>+ <DetailValue>+ {stored.authorizedBy?.username ?? "Unknown"}+ {stored.authorizedAt && (+ <>+ {" on "}+ <span className="font-mono">+ {format(new Date(stored.authorizedAt), "MMM d, yyyy h:mm a")}+ </span>+ </>+ )}+ </DetailValue>+ </Detail>+ </div>+ {stored.lastError && (+ <Alert variant="warning">+ <CircleAlertIcon />+ <AlertDescription>Last refresh failed: {stored.lastError}</AlertDescription>+ </Alert>+ )}+ </div>+ );+ }++ return (+ <p className="text-sm text-muted">+ Sign in to {host} in a pop-up window. Infisical stores the tokens it returns, and the agent+ never sees them.+ </p>+ );+ };++ return (+ <Field>+ <FieldLabel>Authorization</FieldLabel>+ <FieldContent>+ <div className="flex flex-col gap-4 rounded-md border border-border bg-container p-4">+ <div className="flex items-start gap-3">+ <ShieldCheckIcon className="mt-0.5 size-4 shrink-0 text-muted" />+ <div className="min-w-0 flex-1">{renderStatus()}</div>+ </div>++ {isClientRequired && redirectUri && !isNewlyAuthorized && (+ <div className="flex flex-col gap-4 border-t border-border pt-4">+ {registrationError ? (+ <>+ <Alert variant="warning">+ <CircleAlertIcon />+ <AlertDescription>{registrationError}</AlertDescription>+ </Alert>+ <p className="text-sm text-muted">+ Create an OAuth app with the provider, set its redirect URI to the one below,+ then enter its client ID and secret.+ </p>+ </>+ ) : (+ <p className="text-sm text-muted">+ {host} doesn't let Infisical register itself as a client. Create an OAuth app+ with the provider, set its redirect URI to the one below, then enter its client ID+ and secret.+ </p>+ )}+ <Field>+ <FieldLabel>Redirect URI</FieldLabel>+ <FieldContent>+ <div className="flex items-center gap-2">+ <code className="min-w-0 flex-1 truncate rounded-md border border-border bg-card px-2 py-1.5 font-mono text-xs">+ {redirectUri}+ </code>+ <CopyButton value={redirectUri} ariaLabel="Copy redirect URI" />+ </div>+ </FieldContent>+ </Field>+ <div className="flex flex-col gap-3 md:flex-row">+ <Field className="flex-1">+ <FieldLabel htmlFor={clientIdInputId}>Client ID</FieldLabel>+ <FieldContent>+ <Input+ {...register("oauthClientId")}+ id={clientIdInputId}+ maxLength={512}+ autoComplete="off"+ spellCheck={false}+ isError={Boolean(errors.oauthClientId)}+ />+ <FieldError>{errors.oauthClientId?.message}</FieldError>+ </FieldContent>+ </Field>+ <Field className="flex-1">+ <FieldLabel htmlFor={clientSecretInputId}>Client Secret</FieldLabel>+ <FieldContent>+ <Input+ type="password"+ {...register("oauthClientSecret")}+ id={clientSecretInputId}+ maxLength={1024}+ autoComplete="new-password"+ isError={Boolean(errors.oauthClientSecret)}+ />+ <FieldDescription>Leave empty for a public client.</FieldDescription>+ <FieldError>{errors.oauthClientSecret?.message}</FieldError>+ </FieldContent>+ </Field>+ </div>+ </div>+ )}++ {state.status === "failed" && (+ <Alert variant="danger">+ <CircleAlertIcon />+ <AlertDescription>{state.message}</AlertDescription>+ </Alert>+ )}++ {isWaiting ? (+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-2 text-sm text-muted">+ <Spinner size="xs" className="m-0 shrink-0 fill-product-av" />+ <span>+ {state.status === "pending" && state.popupClosed+ ? "Waiting for the authorization. If you closed the window before finishing, select Cancel and try again."+ : `Waiting for you to finish signing in to ${host} in the pop-up window.`}+ </span>+ </div>+ <Button type="button" variant="ghost" size="sm" onClick={cancel}>+ Cancel+ </Button>+ </div>+ ) : (+ <div>+ <Button+ type="button"+ variant={hasAuthorization ? "outline" : "av"}+ size="sm"+ onClick={handleAuthorize}+ isDisabled={!trimmedUrl || (isClientRequired && !clientId.trim())}+ >+ {state.status === "failed" ? "Try Again" : authorizeLabel}+ </Button>+ </div>+ )}+ </div>+ <FieldError>{errors.oauthAuthorizationId?.message}</FieldError>+ </FieldContent>+ </Field>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsxindex e889b61ef6..cdd28466fe 100644--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx@@ -8,12 +8,15 @@ import {DetailLabel,DetailValue} from "@app/components/v3";-import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";+import { AgentVaultCredentialType, AgentVaultServiceType } from "@app/hooks/api/agentVault";+import { TAgentVaultService } from "@app/hooks/api/agentVault/types";import {CREDENTIAL_LABELS,isAllMethods,+ oauthStatusLabel,SURFACE_LABELS,+ TRANSPORT_LABELS,TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";@@ -27,6 +30,8 @@ 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}`;};@@ -45,13 +50,16 @@ const alignColumns = (rows: string[][]) => {type Props = {isUpdate: boolean;+ service?: TAgentVaultService | null;};-export const ReviewFields = ({ isUpdate }: Props) => {+export const ReviewFields = ({ isUpdate, service }: Props) => {const { watch } = useFormContext<TServiceForm>();const form = watch();+ const isMcp = form.serviceType === AgentVaultServiceType.Mcp;const isBasic = form.credentialType === AgentVaultCredentialType.Basic;+ const isOAuth = form.credentialType === AgentVaultCredentialType.OAuth;const secretLabel = isBasic ? "Password" : "Token";const sends = credentialPreview(form);@@ -80,37 +88,68 @@ export const ReviewFields = ({ isUpdate }: Props) => {<div className="mb-4 flex flex-col gap-y-8"><DetailGroup><DetailGroupHeader className="border-b border-border pb-2">Details</DetailGroupHeader>- <div className="flex flex-wrap gap-x-8 gap-y-4">- <Detail>- <DetailLabel>Name</DetailLabel>- <DetailValue>{form.name}</DetailValue>- </Detail>- <Detail>- <DetailLabel>Hosts</DetailLabel>- <DetailValue>{form.hosts.join(", ")}</DetailValue>- </Detail>- <Detail>- <DetailLabel>Methods</DetailLabel>- <DetailValue>- {isAllMethods(form.methods) ? "All" : form.methods.join(", ")}- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Paths</DetailLabel>- <DetailValue>- {form.pathPrefixes.length ? form.pathPrefixes.join(", ") : "All"}- </DetailValue>- </Detail>- </div>+ {isMcp ? (+ <div className="flex flex-wrap gap-x-8 gap-y-4">+ <Detail>+ <DetailLabel>Name</DetailLabel>+ <DetailValue className="font-mono">{form.name}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Server URL</DetailLabel>+ <DetailValue className="font-mono break-all">{form.serverUrl.trim()}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Transport</DetailLabel>+ <DetailValue>{TRANSPORT_LABELS[form.transport]}</DetailValue>+ </Detail>+ </div>+ ) : (+ <div className="flex flex-wrap gap-x-8 gap-y-4">+ <Detail>+ <DetailLabel>Name</DetailLabel>+ <DetailValue>{form.name}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Hosts</DetailLabel>+ <DetailValue>{form.hosts.join(", ")}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Methods</DetailLabel>+ <DetailValue>+ {isAllMethods(form.methods) ? "All" : form.methods.join(", ")}+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Paths</DetailLabel>+ <DetailValue>+ {form.pathPrefixes.length ? form.pathPrefixes.join(", ") : "All"}+ </DetailValue>+ </Detail>+ </div>+ )}</DetailGroup><DetailGroup><DetailGroupHeader className="border-b border-border pb-2">Credential</DetailGroupHeader><div className="flex flex-wrap gap-x-8 gap-y-4">+ {isMcp && (+ <Detail>+ <DetailLabel>Owner</DetailLabel>+ <DetailValue>Shared</DetailValue>+ </Detail>+ )}<Detail><DetailLabel>Type</DetailLabel>- <DetailValue>{CREDENTIAL_LABELS[form.credentialType]}</DetailValue>+ <DetailValue>+ {isMcp && !isOAuth ? "Bearer Token" : CREDENTIAL_LABELS[form.credentialType]}+ </DetailValue></Detail>+ {isOAuth && (+ <Detail>+ <DetailLabel>Status</DetailLabel>+ <DetailValue>{oauthStatusLabel(form, service)}</DetailValue>+ </Detail>+ )}{sends && (<Detail><DetailLabel>Sends</DetailLabel>@@ -123,7 +162,7 @@ export const ReviewFields = ({ isUpdate }: Props) => {<DetailValue>{outcome(form.username, true)}</DetailValue></Detail>)}- {form.credentialType !== AgentVaultCredentialType.Passthrough && (+ {form.credentialType !== AgentVaultCredentialType.Passthrough && !isOAuth && (<Detail><DetailLabel>{secretLabel}</DetailLabel><DetailValue>{outcome(form.secret, isBasic)}</DetailValue>diff --git a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsxindex 3eb8a66a64..b8dc75168f 100644--- a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx+++ b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx@@ -58,6 +58,17 @@ export const SendsPreview = () => {});}+ if (credentialType === AgentVaultCredentialType.OAuth) {+ lines.push({+ id: "credential",+ content: (+ <>+ Authorization: Bearer <span className="text-muted"><access token></span>+ </>+ )+ });+ }+if (credentialType === AgentVaultCredentialType.Basic) {lines.push({id: "credential",diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex cf6f15fef4..7bdd92bd6a 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -21,10 +21,17 @@ import {} from "@app/components/v3";import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";import { hostError } from "@app/helpers/agentVaultHostPattern";-import { AgentVaultTemplate, findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";+import {+ AgentVaultHttpTemplate,+ AgentVaultMcpTemplate,+ AgentVaultTemplate,+ findTemplateForHostPattern+} from "@app/helpers/agentVaultTemplates";import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";import {AgentVaultCredentialType,+ AgentVaultMcpTransport,+ AgentVaultServiceType,AgentVaultVariableReferenceField,useCreateAgentVaultService,useListAgentVaultVariables,@@ -42,23 +49,30 @@ import { ServiceTemplateSelect } from "../ServiceTemplateSelect";import { VariableFormDialog } from "../VariableFormDialog";import { CredentialFields } from "./CredentialFields";import { DetailsFields } from "./DetailsFields";+import { McpCredentialFields } from "./McpCredentialFields";+import { McpDetailsFields } from "./McpDetailsFields";import { ReviewFields } from "./ReviewFields";+import { buildCreateServiceRequest, buildUpdateServiceRequest } from "./serviceRequest";import {buildServiceSchema,displayHostPattern,HTTP_METHODS,- isAllMethods,+ isOAuthAuthorizationMissing,+ MCP_SERVICE_STEP_FIELDS,SERVICE_STEP_FIELDS,ServiceStep,TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";import { NO_STORED_KEYS, ServiceVariablesContext } from "./ServiceVariablesContext";-import { SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";+import { MCP_SERVICE_STEPS, SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";import { ADVANCED_ITEM, TransformationsFields } from "./TransformationsFields";const BLANK_SERVICE_FORM: TServiceForm = {+ serviceType: AgentVaultServiceType.Http,name: "",+ serverUrl: "",+ transport: AgentVaultMcpTransport.StreamableHttp,hosts: [],hostDraft: "",pathDraft: "",@@ -67,14 +81,41 @@ const BLANK_SERVICE_FORM: TServiceForm = {headerPrefix: "Bearer",username: "",secret: "",+ oauthAuthorizationId: "",+ oauthAuthorizedUrl: "",+ oauthScopes: [],+ oauthClientId: "",+ oauthClientSecret: "",methods: [...HTTP_METHODS],pathPrefixes: [],customHeaders: [],substitutions: []};+const BLANK_MCP_SERVICE_FORM: TServiceForm = {+ ...BLANK_SERVICE_FORM,+ serviceType: AgentVaultServiceType.Mcp,+ credentialType: AgentVaultCredentialType.OAuth+};++const mcpFormFromTemplate = (picked: AgentVaultMcpTemplate | null): TServiceForm => {+ if (!picked) return BLANK_MCP_SERVICE_FORM;+ const cred = picked.credential;+ return {+ ...BLANK_MCP_SERVICE_FORM,+ name: picked.key,+ serverUrl: picked.serverUrl,+ transport: picked.transport,+ credentialType: cred.type,+ ...(cred.type === AgentVaultCredentialType.Bearer && {+ headerName: cred.headerName ?? "Authorization",+ headerPrefix: cred.headerPrefix ?? "Bearer"+ })+ };+};+// A template placeholder like <your-tenant>.atlassian.net is not a host, so it goes into the draft.-const formFromTemplate = (picked: AgentVaultTemplate | null, hosts: string[]): TServiceForm => {+const formFromTemplate = (picked: AgentVaultHttpTemplate | null, hosts: string[]): TServiceForm => {const hostFields = {hosts: hosts.filter((host) => !hostError(host, [])),hostDraft: hosts.find((host) => Boolean(hostError(host, []))) ?? ""@@ -102,6 +143,8 @@ type Props = {accessBundleId: string;service?: TAgentVaultService | null;prefillHost?: string;+ // Only for an existing service, whose steps start at Details.+ initialStep?: ServiceStep;onSaved?: () => void;};@@ -150,6 +193,7 @@ export const ServiceSheet = ({accessBundleId,service,prefillHost,+ initialStep,onSaved}: Props) => {const isUpdate = Boolean(service);@@ -194,9 +238,14 @@ export const ServiceSheet = ({reset,setError,trigger,+ watch,+ setValue,formState: { errors, isDirty, isSubmitting }} = formMethods;+ const isMcp = watch("serviceType") === AgentVaultServiceType.Mcp;+ const stepFields = isMcp ? MCP_SERVICE_STEP_FIELDS : SERVICE_STEP_FIELDS;+const discardActionRef = useRef<VoidFunction>(() => onOpenChange(false));const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =useDiscardChangesGuard({ isDirty, onDiscard: () => discardActionRef.current() });@@ -209,13 +258,10 @@ export const ServiceSheet = ({// A prefilled host has already been matched against the templates, and anything picked on the// template step would replace that host.const hasTemplateStep = !isUpdate && !prefillHost;- const steps = useMemo(- () =>- hasTemplateStep- ? SERVICE_STEPS- : SERVICE_STEPS.filter((meta) => meta.step !== ServiceStep.Template),- [hasTemplateStep]- );+ const steps = useMemo(() => {+ const all = isMcp ? MCP_SERVICE_STEPS : SERVICE_STEPS;+ return hasTemplateStep ? all : all.filter((meta) => meta.step !== ServiceStep.Template);+ }, [hasTemplateStep, isMcp]);const stepKeys = useMemo(() => steps.map((meta) => meta.step), [steps]);const panelRef = useRef<HTMLDivElement>(null);@@ -227,7 +273,7 @@ export const ServiceSheet = ({const { step, isLastStep, goBack, goNext, onFormInvalid, setStep } = useWizardSteps<ServiceStep>({stepKeys,- stepFields: SERVICE_STEP_FIELDS,+ stepFields,invalidMessage: "Fix the errors before saving.",validateStep: async (fields) => {const isValid = await trigger(fields as (keyof TServiceForm)[]);@@ -236,7 +282,11 @@ export const ServiceSheet = ({}});- const hasAdvancedError = Boolean(errors.customHeaders || errors.substitutions);+ const hasAdvancedError = Boolean(+ errors.customHeaders ||+ errors.substitutions ||+ (isMcp && (errors.headerName || errors.headerPrefix))+ );useEffect(() => {if (hasAdvancedError) setOpenItem(ADVANCED_ITEM);@@ -257,10 +307,39 @@ export const ServiceSheet = ({useEffect(() => {if (!isOpen) return;- setStep(0);+ setStep(+ service && initialStep+ ? Math.max(+ SERVICE_STEPS.filter((meta) => meta.step !== ServiceStep.Template).findIndex(+ (meta) => meta.step === initialStep+ ),+ 0+ )+ : 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.config.serverUrl,+ transport: service.config.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;reset({...BLANK_SERVICE_FORM,@@ -311,18 +390,27 @@ export const ServiceSheet = ({} else {reset(BLANK_SERVICE_FORM);}- }, [isOpen, service, isUpdate, prefillHost, reset, setStep]);+ }, [isOpen, service, isUpdate, prefillHost, initialStep, reset, setStep]);- const handleTemplatePicked = (picked: AgentVaultTemplate | null) => {+ const handleTemplatePicked = (+ picked: AgentVaultTemplate | null,+ serviceType: AgentVaultServiceType+ ) => {setTemplate(picked);- reset(- picked- ? formFromTemplate(- picked,- picked.hostPattern.split(",").map((host) => host.trim())- )- : BLANK_SERVICE_FORM- );+ if (serviceType === AgentVaultServiceType.Mcp) {+ setOpenItem("");+ reset(mcpFormFromTemplate(picked?.serviceType === AgentVaultServiceType.Mcp ? picked : null));+ } else {+ setOpenItem(ADVANCED_ITEM);+ reset(+ picked?.serviceType === AgentVaultServiceType.Http+ ? formFromTemplate(+ picked,+ picked.hostPattern.split(",").map((host) => host.trim())+ )+ : BLANK_SERVICE_FORM+ );+ }setStep(1);};@@ -333,87 +421,14 @@ export const ServiceSheet = ({setStep(0);});- const buildCredential = (data: TServiceForm) => {- if (data.credentialType === AgentVaultCredentialType.Passthrough) {- return { type: AgentVaultCredentialType.Passthrough as const };- }- if (data.credentialType === AgentVaultCredentialType.Basic) {- return {- type: AgentVaultCredentialType.Basic as const,- username: data.username ?? "",- password: data.secret ?? ""- };- }- return {- type: AgentVaultCredentialType.Bearer as const,- headerName: data.headerName || undefined,- headerPrefix: data.headerPrefix ?? "",- value: data.secret ?? ""- };- };-- const buildCredentialPatch = (data: TServiceForm) => {- if (data.credentialType === AgentVaultCredentialType.Passthrough) {- return { type: AgentVaultCredentialType.Passthrough as const };- }- const untouched = data.secret === UNCHANGED_SECRET;-- if (data.credentialType === AgentVaultCredentialType.Basic) {- return {- type: AgentVaultCredentialType.Basic as const,- username: data.username === UNCHANGED_SECRET ? undefined : (data.username ?? ""),- password: untouched ? undefined : (data.secret ?? "")- };- }- return {- type: AgentVaultCredentialType.Bearer as const,- headerName: data.headerName || "Authorization",- headerPrefix: data.headerPrefix ?? "",- value: untouched || !data.secret ? undefined : data.secret- };- };-- const buildPolicy = (data: TServiceForm) => ({- allowedMethods: isAllMethods(data.methods) ? null : data.methods,- allowedPathPrefixes: data.pathPrefixes.length ? data.pathPrefixes : null- });-- const buildTransformations = (data: TServiceForm) => ({- customHeaders: data.customHeaders.map((header) => ({- ...(header.id ? { id: header.id } : {}),- name: header.name,- prefix: header.prefix,- ...(header.value === UNCHANGED_SECRET ? {} : { value: header.value })- })),- substitutions: data.substitutions.map((substitution) => ({- ...(substitution.id ? { id: substitution.id } : {}),- placeholder: substitution.placeholder,- surfaces: substitution.surfaces,- ...(substitution.value === UNCHANGED_SECRET ? {} : { value: substitution.value })- }))- });-const onSubmit = async (data: TServiceForm) => {try {if (service) {- await updateService.mutateAsync({- accessBundleId,- serviceId: service.id,- name: data.name,- hostPattern: data.hosts.join(","),- ...buildPolicy(data),- credential: buildCredentialPatch(data),- ...buildTransformations(data)- });+ await updateService.mutateAsync(+ buildUpdateServiceRequest(accessBundleId, service.id, data)+ );} else {- await createService.mutateAsync({- accessBundleId,- name: data.name,- hostPattern: data.hosts.join(","),- ...buildPolicy(data),- credential: buildCredential(data),- ...buildTransformations(data)- });+ await createService.mutateAsync(buildCreateServiceRequest(accessBundleId, data));}createNotification({@@ -432,11 +447,26 @@ export const ServiceSheet = ({serverResponse?.error === ApiErrorTypes.BadRequestError &&serverResponse.message.includes("already covers")) {- setError("hosts", { type: "server", message: serverResponse.message });+ setError(isMcp ? "serverUrl" : "hosts", {+ type: "server",+ message: serverResponse.message+ });setStep(stepKeys.indexOf(ServiceStep.Details));return;}+ // An authorization is consumed by the first save that uses it, and is tied to one server URL.+ if (+ serverResponse?.error === ApiErrorTypes.BadRequestError &&+ data.credentialType === AgentVaultCredentialType.OAuth &&+ /authoriz/i.test(serverResponse.message)+ ) {+ setValue("oauthAuthorizationId", "");+ setError("oauthAuthorizationId", { type: "server", message: serverResponse.message });+ setStep(stepKeys.indexOf(ServiceStep.Credential));+ return;+ }+// Thrown after the stored halves are merged in, so the form cannot have known: it is told which// halves exist only as "unchanged", never whether one of them is empty.if (@@ -452,6 +482,8 @@ export const ServiceSheet = ({const STEP_OF_FIELD: Record<string, ServiceStep> = {name: ServiceStep.Details,hostPattern: ServiceStep.Details,+ serverUrl: ServiceStep.Details,+ transport: ServiceStep.Details,allowedMethods: ServiceStep.Details,allowedPathPrefixes: ServiceStep.Details,credential: ServiceStep.Credential,@@ -460,10 +492,13 @@ export const ServiceSheet = ({};const FORM_FIELD_OF: Record<string, keyof TServiceForm> = {- hostPattern: "hosts",+ hostPattern: isMcp ? "serverUrl" : "hosts",allowedMethods: "methods",allowedPathPrefixes: "pathPrefixes",- credential: "secret"+ credential:+ data.credentialType === AgentVaultCredentialType.OAuth+ ? "oauthAuthorizationId"+ : "secret"};let earliestStep: number | null = null;@@ -492,9 +527,7 @@ export const ServiceSheet = ({return;}- // The mutation suppresses the global toast for bad requests so the conflict above shows once.- // Every other bad request has nothing rendering it, so hand those back.- onRequestError(error);+ if (serverResponse?.error === ApiErrorTypes.BadRequestError) onRequestError(error);}};@@ -507,7 +540,7 @@ export const ServiceSheet = ({}for (let i = step; i < target; i += 1) {// eslint-disable-next-line no-await-in-loop- if (!(await trigger(SERVICE_STEP_FIELDS[stepKeys[i]] as (keyof TServiceForm)[]))) {+ if (!(await trigger(stepFields[stepKeys[i]] as (keyof TServiceForm)[]))) {return;}}@@ -522,13 +555,33 @@ export const ServiceSheet = ({await goNext();};+ const customName = isMcp ? "Custom MCP Server" : "Custom";+const stepDescription = (meta: (typeof SERVICE_STEPS)[number]) => {- if (meta.step === ServiceStep.Template) return template?.name ?? "Custom";+ if (meta.step === ServiceStep.Template) return template?.name ?? customName;if (meta.step === ServiceStep.Review && isUpdate) return "Confirm and save";return meta.shortDescription;};const current = steps[step];+ const [credentialType, serverUrl, oauthAuthorizationId, oauthAuthorizedUrl] = watch([+ "credentialType",+ "serverUrl",+ "oauthAuthorizationId",+ "oauthAuthorizedUrl"+ ]);+ const isAwaitingAuthorization =+ current.step === ServiceStep.Credential &&+ isOAuthAuthorizationMissing(+ {+ serviceType: isMcp ? AgentVaultServiceType.Mcp : AgentVaultServiceType.Http,+ credentialType,+ serverUrl,+ oauthAuthorizationId,+ oauthAuthorizedUrl+ },+ service+ );const isTemplateStep = current.step === ServiceStep.Template;const saveLabel = isUpdate ? "Save" : "Add Service";@@ -547,7 +600,7 @@ export const ServiceSheet = ({<SheetHeader>{isTemplateStep ? (<>- <SheetTitle>Choose a template</SheetTitle>+ <SheetTitle>Choose a Template</SheetTitle><SheetDescription>Start from a template, or configure the service yourself.</SheetDescription>@@ -558,7 +611,7 @@ export const ServiceSheet = ({{template && (<ProviderIcon icon={template.image} alt="" className="size-6 object-contain" />)}- {template?.name ?? (isUpdate ? service?.name : "Custom")}+ {template?.name ?? (isUpdate ? service?.name : customName)}<DocumentationLinkBadge href={SERVICE_DOCS_URL} /></SheetTitle><SheetDescription>Set up the service and its credentials.</SheetDescription>@@ -568,7 +621,7 @@ export const ServiceSheet = ({<FormProvider {...formMethods}>{isTemplateStep ? (- <div className="min-h-0 flex-1 overflow-y-auto p-6">+ <div className="flex min-h-0 flex-1"><ServiceTemplateSelect onSelect={handleTemplatePicked} /></div>) : (@@ -578,7 +631,7 @@ export const ServiceSheet = ({<div className="flex min-h-0 flex-1 overflow-hidden"><aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6"><p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">- Setup steps+ Setup Steps</p><StepperactiveStep={step}@@ -608,8 +661,19 @@ export const ServiceSheet = ({<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 &&+ (isMcp ? <McpDetailsFields /> : <DetailsFields />)}+ {current.step === ServiceStep.Credential && isMcp && (+ <ServiceVariablesContext.Provider value={serviceVariables}>+ <McpCredentialFields+ accessBundleId={accessBundleId}+ service={service}+ openItem={openItem}+ onOpenChange={setOpenItem}+ />+ </ServiceVariablesContext.Provider>+ )}+ {current.step === ServiceStep.Credential && !isMcp && (<ServiceVariablesContext.Provider value={serviceVariables}><div className="flex flex-col gap-5"><CredentialFields storedType={service?.credential.type} />@@ -617,7 +681,9 @@ export const ServiceSheet = ({</div></ServiceVariablesContext.Provider>)}- {current.step === ServiceStep.Review && <ReviewFields isUpdate={isUpdate} />}+ {current.step === ServiceStep.Review && (+ <ReviewFields isUpdate={isUpdate} service={service} />+ )}</div><aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">@@ -627,7 +693,7 @@ export const ServiceSheet = ({</p><DocumentationLinkBadge href={SERVICE_DOCS_URL} /></div>- <p className="text-sm font-semibold text-foreground">What this step does</p>+ <h3 className="text-sm font-normal text-foreground">What This Step Does</h3><p className="text-sm leading-relaxed text-muted">{current.rightDescription}</p>{current.rightTip && (<p className="text-sm leading-relaxed text-muted">{current.rightTip}</p>@@ -656,6 +722,7 @@ export const ServiceSheet = ({type="button"variant="av"onClick={handleNext}+ isDisabled={isAwaitingAuthorization}isPending={isLastStep && isSubmitting}>{isLastStep ? saveLabel : "Continue"}diff --git a/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx b/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsxindex 715fdb7cf3..cd9cd5f33d 100644--- a/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx@@ -1,3 +1,4 @@+import { ReactNode } from "react";import { Controller, useFieldArray, useFormContext } from "react-hook-form";import { InfoIcon, PlusIcon, TrashIcon } from "lucide-react";@@ -70,10 +71,16 @@ const RemoveRowButton = ({export const TransformationsFields = ({openItem,- onOpenChange+ onOpenChange,+ label = "Advanced Options",+ hasSubstitutions = true,+ children}: {openItem: string;onOpenChange: (item: string) => void;+ label?: string;+ hasSubstitutions?: boolean;+ children?: ReactNode;}) => {const { control, getValues } = useFormContext<TServiceForm>();const { storedKeys } = useServiceVariables();@@ -89,9 +96,10 @@ export const TransformationsFields = ({onValueChange={onOpenChange}><AccordionItem value={ADVANCED_ITEM}>- <AccordionTrigger>Advanced Options</AccordionTrigger>+ <AccordionTrigger>{label}</AccordionTrigger><AccordionContent><div className="flex flex-col gap-5">+ {children}<div className="flex flex-col gap-3"><div><p className="text-sm font-medium">Custom headers</p>@@ -195,154 +203,158 @@ export const TransformationsFields = ({/></div>- <div className="flex flex-col gap-3">- <div>- <p className="text-sm font-medium">Substitutions</p>- <p className="mt-1 text-xs text-muted">- Your agent sends a placeholder. The proxy swaps it for the real value before- forwarding.- </p>- </div>+ {hasSubstitutions && (<div className="flex flex-col gap-3">- {substitutions.fields.map((row, index) => (- <div- key={row.id}- className="flex flex-col gap-3 rounded-md border border-border bg-container/50 p-4"- >- <div className="flex items-start gap-2">- <Controller- control={control}- name={`substitutions.${index}.placeholder`}- render={({ field, fieldState }) => (- <Field className="flex-1">- <FieldContent>- <FieldLabel className="text-xs">Replace</FieldLabel>- <InputGroup>- <InputGroupInput- {...field}- aria-label="Placeholder"- placeholder="__API_TOKEN__"+ <div>+ <p className="text-sm font-medium">Substitutions</p>+ <p className="mt-1 text-xs text-muted">+ Your agent sends a placeholder. The proxy swaps it for the real value before+ forwarding.+ </p>+ </div>+ <div className="flex flex-col gap-3">+ {substitutions.fields.map((row, index) => (+ <div+ key={row.id}+ className="flex flex-col gap-3 rounded-md border border-border bg-container/50 p-4"+ >+ <div className="flex items-start gap-2">+ <Controller+ control={control}+ name={`substitutions.${index}.placeholder`}+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldContent>+ <FieldLabel className="text-xs">Replace</FieldLabel>+ <InputGroup>+ <InputGroupInput+ {...field}+ aria-label="Placeholder"+ placeholder="__API_TOKEN__"+ isError={Boolean(fieldState.error)}+ />+ {Boolean(field.value) && (+ <InputGroupAddon align="inline-end">+ <CopyButton+ value={field.value}+ ariaLabel="Copy placeholder"+ size="xs"+ />+ </InputGroupAddon>+ )}+ </InputGroup>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name={`substitutions.${index}.value`}+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldContent>+ <FieldLabel className="text-xs">With</FieldLabel>+ <SecretInput+ field={field}+ label="Substitution value"+ ariaLabel="Substitution value"+ placeholder="Enter the real value, or type {{"isError={Boolean(fieldState.error)}+ isUntouched={field.value === UNCHANGED_SECRET}+ hasStoredSecret={Boolean(getValues(`substitutions.${index}.id`))}+ canBeCleared={false}+ storedKeys={+ storedKeys.substitutions[+ getValues(`substitutions.${index}.id`) ?? ""+ ]+ }/>- {Boolean(field.value) && (- <InputGroupAddon align="inline-end">- <CopyButton- value={field.value}- ariaLabel="Copy placeholder"- size="xs"- />- </InputGroupAddon>- )}- </InputGroup>- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <RemoveRowButton+ ariaLabel={`Remove substitution ${index + 1}`}+ hasLabelRow+ onClick={() => substitutions.remove(index)}+ />+ </div>+<Controllercontrol={control}- name={`substitutions.${index}.value`}+ name={`substitutions.${index}.surfaces`}render={({ field, fieldState }) => (- <Field className="flex-1">+ <Field><FieldContent>- <FieldLabel className="text-xs">With</FieldLabel>- <SecretInput- field={field}- label="Substitution value"- ariaLabel="Substitution value"- placeholder="Enter the real value, or type {{"- isError={Boolean(fieldState.error)}- isUntouched={field.value === UNCHANGED_SECRET}- hasStoredSecret={Boolean(getValues(`substitutions.${index}.id`))}- canBeCleared={false}- storedKeys={- storedKeys.substitutions[- getValues(`substitutions.${index}.id`) ?? ""- ]- }- />+ <FieldLabel className="text-xs">+ Replace In+ <HoverCard openDelay={200} closeDelay={150}>+ <HoverCardTrigger asChild>+ <InfoIcon />+ </HoverCardTrigger>+ <HoverCardContent className="w-96" side="top" align="start">+ <SubstitutionExample />+ </HoverCardContent>+ </HoverCard>+ </FieldLabel>+ <div className="mt-2 flex flex-wrap gap-x-5 gap-y-2">+ {SURFACES.map((surface) => (+ <Field key={surface} orientation="horizontal" className="w-auto">+ <Checkbox+ id={`surface-${index}-${surface}`}+ isChecked={field.value.includes(surface)}+ onCheckedChange={(checked) =>+ field.onChange(+ checked === true+ ? [...field.value, surface]+ : field.value.filter((value) => value !== surface)+ )+ }+ />+ <FieldLabel htmlFor={`surface-${index}-${surface}`}>+ {SURFACE_LABELS[surface]}+ </FieldLabel>+ </Field>+ ))}+ </div><FieldError>{fieldState.error?.message}</FieldError></FieldContent></Field>)}/>- <RemoveRowButton- ariaLabel={`Remove substitution ${index + 1}`}- hasLabelRow- onClick={() => substitutions.remove(index)}- /></div>+ ))}- <Controller- control={control}- name={`substitutions.${index}.surfaces`}- render={({ field, fieldState }) => (- <Field>- <FieldContent>- <FieldLabel className="text-xs">- Replace In- <HoverCard openDelay={200} closeDelay={150}>- <HoverCardTrigger asChild>- <InfoIcon />- </HoverCardTrigger>- <HoverCardContent className="w-96" side="top" align="start">- <SubstitutionExample />- </HoverCardContent>- </HoverCard>- </FieldLabel>- <div className="mt-2 flex flex-wrap gap-x-5 gap-y-2">- {SURFACES.map((surface) => (- <Field key={surface} orientation="horizontal" className="w-auto">- <Checkbox- id={`surface-${index}-${surface}`}- isChecked={field.value.includes(surface)}- onCheckedChange={(checked) =>- field.onChange(- checked === true- ? [...field.value, surface]- : field.value.filter((value) => value !== surface)- )- }- />- <FieldLabel htmlFor={`surface-${index}-${surface}`}>- {SURFACE_LABELS[surface]}- </FieldLabel>- </Field>- ))}- </div>- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />- </div>- ))}-- {substitutions.fields.length < MAX_SUBSTITUTIONS && (- <Button- variant="ghost"- size="xs"- className="self-start"- onClick={() =>- substitutions.append({- placeholder: "",- value: "",- surfaces: [AgentVaultSubstitutionSurface.Header]- })- }- >- <PlusIcon className="mr-1 size-4" />- Add Substitution- </Button>- )}+ {substitutions.fields.length < MAX_SUBSTITUTIONS && (+ <Button+ variant="ghost"+ size="xs"+ className="self-start"+ onClick={() =>+ substitutions.append({+ placeholder: "",+ value: "",+ surfaces: [AgentVaultSubstitutionSurface.Header]+ })+ }+ >+ <PlusIcon className="mr-1 size-4" />+ Add Substitution+ </Button>+ )}- <Controller- control={control}- name="substitutions"- render={({ fieldState }) => <FieldError>{fieldState.error?.message}</FieldError>}- />+ <Controller+ control={control}+ name="substitutions"+ render={({ fieldState }) => (+ <FieldError>{fieldState.error?.message}</FieldError>+ )}+ />+ </div></div>- </div>+ )}</div></AccordionContent></AccordionItem>diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.tsnew file mode 100644index 0000000000..709a33b6f1--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts@@ -0,0 +1,255 @@+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: [],+ 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",+ 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"+ },+ 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" });+ 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",+ name: "stripe",+ hostPattern: "api.stripe.com",+ allowedMethods: null,+ allowedPathPrefixes: null,+ credential: {+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: undefined+ },+ 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+ });+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ form({+ credentialType: AgentVaultCredentialType.Basic,+ username: UNCHANGED_SECRET,+ secret: ""+ })+ ).credential+ ).toEqual({ type: AgentVaultCredentialType.Basic, username: undefined, password: "" });+ });++ 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",+ 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 --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.tsnew file mode 100644index 0000000000..f5e40f3a44--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts@@ -0,0 +1,141 @@+import { AgentVaultCredentialType, AgentVaultServiceType } 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 buildHttpCredential = (data: TServiceForm): TAgentVaultCredentialInput => {+ if (data.credentialType === AgentVaultCredentialType.Passthrough) {+ return { type: AgentVaultCredentialType.Passthrough };+ }+ if (data.credentialType === AgentVaultCredentialType.Basic) {+ return {+ type: AgentVaultCredentialType.Basic,+ username: data.username ?? "",+ password: data.secret ?? ""+ };+ }+ return bearerCredential(data);+};++// 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 => {+ 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 ?? "")+ };+ }+ return {+ type: AgentVaultCredentialType.Bearer,+ headerName: data.headerName || "Authorization",+ headerPrefix: data.headerPrefix ?? "",+ value: isSecretUntouched || !data.secret ? undefined : data.secret+ };+};++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, ...buildHttpFields(data), credential: buildHttpCredential(data) };++export const buildUpdateServiceRequest = (+ accessBundleId: string,+ serviceId: string,+ data: TServiceForm+): TUpdateAgentVaultServiceDTO =>+ data.serviceType === AgentVaultServiceType.Mcp+ ? {+ accessBundleId,+ serviceId,+ ...buildMcpFields(data),+ ...withCredential(buildMcpCredentialPatch(data))+ }+ : {+ accessBundleId,+ serviceId,+ ...buildHttpFields(data),+ credential: buildHttpCredentialPatch(data)+ };diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.tsnew file mode 100644index 0000000000..87933e1089--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts@@ -0,0 +1,234 @@+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,+ 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: [],+ 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,+ config: { 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,+ authorizedBy: 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/);+ });++ 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"+ }+ } 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");+ });+});++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(513), oauthClientSecret: "x".repeat(1025) })+ );+ expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual([+ "oauthClientId",+ "oauthClientSecret"+ ]);+ });++ 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);+ 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 --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 5304b358e4..e26e9d4c95 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -6,9 +6,15 @@ import { variableReferenceError } from "@app/helpers/agentVaultVariables";import {AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,+ AgentVaultOAuthStatus,+ AgentVaultServiceType,AgentVaultSubstitutionSurface} 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";/**@@ -27,7 +33,30 @@ export const displayHostPattern = (hostPattern: string) =>export const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {[AgentVaultCredentialType.Bearer]: "Bearer",[AgentVaultCredentialType.Basic]: "Basic Auth",- [AgentVaultCredentialType.Passthrough]: "Pass-through"+ [AgentVaultCredentialType.Passthrough]: "Pass-through",+ [AgentVaultCredentialType.OAuth]: "OAuth 2.1"+};++export const HTTP_CREDENTIAL_TYPES = [+ AgentVaultCredentialType.Bearer,+ AgentVaultCredentialType.Basic,+ AgentVaultCredentialType.Passthrough+];++export const OAUTH_STATUS_LABELS: Record<AgentVaultOAuthStatus, string> = {+ [AgentVaultOAuthStatus.Connected]: "Connected",+ [AgentVaultOAuthStatus.NeedsReauthorization]: "Needs Reauthorization",+ [AgentVaultOAuthStatus.NeedsAdditionalScopes]: "Needs Additional Scopes"+};++export const SERVICE_TYPE_LABELS: Record<AgentVaultServiceType, string> = {+ [AgentVaultServiceType.Http]: "HTTP API",+ [AgentVaultServiceType.Mcp]: "MCP Server"+};++export const TRANSPORT_LABELS: Record<AgentVaultMcpTransport, string> = {+ [AgentVaultMcpTransport.StreamableHttp]: "Streamable HTTP",+ [AgentVaultMcpTransport.Sse]: "SSE"};export const HTTP_METHODS = Object.values(AgentVaultHttpMethod);@@ -46,6 +75,35 @@ export const MAX_PATH_PREFIXES = 20;// The column holds every host as one comma-joined string, so this caps the join, not any single host.const AGENT_VAULT_MAX_HOST_PATTERN_LENGTH = 1024;+const MAX_SERVER_URL_LENGTH = 2048;++export const serverUrlError = (value: string): string | null => {+ const trimmed = value.trim();+ if (!trimmed) return "Enter the server URL.";+ if (trimmed.length > MAX_SERVER_URL_LENGTH) {+ return `A server URL can be at most ${MAX_SERVER_URL_LENGTH} characters.`;+ }+ if (/\s/.test(trimmed)) return "The server URL can't contain spaces.";+ // On the raw text: the URL parser reads "https:host" as if it were "https://host".+ if (!/^https:\/\//i.test(trimmed)) {+ return "The server URL must start with https://, as in https://mcp.example.com/mcp.";+ }+ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ return "Enter a full URL, as in https://mcp.example.com/mcp.";+ }+ if (url.username || url.password) {+ return "Remove the credentials from the URL. Add them on the Credential step instead.";+ }+ if (trimmed.includes("#")) return "Remove the # fragment from the URL.";+ if (trimmed.includes("?")) {+ return "Server URLs can't include a query string, since it is stored and shown in plaintext. Put a token in the Bearer token or a custom header instead.";+ }+ return null;+};+export const SURFACE_LABELS: Record<AgentVaultSubstitutionSurface, string> = {[AgentVaultSubstitutionSurface.Path]: "URL Path",[AgentVaultSubstitutionSurface.Query]: "Query String",@@ -104,11 +162,75 @@ export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {[ServiceStep.Review]: []};+export const MCP_SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {+ [ServiceStep.Template]: [],+ [ServiceStep.Details]: ["name", "serverUrl", "transport"],+ [ServiceStep.Credential]: [+ "credentialType",+ "headerName",+ "headerPrefix",+ "secret",+ "oauthAuthorizationId",+ "oauthClientId",+ "oauthClientSecret",+ "customHeaders"+ ],+ [ServiceStep.Review]: []+};++// Spelled out rather than picked from TServiceForm, which is inferred from the schema that calls these.+type TOAuthFormState = {+ serverUrl: string;+ oauthAuthorizationId: string;+ oauthAuthorizedUrl: string;+};++// Reusing an authorization after the server URL changes could attach its tokens to another host.+export const newOAuthAuthorizationId = (form: TOAuthFormState) =>+ form.oauthAuthorizationId && form.oauthAuthorizedUrl === form.serverUrl.trim()+ ? form.oauthAuthorizationId+ : undefined;++export const storedOAuthCredential = (+ service: TAgentVaultService | null | undefined,+ serverUrl: string+): TAgentVaultOAuthCredentialSummary | null =>+ service?.type === AgentVaultServiceType.Mcp &&+ service.credential.type === AgentVaultCredentialType.OAuth &&+ service.config.serverUrl === serverUrl.trim()+ ? service.credential+ : null;++export const isOAuthAuthorizationMissing = (+ form: TOAuthFormState & {+ serviceType: AgentVaultServiceType;+ credentialType: AgentVaultCredentialType;+ },+ service?: TAgentVaultService | null+) => {+ if (+ form.serviceType !== AgentVaultServiceType.Mcp ||+ form.credentialType !== AgentVaultCredentialType.OAuth+ ) {+ return false;+ }+ return !newOAuthAuthorizationId(form) && !storedOAuthCredential(service, form.serverUrl);+};++export const oauthStatusLabel = (form: TOAuthFormState, service?: TAgentVaultService | null) => {+ const stored = storedOAuthCredential(service, form.serverUrl);+ if (newOAuthAuthorizationId(form)) return stored ? "Reauthorized" : "Authorized";+ return stored ? OAUTH_STATUS_LABELS[stored.status] : "Not authorized";+};+/** `variableKeys` stays undefined while the list loads, so only the shape of a reference is checked. */export const buildServiceSchema = (service?: TAgentVaultService | null, variableKeys?: string[]) =>z.object({+ serviceType: z.nativeEnum(AgentVaultServiceType),name: slugSchema({ max: 64, field: "Name" }),+ serverUrl: z.string(),+ transport: z.nativeEnum(AgentVaultMcpTransport),hosts: z.array(z.string()),// In the form rather than component state so the resolver sees it: trigger() wipes anything set with// setError, so a refusal held outside the form would let the step advance.@@ -127,6 +249,19 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variableheaderPrefix: z.string().trim().max(64).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()),+ oauthClientId: z+ .string()+ .trim()+ .max(512, "A client ID can be at most 512 characters.")+ .optional(),+ oauthClientSecret: z+ .string()+ .max(1024, "A client secret can be at most 1024 characters.")+ .optional(),methods: z.array(z.nativeEnum(AgentVaultHttpMethod)),pathPrefixes: z.array(z.string())@@ -153,15 +288,40 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variable.max(MAX_SUBSTITUTIONS, `You can add at most ${MAX_SUBSTITUTIONS} substitutions.`)}).superRefine((data, ctx) => {- addHostIssues(data.hosts, ctx, ["hosts"]);- const hostDraft = data.hostDraft.trim();+ const isMcp = data.serviceType === AgentVaultServiceType.Mcp;+ if (isMcp) {+ const urlError = serverUrlError(data.serverUrl);+ if (urlError) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["serverUrl"], message: urlError });+ }+ if (+ data.credentialType !== AgentVaultCredentialType.Bearer &&+ data.credentialType !== AgentVaultCredentialType.OAuth+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["credentialType"],+ message: "An MCP server takes OAuth 2.1 or a bearer token."+ });+ }+ if (isOAuthAuthorizationMissing(data, service)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["oauthAuthorizationId"],+ message: "Authorize the server to continue."+ });+ }+ }++ if (!isMcp) addHostIssues(data.hosts, ctx, ["hosts"]);+ const hostDraft = isMcp ? "" : data.hostDraft.trim();if (hostDraft) {ctx.addIssue({code: z.ZodIssueCode.custom,path: ["hosts"],message: hostError(hostDraft, data.hosts) ?? `Add "${hostDraft}" or clear it.`});- } else if (data.hosts.length === 0) {+ } else if (!isMcp && data.hosts.length === 0) {ctx.addIssue({code: z.ZodIssueCode.custom,path: ["hosts"],@@ -169,7 +329,7 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variable});}- const pathDraft = data.pathDraft.trim();+ const pathDraft = isMcp ? "" : data.pathDraft.trim();if (pathDraft) {ctx.addIssue({code: z.ZodIssueCode.custom,@@ -186,7 +346,7 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variable});}- if (data.methods.length === 0) {+ if (!isMcp && data.methods.length === 0) {ctx.addIssue({code: z.ZodIssueCode.custom,path: ["methods"],@@ -194,18 +354,23 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variable});}- addPathPrefixIssues(data.pathPrefixes, ctx, ["pathPrefixes"]);+ if (!isMcp) addPathPrefixIssues(data.pathPrefixes, ctx, ["pathPrefixes"]);++ const hasHeaderShape = data.credentialType === AgentVaultCredentialType.Bearer;let credentialHeader: string | null = null;- if (data.credentialType === AgentVaultCredentialType.Bearer) {+ if (hasHeaderShape) {credentialHeader = data.headerName || "Authorization";- } else if (data.credentialType === AgentVaultCredentialType.Basic) {+ } else if (+ data.credentialType === AgentVaultCredentialType.Basic ||+ data.credentialType === AgentVaultCredentialType.OAuth+ ) {credentialHeader = "Authorization";}- // Basic always writes Authorization, which is not reserved, so only bearer can name one.+ // Basic and OAuth always write Authorization, which is not reserved, so only bearer can name one.if (- data.credentialType === AgentVaultCredentialType.Bearer &&+ hasHeaderShape &&data.headerName &&RESERVED_HEADER_NAMES.has(data.headerName.toLowerCase())) {@@ -216,11 +381,7 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variable});}- if (- data.credentialType === AgentVaultCredentialType.Bearer &&- data.headerPrefix &&- hasDoubleBraces(data.headerPrefix)- ) {+ if (hasHeaderShape && data.headerPrefix && hasDoubleBraces(data.headerPrefix)) {ctx.addIssue({code: z.ZodIssueCode.custom,path: ["headerPrefix"],@@ -303,7 +464,10 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variableif (message) ctx.addIssue({ code: z.ZodIssueCode.custom, path, message });};- if (data.credentialType !== AgentVaultCredentialType.Passthrough) {+ if (+ data.credentialType !== AgentVaultCredentialType.Passthrough &&+ data.credentialType !== AgentVaultCredentialType.OAuth+ ) {addReferenceIssue(data.secret, ["secret"]);}if (data.credentialType === AgentVaultCredentialType.Basic) {@@ -316,7 +480,12 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variableaddReferenceIssue(substitution.value, ["substitutions", index, "value"]));- if (data.credentialType === AgentVaultCredentialType.Passthrough) return;+ if (+ data.credentialType === AgentVaultCredentialType.Passthrough ||+ data.credentialType === AgentVaultCredentialType.OAuth+ ) {+ return;+ }const isUnchanged = data.secret === UNCHANGED_SECRET;diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.tsindex 86b2644984..cda7daac5a 100644--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts@@ -15,6 +15,9 @@ type StepMeta = {rightTip?: string;};+const VARIABLE_TIP =+ "To use one of this bundle's variables, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place.";+export const SERVICE_STEPS: StepMeta[] = [{step: ServiceStep.Template,@@ -39,8 +42,44 @@ export const SERVICE_STEPS: StepMeta[] = [rightLabel: "CREDENTIAL",rightDescription:"Agents reach this service without ever holding the credential themselves. Custom headers go out on top of it, and a substitution swaps a placeholder your agent already sends for the real value.",- rightTip:- "To use one of this bundle's variables, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place."+ rightTip: VARIABLE_TIP+ },+ {+ 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 MCP_SERVICE_STEPS: StepMeta[] = [+ {+ step: ServiceStep.Template,+ name: "Template"+ },+ {+ step: ServiceStep.Details,+ name: "Details",+ shortDescription: "Name, transport and server",+ title: "Details",+ subtitle: "What this service is called and the MCP server it connects to.",+ rightLabel: "DETAILS",+ rightDescription:+ "The agent connects to this server through the proxy, which adds the credential. Tools come later: most servers only list them to an authenticated session."+ },+ {+ step: ServiceStep.Credential,+ name: "Credential",+ shortDescription: "How to authenticate",+ title: "Credential",+ subtitle: "How the proxy authenticates to this MCP server.",+ rightLabel: "CREDENTIAL",+ rightDescription:+ "The proxy authenticates to the MCP server for the agent. Infisical refreshes OAuth tokens automatically, and the agent never sees them. The agent can call any tool the server exposes to this credential.",+ rightTip: VARIABLE_TIP},{step: ServiceStep.Review,diff --git a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.tsnew file mode 100644index 0000000000..7850d9941c--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts@@ -0,0 +1,175 @@+import { useCallback, useEffect, useRef, useState } from "react";+import axios from "axios";++import {+ AgentVaultOAuthAuthorizationStatus,+ useCreateAgentVaultOAuthAuthorization,+ useGetAgentVaultOAuthAuthorization+} from "@app/hooks/api/agentVault";+import {+ TAgentVaultOAuthAuthorization,+ TCreateAgentVaultOAuthAuthorizationDTO+} from "@app/hooks/api/agentVault/types";++const POLL_TIMEOUT_MS = 5 * 60 * 1000;+const POPUP_NAME = "infisical-agent-vault-oauth";+const POPUP_FEATURES = "popup,width=600,height=720";++export type TOAuthAuthorizeState =+ | { status: "idle" }+ | { status: "starting" }+ | { status: "pending"; popupClosed: boolean }+ | { status: "authorized"; authorization: TAgentVaultOAuthAuthorization }+ | { status: "failed"; message: string };++const serverMessage = (error: unknown) => {+ if (!axios.isAxiosError<{ message?: unknown }>(error)) return null;+ const message = error.response?.data?.message;+ return typeof message === "string" ? message : null;+};++export const useOAuthAuthorize = ({+ onAuthorized+}: {+ onAuthorized: (authorization: TAgentVaultOAuthAuthorization) => void;+}) => {+ const createAuthorization = useCreateAgentVaultOAuthAuthorization();+ const [state, setState] = useState<TOAuthAuthorizeState>({ status: "idle" });+ const [isClientRequired, setIsClientRequired] = useState(false);+ const [redirectUri, setRedirectUri] = useState<string | null>(null);+ const [registrationError, setRegistrationError] = useState<string | null>(null);+ const [pendingAuthorization, setPendingAuthorization] = useState<{+ id: string;+ attempt: number;+ } | null>(null);+ const {+ data: authorization,+ error: authorizationError,+ dataUpdatedAt+ } = useGetAgentVaultOAuthAuthorization(pendingAuthorization?.id ?? "");++ const popupRef = useRef<Window | null>(null);+ // Bumped by every new attempt and by cancel, so a response for an older attempt is dropped.+ const attemptRef = useRef(0);+ const onAuthorizedRef = useRef(onAuthorized);+ onAuthorizedRef.current = onAuthorized;++ const stop = useCallback(() => {+ attemptRef.current += 1;+ setPendingAuthorization(null);+ if (popupRef.current && !popupRef.current.closed) popupRef.current.close();+ popupRef.current = null;+ }, []);++ useEffect(() => stop, [stop]);++ const fail = useCallback(+ (message: string) => {+ stop();+ setState({ status: "failed", message });+ },+ [stop]+ );++ useEffect(() => {+ if (!pendingAuthorization || attemptRef.current !== pendingAuthorization.attempt) return;+ if (authorizationError) {+ fail(+ serverMessage(authorizationError) ??+ "Couldn't check the authorization status. Select Authorize to try again."+ );+ return;+ }+ if (!authorization) return;+ if (authorization.status === AgentVaultOAuthAuthorizationStatus.Authorized) {+ stop();+ setState({ status: "authorized", authorization });+ onAuthorizedRef.current(authorization);+ return;+ }+ if (authorization.status === AgentVaultOAuthAuthorizationStatus.Failed) {+ fail(authorization.error ?? "The server refused the authorization. Try again.");+ return;+ }++ // Cross-Origin-Opener-Policy can report an open popup as closed, so this changes only the hint.+ const popupClosed = !popupRef.current || popupRef.current.closed;+ setState((previous) =>+ previous.status === "pending" && previous.popupClosed !== popupClosed+ ? { status: "pending", popupClosed }+ : previous+ );+ }, [pendingAuthorization, authorization, authorizationError, dataUpdatedAt, fail, stop]);++ useEffect(() => {+ if (!pendingAuthorization) return undefined;+ const timeout = window.setTimeout(() => {+ if (attemptRef.current === pendingAuthorization.attempt) {+ fail("The authorization timed out after 5 minutes. Select Authorize to try again.");+ }+ }, POLL_TIMEOUT_MS);+ return () => window.clearTimeout(timeout);+ }, [pendingAuthorization, fail]);++ // Call straight from the click handler: browsers only allow a popup opened during a user gesture,+ // so it is opened blank first and pointed at the authorize URL once the server returns it.+ const authorize = useCallback(+ (params: TCreateAgentVaultOAuthAuthorizationDTO) => {+ stop();+ const attempt = attemptRef.current;++ const popup = window.open("", POPUP_NAME, POPUP_FEATURES);+ if (!popup) {+ setState({+ status: "failed",+ message:+ "Your browser blocked the authorization window. Allow pop-ups for this site, then select Authorize again."+ });+ return;+ }+ // The authorization server, possibly an admin-entered one, gets no handle on this tab.+ popup.opener = null;+ popupRef.current = popup;+ setState({ status: "starting" });++ createAuthorization+ .mutateAsync(params)+ .then(+ ({+ registrationRequired,+ redirectUri: uri,+ registrationError: reason,+ authorization: createdAuthorization+ }) => {+ if (attemptRef.current !== attempt) return;+ if (registrationRequired || !createdAuthorization) {+ stop();+ setIsClientRequired(true);+ setRedirectUri(uri);+ setRegistrationError(reason);+ setState({ status: "idle" });+ return;+ }+ popup.location.href = createdAuthorization.authorizeUrl;+ setState({ status: "pending", popupClosed: false });+ setPendingAuthorization({ id: createdAuthorization.id, attempt });+ }+ )+ .catch((error: unknown) => {+ if (attemptRef.current !== attempt) return;+ fail(+ serverMessage(error) ??+ "Couldn't start the authorization. Check the server URL and try again."+ );+ });+ },+ [createAuthorization, fail, stop]+ );++ const cancel = useCallback(() => {+ stop();+ setState({ status: "idle" });+ }, [stop]);++ return { state, isClientRequired, redirectUri, registrationError, authorize, cancel };+};diff --git a/frontend/src/helpers/agentVaultTemplates.ts b/frontend/src/helpers/agentVaultTemplates.tsindex 1049e5b92c..a32ade7c5a 100644--- a/frontend/src/helpers/agentVaultTemplates.ts+++ b/frontend/src/helpers/agentVaultTemplates.ts@@ -1,4 +1,8 @@-import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";+import {+ AgentVaultCredentialType,+ AgentVaultMcpTransport,+ AgentVaultServiceType+} from "@app/hooks/api/agentVault";// Copied from the proxied-services catalog rather than imported: that module stays independently// deletable, and Agent Vault's grammar rejects the paths several of its entries carry.@@ -17,7 +21,8 @@ export type AgentVaultTemplateCredential =| { type: AgentVaultCredentialType.Basic }| { type: AgentVaultCredentialType.Passthrough };-export type AgentVaultTemplate = {+export type AgentVaultHttpTemplate = {+ serviceType: AgentVaultServiceType.Http;key: string;name: string;image: string;@@ -28,7 +33,23 @@ export type AgentVaultTemplate = {credential: AgentVaultTemplateCredential;};-export const AGENT_VAULT_TEMPLATES: AgentVaultTemplate[] = [+export type AgentVaultMcpTemplate = {+ serviceType: AgentVaultServiceType.Mcp;+ key: string;+ name: string;+ image: string;+ description: string;+ serverUrl: string;+ transport: AgentVaultMcpTransport;+ aliases?: string[];+ credential:+ | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string }+ | { type: AgentVaultCredentialType.OAuth };+};++export type AgentVaultTemplate = AgentVaultHttpTemplate | AgentVaultMcpTemplate;++const HTTP_TEMPLATES: Omit<AgentVaultHttpTemplate, "serviceType">[] = [{key: "openai",name: "OpenAI",@@ -379,6 +400,58 @@ export const AGENT_VAULT_TEMPLATES: AgentVaultTemplate[] = [}];+export const AGENT_VAULT_TEMPLATES: AgentVaultHttpTemplate[] = HTTP_TEMPLATES.map((template) => ({+ ...template,+ serviceType: AgentVaultServiceType.Http+}));++export const AGENT_VAULT_MCP_TEMPLATES: AgentVaultMcpTemplate[] = [+ {+ serviceType: AgentVaultServiceType.Mcp,+ key: "github-mcp",+ name: "GitHub MCP",+ image: "GitHub.png",+ description: "Repos, issues, and pull requests as MCP tools.",+ serverUrl: "https://api.githubcopilot.com/mcp/",+ transport: AgentVaultMcpTransport.StreamableHttp,+ aliases: ["github", "mcp"],+ credential: { type: AgentVaultCredentialType.Bearer }+ },+ {+ serviceType: AgentVaultServiceType.Mcp,+ key: "linear-mcp",+ name: "Linear MCP",+ image: "Linear.svg",+ description: "Issues and projects as MCP tools.",+ serverUrl: "https://mcp.linear.app/mcp",+ transport: AgentVaultMcpTransport.StreamableHttp,+ aliases: ["linear", "mcp"],+ credential: { type: AgentVaultCredentialType.OAuth }+ },+ {+ serviceType: AgentVaultServiceType.Mcp,+ key: "notion-mcp",+ name: "Notion MCP",+ image: "Notion.svg",+ description: "Pages and databases as MCP tools.",+ serverUrl: "https://mcp.notion.com/mcp",+ transport: AgentVaultMcpTransport.StreamableHttp,+ aliases: ["notion", "mcp"],+ credential: { type: AgentVaultCredentialType.OAuth }+ },+ {+ serviceType: AgentVaultServiceType.Mcp,+ key: "sentry-mcp",+ name: "Sentry MCP",+ image: "Sentry.svg",+ description: "Issues and errors as MCP tools.",+ serverUrl: "https://mcp.sentry.dev/mcp",+ transport: AgentVaultMcpTransport.StreamableHttp,+ aliases: ["sentry", "mcp"],+ credential: { type: AgentVaultCredentialType.OAuth }+ }+];+export const POPULAR_AGENT_VAULT_TEMPLATES = ["openai","anthropic",@@ -401,16 +474,46 @@ const hostMatchesTemplateHost = (host: string, templateHost: string) => {return !host.slice(0, host.length - suffix.length - 1).includes(".");};-export const findTemplateForHostPattern = (hostPattern: string): AgentVaultTemplate | undefined => {- const hosts = hostPattern+const hostOfUrl = (url: string) => {+ try {+ return new URL(url).hostname;+ } catch {+ return "";+ }+};++const templateHosts = (template: AgentVaultTemplate) =>+ template.serviceType === AgentVaultServiceType.Mcp+ ? [hostOfUrl(template.serverUrl)]+ : template.hostPattern.split(",").map((entry) => stripPort(entry.trim()));++const hostsOfPattern = (hostPattern: string) =>+ hostPattern.split(",").map((entry) => stripPort(entry.trim())).filter(Boolean);+export const findTemplateForHostPattern = (+ hostPattern: string+): AgentVaultHttpTemplate | undefined => {+ const hosts = hostsOfPattern(hostPattern);+return AGENT_VAULT_TEMPLATES.find((template) =>- template.hostPattern- .split(",")- .map((entry) => stripPort(entry.trim()))- .some((templateHost) => hosts.some((host) => hostMatchesTemplateHost(host, templateHost)))+ templateHosts(template).some((templateHost) =>+ hosts.some((host) => hostMatchesTemplateHost(host, templateHost))+ )+ );+};++/** For icons: an MCP service's host pattern is derived from its server URL, so the MCP templates match it too. */+export const findAnyTemplateForHostPattern = (+ hostPattern: string+): AgentVaultTemplate | undefined => {+ const hosts = hostsOfPattern(hostPattern);+ return (+ findTemplateForHostPattern(hostPattern) ??+ AGENT_VAULT_MCP_TEMPLATES.find((template) =>+ templateHosts(template).some((templateHost) => hosts.includes(templateHost))+ ));};diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.tsindex 75d997b948..b353500498 100644--- a/frontend/src/hooks/api/agentVault/enums.ts+++ b/frontend/src/hooks/api/agentVault/enums.ts@@ -15,10 +15,33 @@ export enum AgentVaultSubstitutionSurface {Body = "body"}+export enum AgentVaultServiceType {+ Http = "http",+ Mcp = "mcp"+}++export enum AgentVaultMcpTransport {+ StreamableHttp = "streamable-http",+ Sse = "sse"+}+export enum AgentVaultCredentialType {Bearer = "bearer",Basic = "basic",- Passthrough = "passthrough"+ Passthrough = "passthrough",+ OAuth = "oauth"+}++export enum AgentVaultOAuthStatus {+ Connected = "connected",+ NeedsReauthorization = "needs-reauthorization",+ NeedsAdditionalScopes = "needs-additional-scopes"+}++export enum AgentVaultOAuthAuthorizationStatus {+ Pending = "pending",+ Authorized = "authorized",+ Failed = "failed"}export enum AgentVaultMemberType {diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 5f3c6062ee..027c4bc693 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -15,6 +15,7 @@ import {TAgentVaultGrantedMember,TAgentVaultMemberWriteResult,TAgentVaultMintedSession,+ TAgentVaultOAuthAuthorization,TAgentVaultProxy,TAgentVaultProxySettingsDTO,TAgentVaultService,@@ -22,7 +23,10 @@ import {TAgentVaultVariable,TAgentVaultVariableRef,TAgentVaultWrittenMember,+ TCompleteAgentVaultOAuthAuthorizationDTO,TCreateAgentVaultAccessBundleDTO,+ TCreateAgentVaultOAuthAuthorizationDTO,+ TCreateAgentVaultOAuthAuthorizationResponse,TCreateAgentVaultServiceDTO,TCreateAgentVaultSessionDTO,TCreateAgentVaultVariableDTO,@@ -459,3 +463,33 @@ export const useRevealAgentVaultVariableValue = () =>return data.value;}});++export const useCreateAgentVaultOAuthAuthorization = () =>+ useMutation({+ // Discovery and registration failures name the server and what failed, and the Authorize card+ // shows them in place.+ meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError] },+ 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, "NotFound"] },+ 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;+ }+ });diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 8a02265057..85086103f4 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -5,7 +5,7 @@ import axios from "axios";import { apiRequest } from "@app/config/request";import { useOrganization } from "@app/context";-import { AgentVaultMemberType } from "./enums";+import { AgentVaultMemberType, AgentVaultOAuthAuthorizationStatus } from "./enums";import {createSessionLogChunkCache,decryptSessionLogPage,@@ -22,6 +22,7 @@ import {TAgentVaultAccessBundleListItem,TAgentVaultDecryptedSessionLogPage,TAgentVaultMember,+ TAgentVaultOAuthAuthorization,TAgentVaultProductActor,TAgentVaultProductMember,TAgentVaultProductMemberOf,@@ -45,6 +46,17 @@ export const fetchAgentVaultProjectId = async () => {return data.projectId;};+export const fetchAgentVaultOAuthAuthorization = async (+ authorizationId: string,+ signal?: AbortSignal+) => {+ const { data } = await apiRequest.get<{ authorization: TAgentVaultOAuthAuthorization }>(+ `/api/v1/agent-vault/oauth/authorizations/${encodeURIComponent(authorizationId)}`,+ { signal }+ );+ return data.authorization;+};+export const AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS = 15_000;const SESSION_LOG_GAP_FILL_INTERVAL_MS = 60_000;@@ -60,6 +72,8 @@ export const getSessionLogStorageError = (error: unknown) =>// path parameter: without it a switch to another org would serve the previous org's data from cache.export const agentVaultKeys = {all: (orgId: string) => ["agent-vault", orgId] as const,+ oauthAuthorization: (orgId: string, authorizationId: string) =>+ [...agentVaultKeys.all(orgId), "oauth-authorizations", authorizationId] as const,accessBundles: (orgId: string) => [...agentVaultKeys.all(orgId), "access-bundles"] as const,accessBundle: (orgId: string, accessBundleId: string) =>[...agentVaultKeys.accessBundles(orgId), accessBundleId] as const,@@ -109,6 +123,26 @@ export const agentVaultKeys = {[...agentVaultKeys.sessions(orgId), sessionId, "logs-live", range ?? {}] as const};+export const useGetAgentVaultOAuthAuthorization = (authorizationId: string) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.oauthAuthorization(currentOrg.id, authorizationId),+ queryFn: ({ signal }) => fetchAgentVaultOAuthAuthorization(authorizationId, signal),+ enabled: Boolean(authorizationId),+ staleTime: 0,+ gcTime: 0,+ retry: false,+ refetchInterval: (query) =>+ query.state.error ||+ (query.state.data && query.state.data.status !== AgentVaultOAuthAuthorizationStatus.Pending)+ ? false+ : 2000,+ // The provider popup can leave the Infisical tab in the background until authorization finishes.+ refetchIntervalInBackground: true+ });+};+export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentVaultMemberType>(params: TListAgentVaultMembersDTO & { actorType?: T } = {},enabled = truediff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.tsindex 7573114aaa..b5d4738405 100644--- a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts@@ -43,6 +43,26 @@ describe("parseSessionLogRecords", () => {it("refuses anything that is not an array of records", () => {assert.equal(parseSessionLogRecords({ records: [record] }), null);});++ it("keeps the service type and MCP calls of an MCP record", () => {+ const mcpRecord = {+ ...record,+ method: "POST",+ decision: "brokered",+ service: "linear",+ serviceType: "mcp",+ mcp: { calls: [{ method: "tools/call", tool: "create_issue" }], parsed: true }+ };+ assert.deepEqual(parseSessionLogRecords([mcpRecord]), [mcpRecord]);+ });++ it("drops a malformed MCP detail rather than the whole chunk", () => {+ const [parsed] = parseSessionLogRecords([+ { ...record, serviceType: "mcp", mcp: { calls: "tools/call" } }+ ])!;+ assert.equal(parsed.serviceType, "mcp");+ assert.equal(parsed.mcp, undefined);+ });});describe("recordsMatchChunk", () => {@@ -84,7 +104,7 @@ describe("decryptSessionLogPage", () => {// The same object Go's TestSealMatchesTheBrowserVector seals: the IV, then the ciphertext and tag.const sealed = Uint8Array.from(atob(- "qrvM3e7/ABEiM0RVPLRwxBbgu+W68Br1N9gY1oUy8wjJxQClAtBh0NfJS1UcWOCPn3laS615sIqwFONhPIPNWRI3CA+a5tUJ7aoim0sQkE4d9gzou2mc/AWiCdToVBJPtdumA9jIzh3yAI81YPwcoDXEVnq2+7ooNNJShGdLX95itbrna/t4nFKRKSSgNzbH23eMtSMcSo72puk/2iwh4sVbTKzC2kwvbf1U6Mgd21zkIq2jDKKwhcT6mTfjPivW4FzmmkspQVMoWwANRX+QVyXzrMipZfoq5N/UcUI6rCvRUkqg+3ST5GVMelW0mjOO"+ "qrvM3e7/ABEiM0RVPLRwxBbgu+W68Br1N9gY1oUy8wjJxQClAtBh0NfJS1UcWOCPn3laS615sIqwFONhPIPNWRI3CA+a5tUJ7aoim0sQkE4d9gzou2mc/AWiCdToVBJPtdumA9jIzh3yAI81YPwcoDXEVnq2+7ooNNJShGdLX95itbrna/t4nFKRKSSgNzbH23eMtSMcSo72puk/2iwh4sVbTKzC2kwvbf1U6Mgd21zkIq2jDKKwhcT6mTfjPivW4FzmmkspQVMoWwANRX+QVyXzrMipZfoq5N/UcUI6/VTBSsIZvF08UTnPeIW+yM1I5hHCoi0WQT6QRe0bdx5+BvGuvJQB"),(char) => char.charCodeAt(0));@@ -242,6 +262,7 @@ describe("decryptSessionLogPage", () => {assert.equal(result.decrypted[key].gap, null);assert.equal(result.decrypted[key].records[0].path, "/zen");+ assert.equal(result.decrypted[key].records[0].serviceType, "http");});it("refuses a chunk whose records name a different proxy than its file", async () => {diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.tsindex 9670faa688..a419e256ef 100644--- a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts@@ -65,7 +65,16 @@ const SessionLogRecordsSchema = z.array(status: z.number().int(),decision: z.string(),service: z.string().nullable(),- accessBundle: z.string().nullable()+ accessBundle: z.string().nullable(),+ serviceType: z.string().nullish(),+ // A malformed detail drops only the detail. Failing the parse would hide the whole chunk.+ mcp: z+ .object({+ calls: z.array(z.object({ method: z.string(), tool: z.string().nullish() })),+ parsed: z.boolean()+ })+ .optional()+ .catch(undefined)}));diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 7f1fc2a772..cc918321e8 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -1,7 +1,11 @@import {AgentVaultCredentialType,AgentVaultHttpMethod,+ AgentVaultMcpTransport,AgentVaultMemberType,+ AgentVaultOAuthAuthorizationStatus,+ AgentVaultOAuthStatus,+ AgentVaultServiceType,AgentVaultSessionLogDecision,AgentVaultSessionScope,AgentVaultSessionStatus,@@ -10,10 +14,23 @@ import {AgentVaultVariableReferenceField} from "./enums";+export type TAgentVaultOAuthCredentialSummary = {+ type: AgentVaultCredentialType.OAuth;+ status: AgentVaultOAuthStatus;+ issuer: string;+ grantedScopes: string[];+ requiredScopes: string[];+ expiresAt: string | null;+ authorizedBy: { userId: string; username: string } | null;+ authorizedAt: string | null;+ lastError: string | null;+};+export type TAgentVaultCredentialSummary =| { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }| { type: AgentVaultCredentialType.Basic }- | { type: AgentVaultCredentialType.Passthrough };+ | { type: AgentVaultCredentialType.Passthrough }+ | TAgentVaultOAuthCredentialSummary;export type TAgentVaultCredentialInput =| {@@ -25,6 +42,11 @@ export type TAgentVaultCredentialInput =| { type: AgentVaultCredentialType.Basic; username: string; password: string }| { type: AgentVaultCredentialType.Passthrough };+export type TAgentVaultOAuthCredentialInput = {+ type: AgentVaultCredentialType.OAuth;+ authorizationId: string;+};+export type TAgentVaultCredentialUpdate =| {type: AgentVaultCredentialType.Bearer;@@ -33,7 +55,8 @@ export type TAgentVaultCredentialUpdate =value?: string;}| { type: AgentVaultCredentialType.Basic; username?: string; password?: string }- | { type: AgentVaultCredentialType.Passthrough };+ | { type: AgentVaultCredentialType.Passthrough }+ | TAgentVaultOAuthCredentialInput;export type TAgentVaultCustomHeaderSummary = { id: string; name: string; prefix: string };@@ -72,7 +95,16 @@ export type TAgentVaultVariableReference = {| { field: AgentVaultVariableReferenceField.Substitution; substitutionId: string });-export type TAgentVaultService = {+export type TAgentVaultMcpServiceConfig = {+ serverUrl: string;+ transport: AgentVaultMcpTransport;+};++export type TAgentVaultServiceConfig =+ | { type: AgentVaultServiceType.Http; config: Record<string, never> }+ | { type: AgentVaultServiceType.Mcp; config: TAgentVaultMcpServiceConfig };++export type TAgentVaultService = TAgentVaultServiceConfig & {id: string;accessBundleId: string;name: string;@@ -254,16 +286,29 @@ export type TUpdateAgentVaultAccessBundleDTO = {description?: string | null;};-export type TCreateAgentVaultServiceDTO = {- accessBundleId: string;- name: string;- hostPattern: string;- allowedMethods?: AgentVaultHttpMethod[] | null;- allowedPathPrefixes?: string[] | null;- credential: TAgentVaultCredentialInput;- customHeaders?: TAgentVaultCustomHeaderInput[];- substitutions?: TAgentVaultSubstitutionInput[];-};+export type TCreateAgentVaultServiceDTO =+ | {+ accessBundleId: string;+ type?: AgentVaultServiceType.Http;+ name: string;+ hostPattern: string;+ allowedMethods?: AgentVaultHttpMethod[] | null;+ allowedPathPrefixes?: string[] | null;+ credential: TAgentVaultCredentialInput;+ customHeaders?: TAgentVaultCustomHeaderInput[];+ substitutions?: TAgentVaultSubstitutionInput[];+ }+ | {+ accessBundleId: string;+ type: AgentVaultServiceType.Mcp;+ name: string;+ serverUrl: string;+ transport: AgentVaultMcpTransport;+ credential:+ | Extract<TAgentVaultCredentialInput, { type: AgentVaultCredentialType.Bearer }>+ | TAgentVaultOAuthCredentialInput;+ customHeaders?: TAgentVaultCustomHeaderInput[];+ };export type TUpdateAgentVaultServiceDTO = {accessBundleId: string;@@ -272,11 +317,50 @@ export type TUpdateAgentVaultServiceDTO = {hostPattern?: string;allowedMethods?: AgentVaultHttpMethod[] | null;allowedPathPrefixes?: string[] | null;+ serverUrl?: string;+ transport?: AgentVaultMcpTransport;credential?: TAgentVaultCredentialUpdate;customHeaders?: TAgentVaultCustomHeaderInput[];substitutions?: TAgentVaultSubstitutionInput[];};+export type TAgentVaultOAuthAuthorization = {+ id: string;+ status: AgentVaultOAuthAuthorizationStatus;+ error: string | null;+ scopes: string[];+};++export type TCreateAgentVaultOAuthAuthorizationDTO = {+ accessBundleId: string;+ serverUrl: string;+ serviceId?: string;+ clientId?: string;+ clientSecret?: string;+};++export type TCreateAgentVaultOAuthAuthorizationResponse = {+ registrationRequired: boolean;+ redirectUri: string;+ // Why the server's registration endpoint refused Infisical; null when it simply has none.+ registrationError: string | null;+ authorization: {+ id: string;+ status: AgentVaultOAuthAuthorizationStatus;+ authorizeUrl: string;+ scopes: string[];+ } | null;+};++export type TCompleteAgentVaultOAuthAuthorizationDTO = {+ authorizationId: string;+ state: string;+ code?: string;+ iss?: string;+ error?: string;+ errorDescription?: string;+};+export type TAddAgentVaultMembersDTO = TAgentVaultActorIdsDTO & {accessBundleId: string;};@@ -355,6 +439,17 @@ export type TAgentVaultSessionLogTailPage = TAgentVaultSessionLogPage & {nextCursor: string;};+export type TAgentVaultSessionLogMcpCall = {+ method: string;+ tool?: string | null;+};++export type TAgentVaultSessionLogMcpDetail = {+ calls: TAgentVaultSessionLogMcpCall[];+ // False when the proxy could not read the body, as for one over its size limit.+ parsed: boolean;+};+export type TAgentVaultSessionLogRecord = {ts: string;seq: number;@@ -367,6 +462,9 @@ export type TAgentVaultSessionLogRecord = {decision: AgentVaultSessionLogDecision;service: string | null;accessBundle: string | null;+ // Absent on records written before service types existed, and null when no service matched.+ serviceType?: AgentVaultServiceType | null;+ mcp?: TAgentVaultSessionLogMcpDetail;};export type TAgentVaultSessionLogGapReason =diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 8b01fbd474..f9cf106e3f 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -478,6 +478,7 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.AGENT_VAULT_SERVICE_CREATE]: "Create service",[EventType.AGENT_VAULT_SERVICE_UPDATE]: "Update service",[EventType.AGENT_VAULT_SERVICE_DELETE]: "Delete service",+ [EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE]: "Authorize service credential",[EventType.AGENT_VAULT_VARIABLE_CREATE]: "Create variable",[EventType.AGENT_VAULT_VARIABLE_UPDATE]: "Update variable",[EventType.AGENT_VAULT_VARIABLE_DELETE]: "Delete variable",@@ -559,6 +560,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.AGENT_VAULT_SERVICE_CREATE,EventType.AGENT_VAULT_SERVICE_UPDATE,EventType.AGENT_VAULT_SERVICE_DELETE,+ EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE,EventType.AGENT_VAULT_VARIABLE_CREATE,EventType.AGENT_VAULT_VARIABLE_UPDATE,EventType.AGENT_VAULT_VARIABLE_DELETE,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex 0915b412ab..ec633f2e32 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -476,6 +476,7 @@ export enum EventType {AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",+ AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE = "agent-vault-service-credential-authorize",AGENT_VAULT_VARIABLE_CREATE = "agent-vault-variable-create",AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsxindex f247d48453..cc3f216613 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx@@ -14,6 +14,7 @@ import {import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";import { ServiceSheet } from "@app/components/agent-vault/service-sheet";+import { ServiceStep } from "@app/components/agent-vault/service-sheet/serviceSchema";import {Button,DropdownMenu,@@ -56,6 +57,7 @@ export const AgentVaultAccessBundleDetailPage = () => {const [isDeleteOpen, setIsDeleteOpen] = useState(false);const [isServiceSheetOpen, setIsServiceSheetOpen] = useState(false);const [serviceToEdit, setServiceToEdit] = useState<TAgentVaultService | null>(null);+ const [serviceSheetStep, setServiceSheetStep] = useState<ServiceStep | undefined>();if (isPending) return <PageLoader />;if (!accessBundle) {@@ -133,10 +135,17 @@ export const AgentVaultAccessBundleDetailPage = () => {canManage={isAdmin}onAdd={() => {setServiceToEdit(null);+ setServiceSheetStep(undefined);setIsServiceSheetOpen(true);}}onEdit={(service) => {setServiceToEdit(service);+ setServiceSheetStep(undefined);+ setIsServiceSheetOpen(true);+ }}+ onReauthorize={(service) => {+ setServiceToEdit(service);+ setServiceSheetStep(ServiceStep.Credential);setIsServiceSheetOpen(true);}}/>@@ -157,6 +166,7 @@ export const AgentVaultAccessBundleDetailPage = () => {onOpenChange={setIsServiceSheetOpen}accessBundleId={accessBundle.id}service={serviceToEdit}+ initialStep={serviceSheetStep}/><AccessBundleFormDialogdiff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsxindex 0f58e3d003..74e8f6c557 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx@@ -2,18 +2,26 @@ import { useMemo, useState } from "react";import { format } from "date-fns";import {ChevronDownIcon,+ GlobeIcon,+ KeyRoundIcon,MoreHorizontalIcon,PencilIcon,PlusIcon,SearchIcon,+ ServerIcon,TrashIcon} from "lucide-react";import { twMerge } from "tailwind-merge";-import { displayHostPattern } from "@app/components/agent-vault/service-sheet/serviceSchema";+import { OAuthStatusBadge } from "@app/components/agent-vault/service-sheet/OAuthAuthorizeCard";+import {+ displayHostPattern,+ SERVICE_TYPE_LABELS+} from "@app/components/agent-vault/service-sheet/serviceSchema";import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";import { createNotification } from "@app/components/notifications";import {+ Badge,Button,Card,CardAction,@@ -35,6 +43,11 @@ import {InputGroup,InputGroupAddon,InputGroupInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,Table,TableBody,TableCell,@@ -45,23 +58,37 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useDeleteAgentVaultService } from "@app/hooks/api/agentVault";+import {+ AgentVaultCredentialType,+ AgentVaultOAuthStatus,+ AgentVaultServiceType,+ useDeleteAgentVaultService+} from "@app/hooks/api/agentVault";import { TAgentVaultService } from "@app/hooks/api/agentVault/types";import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";enum SortColumn {Name = "name",- Hosts = "hosts",+ Type = "type",+ Target = "target",Created = "created"}+const ALL_TYPES = "all";++const serviceTypeOf = (service: TAgentVaultService) => service.type ?? AgentVaultServiceType.Http;++const targetOf = (service: TAgentVaultService) =>+ service.type === AgentVaultServiceType.Mcp ? service.config.serverUrl : service.hostPattern;+const SORT_COMPARATORS: Record<SortColumn,(a: TAgentVaultService, b: TAgentVaultService) => number> = {[SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),- [SortColumn.Hosts]: (a, b) => a.hostPattern.localeCompare(b.hostPattern),+ [SortColumn.Type]: (a, b) => serviceTypeOf(a).localeCompare(serviceTypeOf(b)),+ [SortColumn.Target]: (a, b) => targetOf(a).localeCompare(targetOf(b)),[SortColumn.Created]: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()};@@ -71,6 +98,7 @@ type Props = {canManage: boolean;onAdd: () => void;onEdit: (service: TAgentVaultService) => void;+ onReauthorize: (service: TAgentVaultService) => void;};// Two hosts is what the column fits comfortably; the rest go behind the count so the table keeps its@@ -94,8 +122,32 @@ const HostsCell = ({ hostPattern }: { hostPattern: string }) => {);};-export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdit }: Props) => {+const TypeBadge = ({ type }: { type: AgentVaultServiceType }) => (+ <Badge variant="outline">+ {type === AgentVaultServiceType.Mcp ? <ServerIcon /> : <GlobeIcon />}+ {SERVICE_TYPE_LABELS[type]}+ </Badge>+);++const TargetCell = ({ service }: { service: TAgentVaultService }) =>+ service.type === AgentVaultServiceType.Mcp ? (+ <span className="block max-w-72 truncate font-mono text-sm" title={service.config.serverUrl}>+ {service.config.serverUrl}+ </span>+ ) : (+ <HostsCell hostPattern={service.hostPattern} />+ );++export const ServicesCard = ({+ accessBundleId,+ services,+ canManage,+ onAdd,+ onEdit,+ onReauthorize+}: Props) => {const [search, setSearch] = useState("");+ const [typeFilter, setTypeFilter] = useState<AgentVaultServiceType | typeof ALL_TYPES>(ALL_TYPES);const [serviceToDelete, setServiceToDelete] = useState<TAgentVaultService | null>(null);const deleteService = useDeleteAgentVaultService();@@ -106,13 +158,15 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdiconst term = search.trim().toLowerCase();const filtered = services.filter((service) =>- service.name.toLowerCase().includes(term) ||- service.hostPattern.toLowerCase().includes(term)+ (typeFilter === ALL_TYPES || serviceTypeOf(service) === typeFilter) &&+ (service.name.toLowerCase().includes(term) ||+ service.hostPattern.toLowerCase().includes(term) ||+ targetOf(service).toLowerCase().includes(term)));const ordered = [...filtered].sort(SORT_COMPARATORS[sortColumn]);return sortDirection === "ascending" ? ordered : ordered.reverse();- }, [services, search, sortColumn, sortDirection]);+ }, [services, search, typeFilter, sortColumn, sortDirection]);const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {if (direction === "none") {@@ -157,8 +211,8 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi<DocumentationLinkBadge href={AgentVaultDocsUrls.services} /></CardTitle><CardDescription>- A service defines one API the agent can reach, the hosts the API answers on, and the- credential the proxy attaches to matching requests.+ A service defines one HTTP API or MCP server the agent can reach, and the credential the+ proxy attaches to its requests.</CardDescription>{canManage && (<CardAction>@@ -168,23 +222,36 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi</Button></CardAction>)}+ {services.length > 0 && (+ <div className="flex items-center gap-3 @xs:col-span-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ aria-label="Search services"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search services..."+ />+ </InputGroup>+ <Select+ value={typeFilter}+ onValueChange={(value) => setTypeFilter(value as typeof typeFilter)}+ >+ <SelectTrigger className="w-44" aria-label="Filter by type">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper" align="end">+ <SelectItem value={ALL_TYPES}>All Types</SelectItem>+ <SelectItem value={AgentVaultServiceType.Http}>HTTP APIs</SelectItem>+ <SelectItem value={AgentVaultServiceType.Mcp}>MCP Servers</SelectItem>+ </SelectContent>+ </Select>+ </div>+ )}</CardHeader>- {services.length > 0 && (- <CardContent>- <InputGroup>- <InputGroupAddon>- <SearchIcon />- </InputGroupAddon>- <InputGroupInput- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search services..."- />- </InputGroup>- </CardContent>- )}-{displayed.length === 0 ? (<CardContent><Empty className="border">@@ -195,7 +262,7 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi<EmptyDescription>{services.length === 0? "Add services to give this bundle access to external hosts."- : "Try a different search term."}+ : "Try a different search term or type."}</EmptyDescription></EmptyHeader></Empty>@@ -212,11 +279,18 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi<ChevronDownIcon className={sortIconClassName(SortColumn.Name)} /></TableHead><TableHead- sortDirection={sortColumn === SortColumn.Hosts ? sortDirection : "none"}- onSortChange={(direction) => handleSort(SortColumn.Hosts, direction)}+ sortDirection={sortColumn === SortColumn.Type ? sortDirection : "none"}+ onSortChange={(direction) => handleSort(SortColumn.Type, direction)}>- Hosts- <ChevronDownIcon className={sortIconClassName(SortColumn.Hosts)} />+ Type+ <ChevronDownIcon className={sortIconClassName(SortColumn.Type)} />+ </TableHead>+ <TableHead+ sortDirection={sortColumn === SortColumn.Target ? sortDirection : "none"}+ onSortChange={(direction) => handleSort(SortColumn.Target, direction)}+ >+ Target+ <ChevronDownIcon className={sortIconClassName(SortColumn.Target)} /></TableHead><TableHeadsortDirection={sortColumn === SortColumn.Created ? sortDirection : "none"}@@ -235,10 +309,17 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi<div className="flex items-center gap-2"><ServiceIcon hostPattern={service.hostPattern} />{service.name}+ {service.credential.type === AgentVaultCredentialType.OAuth &&+ service.credential.status !== AgentVaultOAuthStatus.Connected && (+ <OAuthStatusBadge status={service.credential.status} />+ )}</div></TableCell><TableCell>- <HostsCell hostPattern={service.hostPattern} />+ <TypeBadge type={serviceTypeOf(service)} />+ </TableCell>+ <TableCell>+ <TargetCell service={service} /></TableCell><TableCell><Tooltip>@@ -265,6 +346,12 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi<PencilIcon />Edit</DropdownMenuItem>+ {service.credential.type === AgentVaultCredentialType.OAuth && (+ <DropdownMenuItem onClick={() => onReauthorize(service)}>+ <KeyRoundIcon />+ Reauthorize+ </DropdownMenuItem>+ )}<DropdownMenuItemvariant="danger"onClick={() => setServiceToDelete(service)}diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsxnew file mode 100644index 0000000000..09b574c6f0--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx@@ -0,0 +1,119 @@+import { useEffect, useRef, useState } from "react";+import { Helmet } from "react-helmet";+import { useSearch } from "@tanstack/react-router";+import axios from "axios";++import { AuthPageLayout } from "@app/components/auth/AuthPageLayout";+import { AuthPagePanel } from "@app/components/auth/AuthPagePanel";+import { Button, CardContent, CardDescription, CardHeader, CardTitle } from "@app/components/v3";+import {+ AgentVaultOAuthAuthorizationStatus,+ useCompleteAgentVaultOAuthAuthorization+} from "@app/hooks/api/agentVault";++const CLOSE_AFTER_SUCCESS_MS = 1000;+const CLOSE_AFTER_FAILURE_MS = 4000;++type TOutcome =+ | { status: "working" }+ | { status: "authorized" }+ | { status: "failed"; message: string };++const failureMessage = (error: unknown) => {+ if (axios.isAxiosError<{ message?: unknown }>(error)) {+ if (error.response?.status === 404) {+ return "This authorization expired or was started by another user. Close this window and select Authorize again.";+ }+ const message = error.response?.data?.message;+ if (typeof message === "string") return message;+ }+ return "Couldn't finish the authorization. Close this window and select Authorize again.";+};++export const AgentVaultOAuthCallbackPage = () => {+ const search = useSearch({ from: "/_authenticate/agent-vault/oauth/callback" });+ const completeAuthorization = useCompleteAgentVaultOAuthAuthorization();+ const [outcome, setOutcome] = useState<TOutcome>({ status: "working" });+ const hasStarted = useRef(false);++ useEffect(() => {+ if (hasStarted.current) return;+ hasStarted.current = true;++ const { state, code, iss, error, error_description: errorDescription } = search;+ const authorizationId = state?.split(".")[0];+ if (!state || !authorizationId) {+ setOutcome({+ status: "failed",+ message:+ "This page is missing the authorization details. Close this window and select Authorize again."+ });+ return;+ }++ completeAuthorization+ .mutateAsync({ authorizationId, state, code, iss, error, errorDescription })+ .then((authorization) => {+ if (authorization.status === AgentVaultOAuthAuthorizationStatus.Authorized) {+ setOutcome({ status: "authorized" });+ return;+ }+ setOutcome({+ status: "failed",+ message: authorization.error ?? "The server refused the authorization."+ });+ })+ .catch((err: unknown) => setOutcome({ status: "failed", message: failureMessage(err) }));+ // Runs once: completing twice would exchange the same code twice.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ if (outcome.status === "working") return undefined;+ const id = window.setTimeout(+ () => window.close(),+ outcome.status === "authorized" ? CLOSE_AFTER_SUCCESS_MS : CLOSE_AFTER_FAILURE_MS+ );+ return () => window.clearTimeout(id);+ }, [outcome.status]);++ let title = "Finishing Authorization";+ let description = "Confirming the authorization with Infisical.";+ if (outcome.status === "authorized") {+ title = "Authorization Complete";+ description =+ "This window closes on its own. Return to Infisical to finish adding the service.";+ } else if (outcome.status === "failed") {+ title = "Authorization Failed";+ description = outcome.message;+ }++ return (+ <AuthPageLayout variant="focused" showFooter={false}>+ <Helmet>+ <title>Agent Vault Authorization</title>+ </Helmet>+ <AuthPagePanel>+ <CardHeader className="mb-6 gap-2">+ <CardTitle+ className={+ outcome.status === "failed"+ ? "font-alliance text-2xl font-normal text-danger"+ : "font-alliance text-2xl font-normal"+ }+ >+ {title}+ </CardTitle>+ <CardDescription className="text-base">{description}</CardDescription>+ </CardHeader>+ {outcome.status !== "working" && (+ <CardContent>+ <Button type="button" variant="outline" onClick={() => window.close()}>+ Close Window+ </Button>+ </CardContent>+ )}+ </AuthPagePanel>+ </AuthPageLayout>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.ts b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.tsnew file mode 100644index 0000000000..66af92dbfd--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";++import { AgentVaultOAuthCallbackQueryParamsSchema } from "./callbackSchema";++describe("OAuth callback input", () => {+ it("keeps the UUID state and bounded values from a valid provider redirect", () => {+ const params = {+ state: "11111111-1111-4111-8111-111111111111.random-state",+ code: "code",+ iss: "https://provider.example.com"+ };+ expect(AgentVaultOAuthCallbackQueryParamsSchema.parse(params)).toEqual(params);+ });++ it.each([+ "../../projects.state",+ "../access-bundles?x=1.state",+ "not-a-uuid.state",+ "",+ "x".repeat(257)+ ])("drops a state that could select another API path: %s", (state) => {+ expect(AgentVaultOAuthCallbackQueryParamsSchema.parse({ state }).state).toBeUndefined();+ });++ it("drops provider fields exceeding the API's bounds", () => {+ const parsed = AgentVaultOAuthCallbackQueryParamsSchema.parse({+ code: "x".repeat(4097),+ iss: "x".repeat(2049),+ error: "x".repeat(1025),+ error_description: "x".repeat(4097)+ });+ expect(Object.values(parsed).every((value) => value === undefined)).toBe(true);+ });+});diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.ts b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.tsnew file mode 100644index 0000000000..36e844d836--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.ts@@ -0,0 +1,18 @@+import { z } from "zod";++const authorizationIdSchema = z.string().uuid();++export const AgentVaultOAuthCallbackQueryParamsSchema = z.object({+ code: z.string().max(4096).optional().catch(undefined),+ // The ID becomes an API path segment. Reject malformed state before the callback can submit a request.+ state: z+ .string()+ .min(1)+ .max(256)+ .refine((state) => authorizationIdSchema.safeParse(state.split(".")[0]).success)+ .optional()+ .catch(undefined),+ iss: z.string().max(2048).optional().catch(undefined),+ error: z.string().max(1024).optional().catch(undefined),+ error_description: z.string().max(4096).optional().catch(undefined)+});diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsxnew file mode 100644index 0000000000..de9221e2d4--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsx@@ -0,0 +1,10 @@+import { createFileRoute } from "@tanstack/react-router";+import { zodValidator } from "@tanstack/zod-adapter";++import { AgentVaultOAuthCallbackPage } from "./AgentVaultOAuthCallbackPage";+import { AgentVaultOAuthCallbackQueryParamsSchema } from "./callbackSchema";++export const Route = createFileRoute("/_authenticate/agent-vault/oauth/callback")({+ component: AgentVaultOAuthCallbackPage,+ validateSearch: zodValidator(AgentVaultOAuthCallbackQueryParamsSchema)+});diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsxindex b7ba4a3213..29c397366f 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx@@ -7,6 +7,7 @@ import {KeyRoundIcon,type LucideIcon,PlusIcon,+ ServerIcon,ShieldBanIcon} from "lucide-react";import { twMerge } from "tailwind-merge";@@ -21,10 +22,13 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { AgentVaultSessionLogDecision } from "@app/hooks/api/agentVault";-import { TAgentVaultSessionLogRecord } from "@app/hooks/api/agentVault/types";+import { AgentVaultServiceType, AgentVaultSessionLogDecision } from "@app/hooks/api/agentVault";+import {+ TAgentVaultSessionLogMcpCall,+ TAgentVaultSessionLogRecord+} from "@app/hooks/api/agentVault/types";-import { httpStatusLabel } from "./SessionLogsPanel.utils";+import { httpStatusLabel, mcpCallLabel, sessionLogMcpCalls } from "./SessionLogsPanel.utils";const ARRIVAL_HOLD_MS = 1200;@@ -95,6 +99,64 @@ export const hostPatternFor = (record: TAgentVaultSessionLogRecord) => {return record.port === "443" ? host : `${host}:${record.port}`;};+const PathDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => (+ <span className="block truncate" title={record.path}>+ {record.path}+ </span>+);++const McpCallText = ({ call }: { call: TAgentVaultSessionLogMcpCall }) =>+ call.tool ? (+ <>+ <span className="truncate font-mono text-foreground">{call.tool}</span>+ <span className="shrink-0 font-mono text-xs text-muted">{call.method}</span>+ </>+ ) : (+ <span className="truncate font-mono text-xs text-muted">{call.method}</span>+ );++const McpDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => {+ const [first, ...rest] = sessionLogMcpCalls(record);++ return (+ <span className="flex min-w-0 items-center gap-1.5">+ <Badge variant="info">+ <ServerIcon />+ MCP+ </Badge>+ {first ? (+ <span className="flex min-w-0 items-baseline gap-1.5" title={record.path}>+ <McpCallText call={first} />+ </span>+ ) : (+ <span className="min-w-0 truncate text-muted" title={record.path}>+ {record.path}+ </span>+ )}+ {rest.length > 0 && (+ <Tooltip>+ <TooltipTrigger className="shrink-0 text-xs text-muted">+{rest.length}</TooltipTrigger>+ <TooltipContent>+ <div className="flex flex-col font-mono text-xs">+ {rest.map((call, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <span key={index}>{mcpCallLabel(call)}</span>+ ))}+ </div>+ </TooltipContent>+ </Tooltip>+ )}+ </span>+ );+};++const RequestDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) =>+ record.serviceType === AgentVaultServiceType.Mcp ? (+ <McpDetail record={record} />+ ) : (+ <PathDetail record={record} />+ );+type Props = {record: TAgentVaultSessionLogRecord;arrivedAt?: number;@@ -162,9 +224,7 @@ export const SessionLogRow = ({ record, arrivedAt, accessBundleName, onAddServic)}</TableCell><TableCell>- <span className="block truncate" title={record.path}>- {record.path}- </span>+ <RequestDetail record={record} /></TableCell><TableCell className="font-mono text-xs">{!proxyAnswered && record.status ? (diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsxindex fb6772f5f5..213c4fffb3 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx@@ -36,6 +36,7 @@ import {import { useOrganization, useProjectPermission, useSubscription } from "@app/context";import {AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,+ AgentVaultServiceType,AgentVaultSessionLogDecision,getSessionLogStorageError,sessionLogRecordKey,@@ -55,7 +56,9 @@ import {chunkIdTime,groupSessionLogGaps,matchesSessionLogSearch,- sessionLogSearchTerm+ matchesSessionLogType,+ sessionLogSearchTerm,+ SessionLogTypeFilter} from "./SessionLogsPanel.utils";import { useNewRequestsCounter } from "./useNewRequestsCounter";import { useSessionLogsLiveTail } from "./useSessionLogsLiveTail";@@ -115,6 +118,7 @@ export const SessionLogsPanel = ({ session }: Props) => {const [search, setSearch] = useState("");const [decisionFilter, setDecisionFilter] = useState<DecisionFilter>("all");+ const [typeFilter, setTypeFilter] = useState<SessionLogTypeFilter>("all");const { range, applyRange, isActive, canTail, isLive, isPausedForBudget, pauseForBudget } =useSessionLogsLiveTail(session);const { history, live, arrived, isLiveGapUnfilled } = useGetAgentVaultSessionLogs(session.id, {@@ -189,12 +193,14 @@ export const SessionLogsPanel = ({ session }: Props) => {() =>records.filter((record) => {if (decisionFilter !== "all" && record.decision !== decisionFilter) return false;+ if (!matchesSessionLogType(record, typeFilter)) return false;return matchesSessionLogSearch(record, search);}),- [records, search, decisionFilter]+ [records, search, decisionFilter, typeFilter]);- const hasBrowserFilter = Boolean(sessionLogSearchTerm(search)) || decisionFilter !== "all";+ const hasBrowserFilter =+ Boolean(sessionLogSearchTerm(search)) || decisionFilter !== "all" || typeFilter !== "all";const isFiltered = hasBrowserFilter || Boolean(range);// Counted once opened: a chunk's request count isn't known until it is decrypted.@@ -224,6 +230,7 @@ export const SessionLogsPanel = ({ session }: Props) => {const filterKey = [sessionLogSearchTerm(search),decisionFilter,+ typeFilter,range?.startDate.getTime(),range?.endDate.getTime()].join("|");@@ -349,7 +356,7 @@ export const SessionLogsPanel = ({ session }: Props) => {)} and ${format(range.endDate, "MMM d, yyyy HH:mm")}.`;} else if (isFiltered) {noRecordsTitle = "No requests match these filters";- noRecordsDescription = "Try a different search term, outcome or time range.";+ noRecordsDescription = "Try a different search term, type, outcome or time range.";} else if (liveState === "live") {noRecordsLiveState = liveState;noRecordsTitle = "Waiting for requests";@@ -495,7 +502,7 @@ export const SessionLogsPanel = ({ session }: Props) => {<InputGroupInputvalue={search}onChange={(event) => setSearch(event.target.value)}- placeholder="Search host, path, method or service..."+ placeholder="Search host, path, method, tool or service..."/>{search && (<InputGroupAddon align="inline-end">@@ -511,6 +518,19 @@ export const SessionLogsPanel = ({ session }: Props) => {)}</InputGroup></div>+ <Select+ value={typeFilter}+ onValueChange={(value) => setTypeFilter(value as SessionLogTypeFilter)}+ >+ <SelectTrigger aria-label="Filter by type">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value="all">All Types</SelectItem>+ <SelectItem value={AgentVaultServiceType.Http}>HTTP APIs</SelectItem>+ <SelectItem value={AgentVaultServiceType.Mcp}>MCP Servers</SelectItem>+ </SelectContent>+ </Select><Selectvalue={decisionFilter}onValueChange={(value) => setDecisionFilter(value as DecisionFilter)}@@ -658,7 +678,7 @@ export const SessionLogsPanel = ({ session }: Props) => {<TableHead className="w-48">Time</TableHead><TableHead className="w-24">Method</TableHead><TableHead>Host</TableHead>- <TableHead>Path</TableHead>+ <TableHead>Request</TableHead><TableHead className="w-24">Upstream</TableHead><TableHead className="w-36">Outcome</TableHead><TableHead variant="action" className={canAddService ? "w-36" : "w-12"} />diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.tsindex bda1ec1102..32fbe4ac85 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts@@ -1,14 +1,20 @@import assert from "node:assert/strict";import { describe, it } from "vitest";-import { AgentVaultSessionLogDecision } from "@app/hooks/api/agentVault/enums";+import {+ AgentVaultServiceType,+ AgentVaultSessionLogDecision+} from "@app/hooks/api/agentVault/enums";import { TAgentVaultSessionLogRecord } from "@app/hooks/api/agentVault/types";import {chunkIdTime,findRowShift,groupSessionLogGaps,- matchesSessionLogSearch+ matchesSessionLogSearch,+ matchesSessionLogType,+ mcpCallLabel,+ sessionLogMcpCalls} from "./SessionLogsPanel.utils";const record = (seq: number): TAgentVaultSessionLogRecord => ({@@ -105,4 +111,105 @@ describe("matchesSessionLogSearch", () => {it("does not match a path on a different host", () => {assert.equal(matchesSessionLogSearch(repoRequest, "gitlab.com/repos"), false);});++ const mcpRequest: TAgentVaultSessionLogRecord = {+ ...record(2),+ method: "POST",+ host: "mcp.notion.com",+ path: "/mcp",+ serviceType: AgentVaultServiceType.Mcp,+ mcp: {+ parsed: true,+ calls: [{ method: "tools/call", tool: "notion-get-self" }, { method: "tools/list" }]+ }+ };++ it("matches an MCP tool name", () => {+ assert.equal(matchesSessionLogSearch(mcpRequest, "Notion-Get"), true);+ });++ it("matches the JSON-RPC method of a tool call and of other calls", () => {+ assert.equal(matchesSessionLogSearch(mcpRequest, "tools/call"), true);+ assert.equal(matchesSessionLogSearch(mcpRequest, "tools/list"), true);+ assert.equal(matchesSessionLogSearch(mcpRequest, "resources/list"), false);+ });+});++describe("matchesSessionLogType", () => {+ const http = { ...record(1), serviceType: AgentVaultServiceType.Http };+ const mcp = { ...record(2), serviceType: AgentVaultServiceType.Mcp };+ const untyped = { ...record(3), serviceType: null };+ const legacy = record(4);++ it("keeps every record for all types", () => {+ [http, mcp, untyped, legacy].forEach((entry) =>+ assert.equal(matchesSessionLogType(entry, "all"), true)+ );+ });++ it("keeps only records of the chosen type", () => {+ assert.deepEqual(+ [http, mcp, untyped, legacy].map((entry) =>+ matchesSessionLogType(entry, AgentVaultServiceType.Http)+ ),+ [true, false, false, false]+ );+ assert.deepEqual(+ [http, mcp, untyped, legacy].map((entry) =>+ matchesSessionLogType(entry, AgentVaultServiceType.Mcp)+ ),+ [false, true, false, false]+ );+ });+});++describe("sessionLogMcpCalls", () => {+ const calls = [{ method: "tools/call", tool: "search" }, { method: "initialize" }];++ it("returns the parsed calls of an MCP record", () => {+ assert.deepEqual(+ sessionLogMcpCalls({+ ...record(1),+ serviceType: AgentVaultServiceType.Mcp,+ mcp: { parsed: true, calls }+ }),+ calls+ );+ });++ it("returns nothing for an unparsed body, a missing detail or an HTTP record", () => {+ assert.deepEqual(+ sessionLogMcpCalls({+ ...record(1),+ serviceType: AgentVaultServiceType.Mcp,+ mcp: { parsed: false, calls }+ }),+ []+ );+ assert.deepEqual(+ sessionLogMcpCalls({ ...record(1), serviceType: AgentVaultServiceType.Mcp }),+ []+ );+ assert.deepEqual(+ sessionLogMcpCalls({+ ...record(1),+ serviceType: AgentVaultServiceType.Http,+ mcp: { parsed: true, calls }+ }),+ []+ );+ });+});++describe("mcpCallLabel", () => {+ it("leads with the tool name of a tool call", () => {+ assert.equal(mcpCallLabel({ method: "tools/call", tool: "search" }), "search (tools/call)");+ });++ it("shows the method of any other call", () => {+ assert.equal(+ mcpCallLabel({ method: "notifications/initialized", tool: null }),+ "notifications/initialized"+ );+ });});diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.tsindex 51094a819c..d14869960d 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts@@ -1,7 +1,8 @@-import { sessionLogRecordKey } from "@app/hooks/api/agentVault";+import { AgentVaultServiceType, sessionLogRecordKey } from "@app/hooks/api/agentVault";import {TAgentVaultSessionLogGap,TAgentVaultSessionLogGapReason,+ TAgentVaultSessionLogMcpCall,TAgentVaultSessionLogRecord} from "@app/hooks/api/agentVault/types";@@ -114,7 +115,28 @@ export const matchesSessionLogSearch = (record: TAgentVaultSessionLogRecord, seapath,record.method.toLowerCase(),(record.service ?? "").toLowerCase(),+ ...(record.mcp?.calls ?? []).flatMap((call) =>+ [call.method, call.tool ?? ""].map((field) => field.toLowerCase())+ ),`${host}${path}`,`${host}:${record.port}${path}`].some((field) => field.includes(term));};++export type SessionLogTypeFilter = "all" | AgentVaultServiceType;++// Passthrough and blocked requests matched no service, so they have no type to filter on.+export const matchesSessionLogType = (+ record: TAgentVaultSessionLogRecord,+ filter: SessionLogTypeFilter+) => filter === "all" || record.serviceType === filter;++export const sessionLogMcpCalls = (+ record: TAgentVaultSessionLogRecord+): TAgentVaultSessionLogMcpCall[] => {+ if (record.serviceType !== AgentVaultServiceType.Mcp || !record.mcp?.parsed) return [];+ return record.mcp.calls;+};++export const mcpCallLabel = (call: TAgentVaultSessionLogMcpCall) =>+ call.tool ? `${call.tool} (${call.method})` : call.method;diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex 1f0eef6c46..cf465db840 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -46,6 +46,7 @@ import { Route as authLoginPageRouteImport } from './pages/auth/LoginPage/route'import { Route as redirectsPamAccessRedirectImport } from './pages/redirects/pam-access-redirect'import { Route as adminLayoutImport } from './pages/admin/layout'import { Route as authProviderErrorPageRouteImport } from './pages/auth/ProviderErrorPage/route'+import { Route as agentVaultAgentVaultOAuthCallbackPageRouteImport } from './pages/agent-vault/AgentVaultOAuthCallbackPage/route'import { Route as adminWelcomePageRouteImport } from './pages/admin/WelcomePage/route'import { Route as adminSetupPageRouteImport } from './pages/admin/SetupPage/route'import { Route as userPersonalSettingsPageRouteImport } from './pages/user/PersonalSettingsPage/route'@@ -667,6 +668,13 @@ const authProviderErrorPageRouteRoute = authProviderErrorPageRouteImport.update(} as any,)+const agentVaultAgentVaultOAuthCallbackPageRouteRoute =+ agentVaultAgentVaultOAuthCallbackPageRouteImport.update({+ id: '/agent-vault/oauth/callback',+ path: '/agent-vault/oauth/callback',+ getParentRoute: () => middlewaresAuthenticateRoute,+ } as any)+const adminWelcomePageRouteRoute = adminWelcomePageRouteImport.update({id: '/welcome',path: '/welcome',@@ -2976,6 +2984,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof adminWelcomePageRouteImportparentRoute: typeof AuthenticateInjectOrgDetailsAdminImport}+ '/_authenticate/agent-vault/oauth/callback': {+ id: '/_authenticate/agent-vault/oauth/callback'+ path: '/agent-vault/oauth/callback'+ fullPath: '/agent-vault/oauth/callback'+ preLoaderRoute: typeof agentVaultAgentVaultOAuthCallbackPageRouteImport+ parentRoute: typeof middlewaresAuthenticateImport+ }'/_restrict-login-signup/login/provider/error': {id: '/_restrict-login-signup/login/provider/error'path: '/provider/error'@@ -6103,6 +6118,7 @@ interface middlewaresAuthenticateRouteChildren {organizationOauthConsentPageRouteRoute: typeof organizationOauthConsentPageRouteRouteorganizationNoOrgPageRouteRoute: typeof organizationNoOrgPageRouteRouteorganizationSignupOnboardingPageRouteRoute: typeof organizationSignupOnboardingPageRouteRoute+ agentVaultAgentVaultOAuthCallbackPageRouteRoute: typeof agentVaultAgentVaultOAuthCallbackPageRouteRoute}const middlewaresAuthenticateRouteChildren: middlewaresAuthenticateRouteChildren =@@ -6118,6 +6134,8 @@ const middlewaresAuthenticateRouteChildren: middlewaresAuthenticateRouteChildrenorganizationNoOrgPageRouteRoute: organizationNoOrgPageRouteRoute,organizationSignupOnboardingPageRouteRoute:organizationSignupOnboardingPageRouteRoute,+ agentVaultAgentVaultOAuthCallbackPageRouteRoute:+ agentVaultAgentVaultOAuthCallbackPageRouteRoute,}const middlewaresAuthenticateRouteWithChildren =@@ -6231,6 +6249,7 @@ export interface FileRoutesByFullPath {'/personal-settings/': typeof userPersonalSettingsPageRouteRoute'/admin/setup': typeof adminSetupPageRouteRoute'/admin/welcome': typeof adminWelcomePageRouteRoute+ '/agent-vault/oauth/callback': typeof agentVaultAgentVaultOAuthCallbackPageRouteRoute'/login/provider/error': typeof authProviderErrorPageRouteRoute'/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutIntegrationsRouteWithChildren'/pam/access': typeof redirectsPamAccessRedirectRoute@@ -6522,6 +6541,7 @@ export interface FileRoutesByTo {'/admin': typeof adminGeneralPageRouteRoute'/admin/setup': typeof adminSetupPageRouteRoute'/admin/welcome': typeof adminWelcomePageRouteRoute+ '/agent-vault/oauth/callback': typeof agentVaultAgentVaultOAuthCallbackPageRouteRoute'/login/provider/error': typeof authProviderErrorPageRouteRoute'/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutIntegrationsRouteWithChildren'/pam/access': typeof redirectsPamAccessRedirectRoute@@ -6796,6 +6816,7 @@ export interface FileRoutesById {'/_authenticate/personal-settings/_layout/': typeof userPersonalSettingsPageRouteRoute'/_authenticate/_inject-org-details/admin/setup': typeof adminSetupPageRouteRoute'/_authenticate/_inject-org-details/admin/welcome': typeof adminWelcomePageRouteRoute+ '/_authenticate/agent-vault/oauth/callback': typeof agentVaultAgentVaultOAuthCallbackPageRouteRoute'/_restrict-login-signup/login/provider/error': typeof authProviderErrorPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutIntegrationsRouteWithChildren'/_authenticate/_inject-org-details/admin/_admin-layout': typeof adminLayoutRouteWithChildren@@ -7099,6 +7120,7 @@ export interface FileRouteTypes {| '/personal-settings/'| '/admin/setup'| '/admin/welcome'+ | '/agent-vault/oauth/callback'| '/login/provider/error'| '/integrations'| '/pam/access'@@ -7389,6 +7411,7 @@ export interface FileRouteTypes {| '/admin'| '/admin/setup'| '/admin/welcome'+ | '/agent-vault/oauth/callback'| '/login/provider/error'| '/integrations'| '/pam/access'@@ -7661,6 +7684,7 @@ export interface FileRouteTypes {| '/_authenticate/personal-settings/_layout/'| '/_authenticate/_inject-org-details/admin/setup'| '/_authenticate/_inject-org-details/admin/welcome'+ | '/_authenticate/agent-vault/oauth/callback'| '/_restrict-login-signup/login/provider/error'| '/_authenticate/_inject-org-details/_org-layout/integrations'| '/_authenticate/_inject-org-details/admin/_admin-layout'@@ -7989,7 +8013,8 @@ export const routeTree = rootRoute"/_authenticate/mfa-session/$mfaSessionId","/_authenticate/organization/oauth-consent","/_authenticate/organizations/none",- "/_authenticate/organizations/onboarding"+ "/_authenticate/organizations/onboarding",+ "/_authenticate/agent-vault/oauth/callback"]},"/_restrict-login-signup": {@@ -8170,6 +8195,10 @@ export const routeTree = rootRoute"filePath": "admin/WelcomePage/route.tsx","parent": "/_authenticate/_inject-org-details/admin"},+ "/_authenticate/agent-vault/oauth/callback": {+ "filePath": "agent-vault/AgentVaultOAuthCallbackPage/route.tsx",+ "parent": "/_authenticate"+ },"/_restrict-login-signup/login/provider/error": {"filePath": "auth/ProviderErrorPage/route.tsx","parent": "/_restrict-login-signup/login"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 2827c06042..2f4a4603df 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -491,6 +491,7 @@ export const routes = rootRoute("root.tsx", [middleware("authenticate.tsx", [route("/password-setup", "auth/PasswordSetupPage/route.tsx"),route("/mfa-session/$mfaSessionId", "MfaSessionPage/route.tsx"),+ route("/agent-vault/oauth/callback", "agent-vault/AgentVaultOAuthCallbackPage/route.tsx"),route("/personal-settings", [layout("user/layout.tsx", [index("user/PersonalSettingsPage/route.tsx")])]),