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
misc: addressed more feedback
Sheen Capadngan7f508d109241
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.tsindex dee823b132..b6a5f790a9 100644--- 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.ts@@ -63,6 +63,7 @@ export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider)response: {200: z.object({registrationRequired: z.boolean().describe(AGENT_VAULT.OAUTH.registrationRequired),+ oauthAdvertised: z.boolean().describe(AGENT_VAULT.OAUTH.oauthAdvertised),redirectUri: z.string().describe(AGENT_VAULT.OAUTH.redirectUri),registrationError: z.string().nullable().describe(AGENT_VAULT.OAUTH.registrationError),authorization: zdiff --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 fb7c22a2ca..e954a1247c 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@@ -6,6 +6,7 @@ import { DatabaseError } from "@app/lib/errors";import { ormify } from "@app/lib/knex";import { AgentVaultCredentialType, AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";+import { MAX_OAUTH_SCOPES } from "../agent-vault-oauth/agent-vault-oauth-discovery-fns";export type TAgentVaultServiceDALFactory = ReturnType<typeof agentVaultServiceDALFactory>;@@ -85,6 +86,8 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {// The union is taken in the UPDATE, against the row being written: two reports for the same token both pass a// compare on the sealed credential, so a union computed from what each one read would let the last erase the other.+ // Servers usually list every scope a call needs, so scopes already granted are skipped, and a report naming only+ // those writes nothing. The list stops growing at MAX_OAUTH_SCOPES, since this row is read on every resolve.const addRequiredScopes = async ({id,@@ -96,14 +99,20 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {): Promise<Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined> => {try {const stored = `COALESCE("credentialConfig"->'requiredScopes', '[]'::jsonb)`;+ const granted = `COALESCE("credentialConfig"->'grantedScopes', '[]'::jsonb)`;+ const reported = JSON.stringify([...new Set(requiredScopes)]);const [row] = await (tx || db)(TableName.AgentVaultService).where({ id, encryptedCredential: expectedEncryptedCredential, credentialType: AgentVaultCredentialType.OAuth }).whereRaw(`"credentialConfig"->>'accessTokenHash' = ?`, [rejectedTokenHash]).whereRaw(`"credentialConfig"->>'status' IS DISTINCT FROM ?`, [AgentVaultOauthStatus.NeedsReauthorization])+ .whereRaw(+ `EXISTS (SELECT 1 FROM jsonb_array_elements_text(?::jsonb) AS reported(scope) WHERE NOT ${granted} @> jsonb_build_array(reported.scope))`,+ [reported]+ ).update({credentialConfig: db.raw(- `COALESCE("credentialConfig", '{}'::jsonb) || jsonb_build_object('status', ?::text, 'requiredScopes', ${stored} || COALESCE((SELECT jsonb_agg(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)])]+ `COALESCE("credentialConfig", '{}'::jsonb) || jsonb_build_object('status', ?::text, 'requiredScopes', ${stored} || COALESCE((SELECT jsonb_agg(added.scope ORDER BY added.ord) FROM (SELECT reported.scope, reported.ord, row_number() OVER (ORDER BY reported.ord) AS position FROM jsonb_array_elements_text(?::jsonb) WITH ORDINALITY AS reported(scope, ord) WHERE NOT ${stored} @> jsonb_build_array(reported.scope) AND NOT ${granted} @> jsonb_build_array(reported.scope)) AS added WHERE added.position <= ?::int - jsonb_array_length(${stored})), '[]'::jsonb))`,+ [AgentVaultOauthStatus.NeedsAdditionalScopes, reported, MAX_OAUTH_SCOPES])}).returning(["id", "hostPattern", "config", "credentialConfig"]);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.tsindex 23de4e2f40..5d52fd562a 100644--- 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.ts@@ -38,7 +38,7 @@ const SUPPORTED_AUTH_METHODS = Object.values(AgentVaultOauthClientAuthMethod) as// 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]+$/);-export const MAX_CLIENT_ID_LENGTH = 512;+export const MAX_CLIENT_ID_LENGTH = 2048;export const MAX_CLIENT_SECRET_LENGTH = 4096;const parseRegistration = (body: string): TOauthClient | null => {@@ -78,8 +78,9 @@ const parseRegistration = (body: string): TOauthClient | null => {};};-// 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.+// RFC 7591. Servers must ignore metadata fields they don't understand, so the only one a strict server can refuse+// is `application_type` (an OIDC registration value); a refusal is retried once without it. `grant_types` stays,+// or a strict server registers authorization_code only and every refresh fails with unauthorized_client.export const registerOauthClient = async ({http,serverUrl,@@ -94,14 +95,11 @@ export const registerOauthClient = async ({const minimal = {client_name: AGENT_VAULT_OAUTH_CLIENT_NAME,redirect_uris: [redirectUri],- token_endpoint_auth_method: AgentVaultOauthClientAuthMethod.None- };- const full = {- ...minimal,- application_type: "web",+ token_endpoint_auth_method: AgentVaultOauthClientAuthMethod.None,grant_types: [AGENT_VAULT_OAUTH_GRANT_TYPE, "refresh_token"],response_types: ["code"]};+ const full = { ...minimal, application_type: "web" };let lastStatus: number | null = null;let lastReason = "";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.tsindex 53fbd48d1c..3c312e314b 100644--- 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.ts@@ -6,6 +6,7 @@ import {checkProtectedResource,discoverOauthServer,isOauthScopeToken,+ MAX_OAUTH_SCOPES,parseBearerChallenge,protectedResourceMetadataUrls,selectScopes@@ -23,18 +24,28 @@ vi.mock("@app/lib/logger", async () => ({type TStubServer = {challenge?: string | null;probeThrows?: boolean;+ getThrows?: boolean;+ // Requests that never answer, as a hung server's would.+ hang?: boolean;json: Record<string, unknown>;};-const stubHttp = ({ challenge = null, probeThrows = false, json }: TStubServer) => {+const stubHttp = ({ challenge = null, probeThrows = false, getThrows = false, hang = false, json }: TStubServer) => {const fetched: string[] = [];+ const never = () =>+ new Promise<never>(() => {+ /* never settles */+ });const http: TOauthHttpClient = {probe: async () => {+ if (hang) return never();if (probeThrows) throw new Error("connect ECONNREFUSED");return { status: 401, wwwAuthenticate: challenge };},get: async (url) => {fetched.push(url);+ if (hang) return never();+ if (getThrows) throw new Error("getaddrinfo ENOTFOUND");return url in json? { status: 200, contentType: "application/json", body: JSON.stringify(json[url]) }: { status: 404, contentType: "text/plain", body: "not found" };@@ -259,11 +270,15 @@ describe("discovering an MCP server's authorization server", () => {scopes: ["read", "write"],issParameterSupported: true,tokenEndpointAuthMethodsSupported: ["client_secret_basic", "client_secret_post", "none"],- compatibility: []+ compatibility: [],+ oauthAdvertised: true});+ // Each group is asked at once; the challenge's URL is one of the well-known ones, so it isn't asked twice.expect(fetched).toEqual(["https://mcp.linear.app/.well-known/oauth-protected-resource/mcp",- "https://mcp.linear.app/.well-known/oauth-authorization-server"+ "https://mcp.linear.app/.well-known/oauth-protected-resource",+ "https://mcp.linear.app/.well-known/oauth-authorization-server",+ "https://mcp.linear.app/.well-known/openid-configuration"]);});@@ -292,7 +307,7 @@ describe("discovering an MCP server's authorization server", () => {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");+ expect(fetched).toContain("https://github.com/.well-known/oauth-authorization-server/login/oauth");});test("without a challenge, the well-known locations are tried in order", async () => {@@ -423,10 +438,80 @@ describe("discovering an MCP server's authorization server", () => {}});const discovery = await discoverOauthServer(unadvertised.http, "https://mcp.example.com/mcp");- expect(omitted).toBeDefined();expect(discovery.compatibility).toContain(AgentVaultOauthCompatibility.PkceUnadvertised);});+ test("a challenge URL that answers wins over a well-known URL that also does", async () => {+ const { http, fetched } = stubHttp({+ challenge: 'Bearer resource_metadata="https://meta.example.com/prm"',+ json: {+ "https://meta.example.com/prm": {+ resource: "https://mcp.example.com/mcp",+ authorization_servers: ["https://auth-from-challenge.example.com"]+ },+ "https://mcp.example.com/.well-known/oauth-protected-resource/mcp": {+ resource: "https://mcp.example.com/mcp",+ authorization_servers: ["https://auth-well-known.example.com"]+ },+ "https://auth-from-challenge.example.com/.well-known/oauth-authorization-server": {+ ...LINEAR_AS,+ issuer: "https://auth-from-challenge.example.com"+ },+ "https://auth-from-challenge.example.com/.well-known/openid-configuration": {+ ...LINEAR_AS,+ issuer: "https://auth-from-challenge.example.com",+ authorization_endpoint: "https://auth-from-challenge.example.com/second"+ }+ }+ });++ const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");+ expect(discovery.issuer).toBe("https://auth-from-challenge.example.com");+ expect(discovery.authorizationEndpoint).toBe(LINEAR_AS.authorization_endpoint);+ expect(fetched).toContain("https://meta.example.com/prm");+ });++ test("a server where nothing answers is unreachable, so the URL is what to check", async () => {+ const { http } = stubHttp({ probeThrows: true, getThrows: true, json: {} });+ await expect(discoverOauthServer(http, "https://mcp.typo.example.com/mcp")).rejects.toThrow(+ "Couldn't reach 'mcp.typo.example.com'. Check the server URL and that the server is online."+ );+ });++ test("a server that answers without any OAuth signal is not advertised, but still gets guessed endpoints", async () => {+ const { http } = stubHttp({ challenge: null, json: {} });+ const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");+ expect(discovery.oauthAdvertised).toBe(false);+ expect(discovery.endpointsGuessed).toBe(true);+ });++ test("a Bearer challenge alone counts as advertising OAuth", async () => {+ const { http } = stubHttp({ challenge: 'Bearer realm="mcp"', json: {} });+ expect((await discoverOauthServer(http, "https://mcp.example.com/mcp")).oauthAdvertised).toBe(true);+ });++ test("a server that hangs fails within the discovery budget, saying it took too long", async () => {+ const { http } = stubHttp({ hang: true, json: {} });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp", 20)).rejects.toThrow(+ "Couldn't set up OAuth for 'mcp.example.com': it took too long to respond. Check that the server is online, then try again."+ );+ });++ test("a server asking for more scopes than the cap is refused with the count", async () => {+ const { http } = stubHttp({+ json: {+ "https://mcp.example.com/.well-known/oauth-protected-resource": {+ resource: "https://mcp.example.com/mcp",+ authorization_servers: ["https://mcp.example.com"],+ scopes_supported: Array.from({ length: MAX_OAUTH_SCOPES + 1 }, (_, index) => `scope:${index}`)+ }+ }+ });+ await expect(discoverOauthServer(http, "https://mcp.example.com/mcp")).rejects.toThrow(+ `it asks for ${MAX_OAUTH_SCOPES + 1} OAuth scopes, more than the ${MAX_OAUTH_SCOPES} Infisical supports.`+ );+ });+test("an authorization server with a plain-http token endpoint is rejected", async () => {const { http } = stubHttp({json: {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.tsindex 2eecbfbde3..c25bae0678 100644--- 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.ts@@ -7,6 +7,12 @@ import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fimport { AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";export const OFFLINE_ACCESS_SCOPE = "offline_access";+// The spec sets no limit. Slack, the largest real server found, lists 30; this only stops a buggy or hostile+// server from making every authorization store and send an enormous scope list.+export const MAX_OAUTH_SCOPES = 100;+// Each request has its own 10 second timeout, so without an overall budget a server that hangs could hold the+// request past a 60 second gateway.+const DISCOVERY_BUDGET_MS = 25_000;export type TOauthDiscovery = {issuer: string;@@ -21,6 +27,9 @@ export type TOauthDiscovery = {issParameterSupported: boolean;tokenEndpointAuthMethodsSupported: string[] | null;compatibility: AgentVaultOauthCompatibility[];+ // False when the server answered but sent no Bearer challenge and serves no OAuth metadata, which usually+ // means the URL is wrong. Old servers can still work with an admin-entered client, so it only warns.+ oauthAdvertised: boolean;};export const describeServer = (serverUrl: string) => {@@ -103,12 +112,14 @@ const parseJsonObject = (response: TOauthHttpResponse): Record<string, unknown>}};-const fetchJson = async (http: TOauthHttpClient, url: string) => {+type TFetchedJson = { answered: boolean; json: Record<string, unknown> | null };++const fetchJson = async (http: TOauthHttpClient, url: string): Promise<TFetchedJson> => {try {- return parseJsonObject(await http.get(url));+ return { answered: true, json: parseJsonObject(await http.get(url)) };} catch {logger.info(`agentVaultOauth: metadata fetch failed [url=${sanitizeUrlForLog(url)}]`);- return null;+ return { answered: false, json: null };}};@@ -208,27 +219,41 @@ export const selectScopes = ({return [...new Set([...scopes, ...offline])];};-export const discoverOauthServer = async (http: TOauthHttpClient, serverUrl: string): Promise<TOauthDiscovery> => {+const discover = 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 answered = false;++ // The probe and the well-known locations are asked at once; the challenge only says where to look first.+ const wellKnownUrls = protectedResourceMetadataUrls(serverUrl);+ const [challenge, wellKnown] = await Promise.all([+ http.probe(serverUrl).then(+ (response) => {+ answered = true;+ return parseBearerChallenge(response.wwwAuthenticate);+ },+ () => {+ logger.info(`agentVaultOauth: MCP server probe failed [server=${describeServer(serverUrl)}]`);+ return null;+ }+ ),+ Promise.all(wellKnownUrls.map(async (url) => [url, await fetchJson(http, url)] as const))+ ]);+ const fetched = new Map<string, TFetchedJson>(wellKnown);+ const orderedUrls = protectedResourceMetadataUrls(serverUrl, challenge?.resource_metadata);+ const challengeUrl = orderedUrls.find((url) => !fetched.has(url));+ if (challengeUrl) fetched.set(challengeUrl, await fetchJson(http, challengeUrl));+ if ([...fetched.values()].some((result) => result.answered)) answered = true;++ if (!answered) {+ throw new BadRequestError({+ message: `Couldn't reach '${describeServer(serverUrl)}'. Check the server URL and that the server is online.`+ });}- 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;- }- }+ const protectedResource =+ orderedUrls+ .map((url) => fetched.get(url)?.json)+ .find((candidate) => candidate && Array.isArray(candidate.authorization_servers)) ?? null;let resource = serverUrl;let issuer = new URL(serverUrl).origin;@@ -247,19 +272,21 @@ export const discoverOauthServer = async (http: TOauthHttpClient, serverUrl: strcompatibility.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 metadataResults = await Promise.all(authorizationServerMetadataUrls(issuer).map((url) => fetchJson(http, url)));+ const metadata = metadataResults.map((result) => result.json).find(Boolean) ?? null;const scopes = selectScopes({challengeScope: challenge?.scope,scopesSupported: protectedResource?.scopes_supported,authorizationServerScopes: metadata?.scopes_supported});+ if (scopes.length > MAX_OAUTH_SCOPES) {+ throw oauthSetupError(+ serverUrl,+ `it asks for ${scopes.length} OAuth scopes, more than the ${MAX_OAUTH_SCOPES} Infisical supports.`+ );+ }+ const oauthAdvertised = Boolean(challenge || protectedResource || metadata);if (!metadata) {compatibility.add(AgentVaultOauthCompatibility.NoAuthorizationServerMetadata);@@ -275,7 +302,8 @@ export const discoverOauthServer = async (http: TOauthHttpClient, serverUrl: strscopes,issParameterSupported: false,tokenEndpointAuthMethodsSupported: null,- compatibility: [...compatibility]+ compatibility: [...compatibility],+ oauthAdvertised};}@@ -317,6 +345,28 @@ export const discoverOauthServer = async (http: TOauthHttpClient, serverUrl: strtokenEndpointAuthMethodsSupported: Array.isArray(authMethods)? authMethods.filter((method): method is string => typeof method === "string"): null,- compatibility: [...compatibility]+ compatibility: [...compatibility],+ oauthAdvertised};};++export const discoverOauthServer = async (+ http: TOauthHttpClient,+ serverUrl: string,+ budgetMs = DISCOVERY_BUDGET_MS+): Promise<TOauthDiscovery> => {+ let timer: NodeJS.Timeout | undefined;+ const deadline = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ logger.info(`agentVaultOauth: discovery timed out [server=${describeServer(serverUrl)}]`);+ reject(+ oauthSetupError(serverUrl, "it took too long to respond. Check that the server is online, then try again.")+ );+ }, budgetMs);+ });+ try {+ return await Promise.race([discover(http, serverUrl), deadline]);+ } finally {+ clearTimeout(timer);+ }+};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.tsindex 7f8fd583e0..8f870f30f1 100644--- 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.ts@@ -16,6 +16,7 @@ import {AgentVaultOauthStatus,AgentVaultServiceType} from "../agent-vault/agent-vault-enums";+import { MAX_OAUTH_SCOPES } from "./agent-vault-oauth-discovery-fns";import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";import {AGENT_VAULT_SERVICE_MOVED_MESSAGE,@@ -211,19 +212,23 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>});const row = rows.get(id);const stored = row?.credentialConfig as TAgentVaultOauthConfig | undefined;+ const granted = stored?.grantedScopes ?? [];+ const missing = [...new Set(requiredScopes)].filter((scope) => !granted.includes(scope));if (!row?.encryptedCredential?.equals(expectedEncryptedCredential) ||row.credentialType !== AgentVaultCredentialType.OAuth ||stored?.accessTokenHash !== rejectedTokenHash ||- stored.status === AgentVaultOauthStatus.NeedsReauthorization+ stored.status === AgentVaultOauthStatus.NeedsReauthorization ||+ !missing.length) {return undefined;}const existing = stored.requiredScopes ?? [];+ const added = missing.filter((scope) => !existing.includes(scope));row.credentialConfig = {...stored,status: AgentVaultOauthStatus.NeedsAdditionalScopes,- requiredScopes: [...existing, ...[...new Set(requiredScopes)].filter((scope) => !existing.includes(scope))]+ requiredScopes: [...existing, ...added.slice(0, Math.max(0, MAX_OAUTH_SCOPES - existing.length))]};return {id,@@ -328,6 +333,7 @@ describe("starting an authorization", () => {});expect(await createAuthorization(env)).toEqual({registrationRequired: true,+ oauthAdvertised: true,redirectUri: REDIRECT_URI,registrationError: null,authorization: null@@ -341,6 +347,7 @@ describe("starting an authorization", () => {const result = await createAuthorization(env);expect(result).toEqual({registrationRequired: true,+ oauthAdvertised: 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.",@@ -1105,6 +1112,41 @@ describe("refreshing a service's token", () => {expect(config().requiredScopes).toEqual(["admin", "write"]);});+ test("a scope report skips scopes already granted, and changes nothing when only those are named", async () => {+ await env.service.reportMissingScopes({+ serviceId: SERVICE_ID,+ hostPattern: DESTINATION.hostPattern,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["read"]+ });+ expect(config().status).toBe(AgentVaultOauthStatus.Connected);+ expect(config().requiredScopes).toEqual([]);++ await env.service.reportMissingScopes({+ serviceId: SERVICE_ID,+ hostPattern: DESTINATION.hostPattern,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["read", "admin"]+ });+ expect(config().status).toBe(AgentVaultOauthStatus.NeedsAdditionalScopes);+ expect(config().requiredScopes).toEqual(["admin"]);+ });++ test("required scopes stop growing at the cap", async () => {+ const report = (prefix: string) =>+ env.service.reportMissingScopes({+ serviceId: SERVICE_ID,+ hostPattern: DESTINATION.hostPattern,+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: Array.from({ length: 50 }, (_, index) => `${prefix}:${index}`)+ });+ await report("a");+ await report("b");+ await report("c");+ expect(config().requiredScopes).toHaveLength(MAX_OAUTH_SCOPES);+ expect(config().requiredScopes).not.toContain("c:0");+ });+test("a scope report for a service that moved is a 409 and changes nothing", async () => {await expect(env.service.reportMissingScopes({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.tsindex 4b8e4fdb8f..2448446dd2 100644--- 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.ts@@ -350,6 +350,7 @@ export const agentVaultOauthServiceFactory = ({// Either way the fix is the same, an admin-entered client, so the caller is asked for one.return {registrationRequired: true,+ oauthAdvertised: discovery.oauthAdvertised,redirectUri: callbackUri,registrationError: discovery.endpointsGuessed? null@@ -361,7 +362,13 @@ export const agentVaultOauthServiceFactory = ({};}} else {- return { registrationRequired: true, redirectUri: callbackUri, registrationError: null, authorization: null };+ return {+ registrationRequired: true,+ oauthAdvertised: discovery.oauthAdvertised,+ redirectUri: callbackUri,+ registrationError: null,+ authorization: null+ };}const storedScopes = stored ? [...new Set([...stored.config.grantedScopes, ...stored.config.requiredScopes])] : [];@@ -410,6 +417,7 @@ export const agentVaultOauthServiceFactory = ({return {registrationRequired: false,+ oauthAdvertised: discovery.oauthAdvertised,redirectUri: callbackUri,registrationError: null,authorization: {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.tsindex 941e3318ed..641e68d2a3 100644--- 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.ts@@ -3,7 +3,6 @@ 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,@@ -119,6 +118,21 @@ describe("the authorize URL", () => {});});+ test("offline_access asks for consent, which OIDC requires before it issues a refresh token", () => {+ const url = new URL(+ buildAuthorizeUrl({+ authorizationEndpoint: "https://auth.example.com/authorize",+ clientId: "client-1",+ redirectUri: "https://app.infisical.com/agent-vault/oauth/callback",+ codeChallenge: "challenge",+ state: "id.random",+ resource: null,+ scopes: ["read", "offline_access"]+ })+ );+ expect(url.searchParams.get("prompt")).toBe("consent");+ });+test("no scopes and no resource leave both out", () => {const url = new URL(buildAuthorizeUrl({@@ -343,13 +357,6 @@ describe("token requests", () => {});});- 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 });@@ -532,103 +539,6 @@ describe("granted scopes", () => {});});-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 = {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.tsindex fe9fbe2593..13c984369f 100644--- 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.ts@@ -6,7 +6,12 @@ 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 {+ describeServer,+ OFFLINE_ACCESS_SCOPE,+ splitScopes,+ stripTrailingSlash+} from "./agent-vault-oauth-discovery-fns";import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";import {AGENT_VAULT_OAUTH_GRANT_TYPE,@@ -60,6 +65,8 @@ export const buildAuthorizeUrl = ({url.searchParams.set("state", state);if (resource) url.searchParams.set("resource", resource);if (scopes.length) url.searchParams.set("scope", scopes.join(" "));+ // OIDC Core section 11: a server must ignore offline_access without it, and issue no refresh token.+ if (scopes.includes(OFFLINE_ACCESS_SCOPE)) url.searchParams.set("prompt", "consent");return url.toString();};diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 729387b406..03c1326743 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4569,6 +4569,8 @@ export const AGENT_VAULT = {"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.",+ oauthAdvertised:+ "False when the MCP server answered but sent no OAuth challenge and serves no OAuth metadata. The server URL may be wrong; a server that does use OAuth can still be connected with your own client ID and secret.",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`.",diff --git a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsxindex 0e5e17b558..4a40ae9614 100644--- a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx+++ b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx@@ -1,10 +1,13 @@import { Fragment, ReactNode, useId, useState } from "react";import { useFormContext, useWatch } from "react-hook-form";import { format } from "date-fns";-import { CheckIcon, CircleAlertIcon, CircleXIcon, InfoIcon } from "lucide-react";+import { CheckIcon, CircleAlertIcon, CircleXIcon, InfoIcon, TriangleAlertIcon } from "lucide-react";import { twMerge } from "tailwind-merge";import {+ Alert,+ AlertDescription,+ AlertTitle,Badge,Button,CopyButton,@@ -165,17 +168,24 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {);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 {+ state,+ isClientRequired,+ isOAuthAdvertised,+ 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 wantsOwnApp = isClientRequired || isUsingOwnApp;@@ -349,7 +359,18 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {{isOwnApp && (<div className="flex flex-col gap-4">- {isClientRequired && (+ {isClientRequired && !isOAuthAdvertised && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertTitle>{host} doesn't look like it uses OAuth</AlertTitle>+ <AlertDescription>+ It answered, but sent no OAuth challenge and serves no OAuth metadata. Check the+ server URL. If the server does use OAuth, enter your OAuth app's client ID+ and secret below.+ </AlertDescription>+ </Alert>+ )}+ {isClientRequired && isOAuthAdvertised && (<p className="text-xs text-muted">{registrationError? `${host} didn't accept automatic setup, so use your own OAuth app.`@@ -385,7 +406,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {<Input{...register("oauthClientId")}id={clientIdInputId}- maxLength={512}+ maxLength={2048}autoComplete="off"spellCheck={false}isError={Boolean(errors.oauthClientId)}@@ -400,7 +421,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {type="password"{...register("oauthClientSecret")}id={clientSecretInputId}- maxLength={1024}+ maxLength={4096}autoComplete="new-password"isError={Boolean(errors.oauthClientSecret)}/>diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.tsindex e9133fd9d4..1fa4227aac 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts@@ -208,7 +208,7 @@ describe("buildServiceSchema with OAuth", () => {it("validates manual client credentials in the service form", () => {const result = buildServiceSchema(storedOAuthService()).safeParse(- mcpForm({ oauthClientId: "x".repeat(513), oauthClientSecret: "x".repeat(1025) })+ mcpForm({ oauthClientId: "x".repeat(2049), oauthClientSecret: "x".repeat(4097) }));expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(["oauthClientId",diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 904cc6feab..56e7f3ba7c 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -262,11 +262,11 @@ export const buildServiceSchema = (oauthClientId: z.string().trim()- .max(512, "A client ID can be at most 512 characters.")+ .max(2048, "A client ID can be at most 2048 characters.").optional(),oauthClientSecret: z.string()- .max(1024, "A client secret can be at most 1024 characters.")+ .max(4096, "A client secret can be at most 4096 characters.").optional(),methods: z.array(z.nativeEnum(AgentVaultHttpMethod)),pathPrefixes: zdiff --git a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.tsindex 35bfbfbeee..5a44e9ca62 100644--- a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts+++ b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts@@ -38,6 +38,7 @@ export const useOAuthAuthorize = ({const [isClientRequired, setIsClientRequired] = useState(false);const [redirectUri, setRedirectUri] = useState<string | null>(null);const [registrationError, setRegistrationError] = useState<string | null>(null);+ const [isOAuthAdvertised, setIsOAuthAdvertised] = useState(true);const [pendingAuthorization, setPendingAuthorization] = useState<{id: string;attempt: number;@@ -122,6 +123,7 @@ export const useOAuthAuthorize = ({.then(({registrationRequired,+ oauthAdvertised,redirectUri: uri,registrationError: reason,authorization: createdAuthorization@@ -132,6 +134,7 @@ export const useOAuthAuthorize = ({setIsClientRequired(true);setRedirectUri(uri);setRegistrationError(reason);+ setIsOAuthAdvertised(oauthAdvertised);setState({ status: "idle" });return;}@@ -153,5 +156,13 @@ export const useOAuthAuthorize = ({setState({ status: "idle" });}, [stop]);- return { state, isClientRequired, redirectUri, registrationError, authorize, cancel };+ return {+ state,+ isClientRequired,+ isOAuthAdvertised,+ redirectUri,+ registrationError,+ authorize,+ cancel+ };};diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.tsindex 7aafef475a..814d3b8911 100644--- a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts@@ -115,7 +115,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/UcUI6/VTBSsIZvF08UTnPeIW+yM1I5hHCoi0WQT6QRe0bdx5+BvGuvJQB"+ "qrvM3e7/ABEiM0RVPLRwxBbgu+W68Br1N9gY1oUy8wjJxQClAtBh0NfJS1UcWOCPn3laS615sIqwFONhPIPNWRI3CA+a5tUJ7aoim0sQkE4d9gzou2mc/AWiCdToVBJPtdumA9jIzh3yAI81YPwcoDXEVnq2+7ooNNJShGdLX95itbrna/t4nFKRKSSgNzbH23eMtSMcSo72puk/2iwh4sVbTKzC2kwvbf1U6Mgd21zkIq2jDKKwhcT6mTfjPivW4FzmmkspQVMoWwANRX+QVyXzrMipZfoq5N/UcUI6/VTBSsIZvF08UTnPeIW+yM1I5hHColwnfZxQ749XdRSAGhFTIDZG4lkYWxDX+Nw+CUFLdEVwfS/W3qlckKhvB9kyNebTACDUjP8tKYDzi23/ps2hEVcDroDq1EvaoBVV9GPqSbOHiIWDQPpWJ/UJG7anF0NIYtFusQI+WW7KbaPlvoSMs7sALLQLLtM2UjlPalynrTcnH+BREzDa3WqOfHlvTdKfUzsTGp7PmtxOGbE5rHzM5ll+kWvixiwSnGPjBJMy7WeEWCPdnnpTIf1NM4mwikgPH3YPsUCLOauO/GcOoAKaMYxeisSZ6C9V/2ifRbLGOFTaPMmwHEzpeHtQiR8wqd2TKpR7PEBSiSTYpaDJKrzJQgr91cpoPgFakuDptDRaJ4eAcxulJ/ICFC8IkH5cRF2hiDJwdFgy17wdNpFGek87ZB+ZXG8IbS/ONkM8KJrszUHvY9PamV46"),(char) => char.charCodeAt(0));@@ -274,6 +274,11 @@ 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");+ assert.equal(result.decrypted[key].records[1].serviceType, "mcp");+ assert.deepEqual(result.decrypted[key].records[1].mcp, {+ calls: [{ method: "tools/call", tool: "list_issues" }],+ parsed: true+ });});it("refuses a chunk whose records name a different proxy than its file", async () => {diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 62510c7b87..a976391a5a 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -346,6 +346,8 @@ export type TCreateAgentVaultOAuthAuthorizationDTO = {export type TCreateAgentVaultOAuthAuthorizationResponse = {registrationRequired: boolean;+ // False when the server answered but advertises no OAuth, which usually means a wrong URL.+ oauthAdvertised: boolean;redirectUri: string;// Why the server's registration endpoint refused Infisical; null when it simply has none.registrationError: string | null;