Skip to content

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

misc: addressed third batch of review comments

Sheen Capadngan745f211f1864
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.ts
index b6a5f790a9..d99653b35f 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
@@ -3,9 +3,9 @@ import { z } from "zod";
import { AgentVaultOauthAuthorizationStatus } from "@app/ee/services/agent-vault/agent-vault-enums";
import {
MAX_CLIENT_ID_LENGTH,
- MAX_CLIENT_SECRET_LENGTH,
- OAUTH_CLIENT_CREDENTIAL_PATTERN
+ MAX_CLIENT_SECRET_LENGTH
} from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns";
+import { OAUTH_VSCHAR_PATTERN } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-token-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";
@@ -23,10 +23,7 @@ const AuthorizationViewSchema = z.object({
});
const printable = (max: number) =>
- z
- .string()
- .max(max)
- .regex(OAUTH_CLIENT_CREDENTIAL_PATTERN, "Use printable ASCII characters without line breaks or accents");
+ z.string().max(max).regex(OAUTH_VSCHAR_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) => {
@@ -48,14 +45,12 @@ export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider)
.string()
.trim()
.min(1)
- .max(MAX_CLIENT_ID_LENGTH)
.pipe(printable(MAX_CLIENT_ID_LENGTH))
.optional()
.describe(AGENT_VAULT.OAUTH.clientId),
clientSecret: z
.string()
.min(1)
- .max(MAX_CLIENT_SECRET_LENGTH)
.pipe(printable(MAX_CLIENT_SECRET_LENGTH))
.optional()
.describe(AGENT_VAULT.OAUTH.clientSecret)
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.ts
index 4790eeab83..a90f0d6397 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
@@ -17,7 +17,7 @@ import {
} 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 { agentVaultMcpServerUrlSchema } from "@app/ee/services/agent-vault/agent-vault-service-type-fns";
import {
acceptsVariableReferences,
addDuplicateCustomHeaderNameIssues,
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.ts
index cc17eb1f19..04551c6372 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
@@ -54,9 +54,10 @@ import {
assertServiceFieldsSupported,
buildServiceConfig,
getAgentVaultServiceType,
+ getServiceServerUrl,
resolveServiceHostPattern,
TAgentVaultServiceConfig
-} from "../agent-vault/agent-vault-service-types";
+} from "../agent-vault/agent-vault-service-type-fns";
import {
findStoredVariableIds,
findVariableKeys,
@@ -667,8 +668,8 @@ 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.
+ // The tokens come from an authorization the same user completed. Claiming it deletes it right before the write,
+ // and a save that then fails puts it back, so it can be retried without authorizing again.
const claimOauthCredential = async ({
projectId,
ctx,
@@ -1135,7 +1136,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
: undefined;
const oauthAuthorizationId =
credential?.type === AgentVaultCredentialType.OAuth ? credential.authorizationId : undefined;
- const storedServerUrl = (service.config as TAgentVaultServiceConfig | null)?.serverUrl;
+ const storedServerUrl = getServiceServerUrl(service.config);
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 });
@@ -1255,7 +1256,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
ctx: rest.ctx,
accessBundleId: bundle.id,
serviceId: service.id,
- serverUrl: (serviceConfig ?? (service.config as TAgentVaultServiceConfig)).serverUrl!,
+ serverUrl: getServiceServerUrl(serviceConfig ?? service.config)!,
authorizationId: oauthAuthorizationId,
previousRequiredScopes: storedOauth?.requiredScopes
})
@@ -1275,7 +1276,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
// 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)
@@ -1292,8 +1292,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
if (lockedOauth && !oauth && (!credential || credential.type === AgentVaultCredentialType.OAuth)) {
checkOauthServerUnderLock({
requestedServerUrl: serverUrl,
- readServerUrl: storedServerUrl ?? null,
- effectiveServerUrl: lockedServiceConfig.serverUrl ?? null,
+ readServerUrl: storedServerUrl,
+ effectiveServerUrl: getServiceServerUrl(lockedServiceConfig),
lockedOauth
});
}
@@ -1312,7 +1312,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
// 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,
+ lockedServerUrl: getServiceServerUrl(lockedServiceConfig ?? locked.config),
readOauth: storedOauth,
lockedOauth
});
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts
new file mode 100644
index 0000000000..d0fe846f0f
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, test, vi } from "vitest";
+
+import {
+ manualOauthClient,
+ MAX_CLIENT_ID_LENGTH,
+ OauthRegistrationError,
+ registerOauthClient
+} from "./agent-vault-oauth-client-fns";
+import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-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
+}));
+
+const stubPosts = (responses: TOauthHttpResponse[]) => {
+ const calls: { url: string; json: unknown }[] = [];
+ const http: TOauthHttpClient = {
+ probe: async () => ({ status: 401, wwwAuthenticate: null }),
+ get: async () => {
+ throw new Error("unexpected");
+ },
+ postForm: async () => {
+ throw new Error("unexpected");
+ },
+ postJson: async (url, json) => {
+ calls.push({ url, json });
+ const response = responses.shift();
+ if (!response) throw new Error("no more stubbed responses");
+ return response;
+ }
+ };
+ return { http, calls };
+};
+
+const json = (status: number, body: unknown): TOauthHttpResponse => ({
+ status,
+ contentType: "application/json",
+ body: JSON.stringify(body)
+});
+
+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 without application_type, keeping the grant types", 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(calls[1].json).toEqual({
+ client_name: "Infisical Agent Vault",
+ redirect_uris: [args.redirectUri],
+ token_endpoint_auth_method: "none",
+ grant_types: ["authorization_code", "refresh_token"],
+ response_types: ["code"]
+ });
+ });
+
+ 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 long JWT client ID is accepted, up to the limit", async () => {
+ const jwtLength = stubPosts([json(201, { client_id: "c".repeat(850) })]);
+ expect((await registerOauthClient({ http: jwtLength.http, ...args })).client.clientId).toHaveLength(850);
+
+ const tooLong = stubPosts([json(201, { client_id: "c".repeat(MAX_CLIENT_ID_LENGTH + 1) })]);
+ await expect(registerOauthClient({ http: tooLong.http, ...args })).rejects.toThrow(/no usable client ID/);
+ });
+
+ 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);
+ });
+});
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.ts
index 5d52fd562a..1491b4ea8f 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
@@ -1,5 +1,3 @@
-import RE2 from "re2";
-
import { logger } from "@app/lib/logger";
import { describeServer } from "./agent-vault-oauth-discovery-fns";
@@ -7,7 +5,8 @@ import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";
import {
MAX_ERROR_CODE_LENGTH,
MAX_ERROR_DESCRIPTION_LENGTH,
- normalizeProviderText
+ normalizeProviderText,
+ OAUTH_VSCHAR_PATTERN
} from "./agent-vault-oauth-token-fns";
import {
AGENT_VAULT_OAUTH_GRANT_TYPE,
@@ -35,9 +34,6 @@ export class OauthRegistrationError extends Error {
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]+$/);
export const MAX_CLIENT_ID_LENGTH = 2048;
export const MAX_CLIENT_SECRET_LENGTH = 4096;
@@ -52,16 +48,13 @@ const parseRegistration = (body: string): TOauthClient | null => {
!parsed ||
typeof parsed.client_id !== "string" ||
parsed.client_id.length > MAX_CLIENT_ID_LENGTH ||
- !OAUTH_CLIENT_CREDENTIAL_PATTERN.test(parsed.client_id)
+ !OAUTH_VSCHAR_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)
- ) {
+ if (parsed.client_secret.length > MAX_CLIENT_SECRET_LENGTH || !OAUTH_VSCHAR_PATTERN.test(parsed.client_secret)) {
return null;
}
clientSecret = parsed.client_secret;
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.ts
index 8f870f30f1..f70e9ef4b9 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
@@ -105,6 +105,7 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>
const tokenRequests: URLSearchParams[] = [];
const registrations: unknown[] = [];
let registerHandler: () => TOauthHttpResponse = () => json(201, { client_id: "registered-client" });
+ let lockHandler: (settings: unknown) => Promise<void> = async () => {};
let tokenHandler: (form: URLSearchParams) => TOauthHttpResponse = () =>
json(200, { access_token: "at-1", token_type: "Bearer", refresh_token: "rt-1", expires_in: 3600, scope: "read" });
@@ -154,7 +155,10 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>
},
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 })
+ acquireLock: async (_keys: string[], _duration: number, settings?: unknown) => {
+ await lockHandler(settings);
+ return { release: async () => ({}) as never };
+ }
},
kmsService: kms as never,
agentVaultServiceDAL: {
@@ -271,6 +275,9 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>
},
onRegister: (handler: typeof registerHandler) => {
registerHandler = handler;
+ },
+ onAcquireLock: (handler: typeof lockHandler) => {
+ lockHandler = handler;
}
};
};
@@ -298,6 +305,31 @@ const authorize = async (env: ReturnType<typeof setup>) => {
return authorization!.id;
};
+const oauthConfig = (overrides: Partial<TAgentVaultOauthConfig> = {}): TAgentVaultOauthConfig => ({
+ type: AgentVaultCredentialType.OAuth,
+ grantType: "authorization_code",
+ serverUrl: SERVER_URL,
+ 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("starting an authorization", () => {
test("discovers, registers a client, and returns an authorize URL with PKCE S256, resource and state", async () => {
const env = setup();
@@ -379,6 +411,75 @@ describe("starting an authorization", () => {
expect(env.registrations).toHaveLength(0);
});
+ const storeOauthService = (env: ReturnType<typeof setup>, overrides: Partial<TAgentVaultOauthConfig> = {}) =>
+ env.rows.set(SERVICE_ID, {
+ id: SERVICE_ID,
+ name: "linear",
+ type: AgentVaultServiceType.Mcp,
+ accessBundleId: BUNDLE_ID,
+ credentialType: AgentVaultCredentialType.OAuth,
+ credentialConfig: oauthConfig({ clientId: "old-client", grantedScopes: ["admin"], ...overrides }),
+ encryptedCredential: sealBytes({
+ accessToken: "old-access",
+ refreshToken: "old-refresh",
+ clientSecret: "old-shh"
+ })
+ });
+ const clientIdOf = (authorizeUrl: string) => new URL(authorizeUrl).searchParams.get("client_id");
+
+ test("reauthorizing registers a fresh client instead of reusing a registered one the server may have dropped", async () => {
+ const env = setup();
+ storeOauthService(env);
+ const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID });
+ expect(env.registrations).toHaveLength(1);
+ expect(clientIdOf(authorization!.authorizeUrl)).toBe("registered-client");
+ });
+
+ test("reauthorizing keeps a client entered by hand, since nothing can register it again", async () => {
+ const env = setup();
+ storeOauthService(env, { registration: AgentVaultOauthRegistration.Manual });
+ const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID });
+ expect(env.registrations).toHaveLength(0);
+ expect(clientIdOf(authorization!.authorizeUrl)).toBe("old-client");
+ });
+
+ test("reauthorizing falls back to the stored client when a fresh one can't be registered", async () => {
+ const env = setup();
+ env.onRegister(() => json(400, { error: "invalid_client_metadata" }));
+ storeOauthService(env);
+ const result = await createAuthorization(env, { serviceId: SERVICE_ID });
+ expect(result.registrationRequired).toBe(false);
+ expect(clientIdOf(result.authorization!.authorizeUrl)).toBe("old-client");
+ const record = JSON.parse(
+ env.store.get(`agent-vault-oauth-authorization:${result.authorization!.id}`)!
+ ) as TAgentVaultOauthAuthorization;
+ expect(record.registration).toBe(AgentVaultOauthRegistration.Dynamic);
+ });
+
+ test("reauthorizing at a different issuer uses neither the stored client nor its scopes", 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
+ }
+ }
+ });
+ storeOauthService(env, { registration: AgentVaultOauthRegistration.Manual, issuer: "https://old.example.com" });
+ expect((await createAuthorization(env, { serviceId: SERVICE_ID })).registrationRequired).toBe(true);
+
+ const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID, clientId: "my-app" });
+ expect(authorization!.scopes).toEqual(["read", "write"]);
+ });
+
+ test("reauthorizing at the same issuer asks again for the scopes the service holds and still needs", async () => {
+ const env = setup();
+ storeOauthService(env, { requiredScopes: ["write"] });
+ const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID });
+ expect(authorization!.scopes).toEqual(["admin", "write"]);
+ });
+
test("a client secret without a client ID is refused", async () => {
await expect(createAuthorization(setup(), { clientSecret: "shh" })).rejects.toThrow(/client ID/);
});
@@ -515,6 +616,26 @@ describe("completing an authorization", () => {
expect(env.tokenRequests).toHaveLength(0);
});
+ test.each([
+ { iss: "https://evil.example.com", problem: /different server/ },
+ { iss: undefined, problem: /didn't say which server issued it/ }
+ ])("an error response with iss $iss never shows the provider's text", async ({ iss, problem }) => {
+ 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")!,
+ error: "server_error",
+ errorDescription: "Visit https://evil.example.com/login to fix this",
+ iss
+ });
+ expect(view.status).toBe(AgentVaultOauthAuthorizationStatus.Failed);
+ expect(view.error).toMatch(problem);
+ expect(view.error).not.toMatch(/Visit|didn't authorize/);
+ });
+
test("a missing iss from a server that advertises it fails", async () => {
const env = setup();
const { authorization } = await createAuthorization(env);
@@ -537,7 +658,8 @@ describe("completing an authorization", () => {
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)}`
+ errorDescription: `The admin\r\n\tdisabled\u202e this app. ${"x".repeat(3000)}`,
+ iss: "https://mcp.linear.app"
});
expect(view.authorization.status).toBe(AgentVaultOauthAuthorizationStatus.Failed);
expect(view.authorization.error).toMatch(
@@ -554,7 +676,8 @@ describe("completing an authorization", () => {
ctx: ctxOf(USER_ID),
authorizationId: first.id,
state: new URL(first.authorizeUrl).searchParams.get("state")!,
- error: "access_denied"
+ error: "access_denied",
+ iss: "https://mcp.linear.app"
});
expect(deniedView.authorization.error).toBe("Access to 'mcp.linear.app' was denied, so nothing was connected.");
@@ -754,31 +877,6 @@ describe("using an authorization", () => {
});
});
-const oauthConfig = (overrides: Partial<TAgentVaultOauthConfig> = {}): TAgentVaultOauthConfig => ({
- type: AgentVaultCredentialType.OAuth,
- grantType: "authorization_code",
- serverUrl: SERVER_URL,
- 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)!;
@@ -875,6 +973,85 @@ describe("refreshing a service's token", () => {
expect(config().lastError).toMatch(/Reauthorize this service/);
});
+ test.each([
+ { error: "invalid_client", status: 401, why: "the server dropped the registered client" },
+ { error: "unauthorized_client", status: 400, why: "the client may no longer use this grant" },
+ { error: "bad_refresh_token", status: 200, why: "GitHub, with a 200" },
+ { error: "invalid_refresh_token", status: 200, why: "Slack, with ok: false" },
+ { error: "token_revoked", status: 200, why: "Slack" },
+ { error: "token_expired", status: 200, why: "Slack" }
+ ])("$error marks the service as needing reauthorization ($why)", async ({ error, status }) => {
+ env.onToken(() => json(status, { ok: false, error }));
+ 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(config().lastError).toBe(
+ `The MCP server no longer accepts this service's login ('mcp.linear.app' refused the token request: ${error}). Reauthorize this service.`
+ );
+
+ // A dead login isn't retried on the next poll.
+ await env.service.refreshServiceToken({
+ serviceId: SERVICE_ID,
+ projectId: PROJECT_ID,
+ destination: DESTINATION,
+ rejectedTokenHash: hashAccessToken("old-access")
+ });
+ expect(env.tokenRequests).toHaveLength(1);
+ });
+
+ test("the proxy's refresh after a 401 waits longer for a concurrent refresh than resolve does", async () => {
+ const waits: number[] = [];
+ env.onAcquireLock(async (settings) => {
+ const { retryCount, retryDelay } = settings as { retryCount: number; retryDelay: number };
+ waits.push(retryCount * retryDelay);
+ });
+ 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")
+ });
+ row().credentialConfig = oauthConfig({
+ accessTokenHash: hashAccessToken("new-access"),
+ expiresAt: new Date(Date.now() + 30_000).toISOString()
+ });
+ await env.service.refreshServiceToken({
+ serviceId: SERVICE_ID,
+ projectId: PROJECT_ID,
+ destination: DESTINATION,
+ expiresWithinSeconds: 60
+ });
+ expect(waits).toHaveLength(2);
+ // Outlasts the holder's 7 second token budget, yet stays under the proxy's 15 second timeout.
+ expect(waits[0]).toBeGreaterThan(7_000);
+ expect(waits[0]).toBeLessThan(15_000);
+ expect(waits[1]).toBeLessThanOrEqual(3_000);
+ });
+
+ test("a refresh that waited out a failed holder only spends the time left before the proxy gives up", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ try {
+ env.onAcquireLock(async () => {
+ vi.setSystemTime(Date.now() + 12_500);
+ });
+ const result = await env.service.refreshServiceToken({
+ serviceId: SERVICE_ID,
+ projectId: PROJECT_ID,
+ destination: DESTINATION,
+ rejectedTokenHash: hashAccessToken("old-access")
+ });
+ expect(result.credential.value).toBe("old-access");
+ expect(env.tokenRequests).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
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({
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.ts
index 2448446dd2..679b58119c 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
@@ -23,7 +23,7 @@ import {
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 { getServiceServerUrl } from "../agent-vault/agent-vault-service-type-fns";
import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";
import { TAgentVaultServiceDALFactory } from "../agent-vault-access-bundle/agent-vault-service-dal";
import {
@@ -47,9 +47,11 @@ import {
generatePkce,
generateState,
hashAccessToken,
+ isDeadLoginError,
isSameState,
normalizeProviderText,
refreshAccessToken,
+ TOKEN_REQUEST_BUDGET_MS,
validateCallbackIssuer,
withTokenCompatibility
} from "./agent-vault-oauth-token-fns";
@@ -71,14 +73,20 @@ import {
TResolvedOauthCredential
} from "./agent-vault-oauth-types";
-export const AGENT_VAULT_OAUTH_AUTHORIZATION_TTL_SECONDS = 10 * 60;
+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";
+// How long a refresh waits for a concurrent one of the same service before answering with whatever is stored.
+// Resolve waits ~3s, since its own 4 second budget sends the stored token anyway. The proxy's refresh after a 401
+// waits ~10s, so it outlasts the holder's 7 second token budget and gets the new token instead of the rejected one.
+const RESOLVE_REFRESH_LOCK_SETTINGS = { retryCount: 12, retryDelay: 200, retryJitter: 50 };
+const REJECTED_TOKEN_REFRESH_LOCK_SETTINGS = { retryCount: 48, retryDelay: 200, retryJitter: 50 };
+// A refresh answers within this, under the proxy's 15 second timeout, so a waiter whose holder failed gets only the
+// time left for its own token request, and skips it below the minimum.
+const REFRESH_ANSWER_DEADLINE_MS = 13 * 1000;
+const MIN_REFRESH_BUDGET_MS = 1000;
+const AGENT_VAULT_OAUTH_CALLBACK_PATH = "/agent-vault/oauth/callback";
type TAgentVaultOauthServiceFactoryDep = {
keyStore: Pick<
@@ -111,10 +119,8 @@ type TLoadedOauthService = {
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) => {
+const assertAuthorizationServerUrl = (authorizedServerUrl: string, serviceServerUrl: string | null) => {
if (authorizedServerUrl === serviceServerUrl) return;
const authorizedHost = describeServer(authorizedServerUrl);
if (!serviceServerUrl) {
@@ -134,7 +140,7 @@ export const assertAuthorizationServerUrl = (authorizedServerUrl: string, servic
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 =
+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
@@ -316,8 +322,12 @@ export const agentVaultOauthServiceFactory = ({
const discovery = await discoverOauthServer(http, serverUrl);
const compatibility = [...discovery.compatibility];
- let client: TOauthClient;
- let registration: AgentVaultOauthRegistration;
+ // A client is only ever used with the issuer it was registered at, and so are the scopes it was granted.
+ const sameIssuerStored = stored && stored.config.issuer === discovery.issuer ? stored : null;
+
+ let client: TOauthClient | null = null;
+ let registration: AgentVaultOauthRegistration | null = null;
+ let registrationError: string | null = null;
if (clientId) {
client = manualOauthClient({
clientId,
@@ -325,15 +335,13 @@ export const agentVaultOauthServiceFactory = ({
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) {
+ } else if (
+ sameIssuerStored?.config.registration !== AgentVaultOauthRegistration.Manual &&
+ discovery.registrationEndpoint
+ ) {
+ // Reauthorizing registers a fresh client rather than reusing the stored one, which the server may have dropped
+ // (expired, or registered for an old SITE_URL), and then the sign-in would fail on the provider's page without
+ // Infisical ever hearing back. Only a client entered by hand is kept, since nothing can register it again.
try {
const registered = await registerOauthClient({
http,
@@ -348,30 +356,34 @@ export const agentVaultOauthServiceFactory = ({
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,
- oauthAdvertised: discovery.oauthAdvertised,
- 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
- };
+ registrationError = discovery.endpointsGuessed
+ ? null
+ : oauthSetupError(serverUrl, `${error.message} Enter the client ID and secret of your own OAuth app instead.`)
+ .message;
}
- } else {
+ }
+ // The stored client is still worth trying when no fresh one could be registered.
+ if (!client && sameIssuerStored) {
+ client = {
+ clientId: sameIssuerStored.config.clientId,
+ clientSecret: sameIssuerStored.clientSecret,
+ tokenEndpointAuthMethod: sameIssuerStored.config.tokenEndpointAuthMethod
+ };
+ registration = sameIssuerStored.config.registration;
+ }
+ if (!client || !registration) {
return {
registrationRequired: true,
oauthAdvertised: discovery.oauthAdvertised,
redirectUri: callbackUri,
- registrationError: null,
+ registrationError,
authorization: null
};
}
- const storedScopes = stored ? [...new Set([...stored.config.grantedScopes, ...stored.config.requiredScopes])] : [];
+ const storedScopes = sameIssuerStored
+ ? [...new Set([...sameIssuerStored.config.grantedScopes, ...sameIssuerStored.config.requiredScopes])]
+ : [];
const requestedScopes = storedScopes.length
? [
...new Set([
@@ -485,7 +497,10 @@ export const agentVaultOauthServiceFactory = ({
serverUrl: record.serverUrl
});
- if (error) {
+ // RFC 9207 section 2.4: a response from the wrong issuer is not trusted, its error text included.
+ if (issuerProblem) {
+ fail(issuerProblem);
+ } else if (error) {
const providerError = normalizeProviderText(error, undefined, [code, state]);
const detail =
normalizeProviderText(errorDescription, undefined, [code, state]) || providerError || "no reason given";
@@ -494,8 +509,6 @@ export const agentVaultOauthServiceFactory = ({
? `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 {
@@ -682,7 +695,7 @@ export const agentVaultOauthServiceFactory = ({
secret,
encryptedCredential: service.encryptedCredential,
hostPattern: service.hostPattern,
- serverUrl: serverUrlOf(service.config)
+ serverUrl: getServiceServerUrl(service.config)
};
};
@@ -719,6 +732,7 @@ export const agentVaultOauthServiceFactory = ({
expiresWithinSeconds,
destination
}: TRefreshServiceTokenDTO): Promise<{ credential: TResolvedOauthCredential; status: AgentVaultOauthStatus }> => {
+ const deadline = Date.now() + REFRESH_ANSWER_DEADLINE_MS;
let cipherPair: Promise<TProjectCipher> | null = null;
const cipher = () => {
cipherPair ??= getProjectCipher(projectId);
@@ -758,7 +772,7 @@ export const agentVaultOauthServiceFactory = ({
secret,
encryptedCredential,
hostPattern: row.hostPattern,
- serverUrl: serverUrlOf(row.config)
+ serverUrl: getServiceServerUrl(row.config)
});
// A failed swap means the row moved on (a reauthorization, usually), and the new row is the answer.
@@ -793,7 +807,7 @@ export const agentVaultOauthServiceFactory = ({
lock = await keyStore.acquireLock(
[KeyStorePrefixes.AgentVaultOauthRefreshLock(serviceId)],
REFRESH_LOCK_DURATION_MS,
- REFRESH_LOCK_SETTINGS
+ rejectedTokenHash === undefined ? RESOLVE_REFRESH_LOCK_SETTINGS : REJECTED_TOKEN_REFRESH_LOCK_SETTINGS
);
} catch {
// Another refresh held the lock the whole time; whatever it stored is the best answer available.
@@ -810,6 +824,9 @@ export const agentVaultOauthServiceFactory = ({
return answer();
}
+ const budgetMs = Math.min(TOKEN_REQUEST_BUDGET_MS, deadline - Date.now());
+ if (budgetMs < MIN_REFRESH_BUDGET_MS) return answer();
+
const { config, secret } = current;
const result = await refreshAccessToken({
http,
@@ -822,13 +839,14 @@ export const agentVaultOauthServiceFactory = ({
resource: config.resource,
requestedScopes: config.requestedScopes,
sensitiveValues: [secret.accessToken],
- refreshToken: secret.refreshToken!
+ refreshToken: secret.refreshToken!,
+ budgetMs
});
if (!result.ok) {
- if (result.errorCode === "invalid_grant") {
+ if (isDeadLoginError(result.errorCode)) {
await markNeedsReauthorization(
- "The MCP server no longer accepts the stored refresh token (it may have been revoked). Reauthorize this service."
+ `The MCP server no longer accepts this service's login (${result.message}). Reauthorize this service.`
);
} else {
await applyStatus({ lastError: result.message });
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.ts
index 641e68d2a3..e3f0d260ad 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
@@ -17,6 +17,7 @@ import {
normalizeProviderText,
parseExpiresIn,
parseGrantedScopes,
+ parseTokenResponse,
requestToken,
validateCallbackIssuer,
withTokenCompatibility
@@ -429,6 +430,16 @@ describe("token requests", () => {
});
});
+describe("token types", () => {
+ test.each(["Bearer", "bearer", "user", "N_A", undefined])("a %s token is used as a bearer token", (tokenType) => {
+ expect(parseTokenResponse({ access_token: "xoxp-1", token_type: tokenType })?.accessToken).toBe("xoxp-1");
+ });
+
+ test.each(["DPoP", "mac", "PoP"])("a %s token is refused, since it needs proof the proxy can't give", (tokenType) => {
+ expect(parseTokenResponse({ access_token: "at", token_type: tokenType })).toBeNull();
+ });
+});
+
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 �");
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.ts
index 13c984369f..1a9b5f3dfc 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
@@ -122,12 +122,14 @@ const parseTokenBody = (contentType: string, body: string): Record<string, unkno
return null;
};
+// RFC 6749 appendix A: client IDs, client secrets and tokens are all 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; the client 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_VSCHAR_PATTERN = new RE2(/^[\x20-\x7e]+$/);
+
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);
+ typeof value === "string" && value.length <= MAX_TOKEN_LENGTH && OAUTH_VSCHAR_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
@@ -158,14 +160,19 @@ export const parseGrantedScopes = (
return { scopes: splitScopes(scope), commaSeparated: false };
};
+const PROOF_OF_POSSESSION_TOKEN_TYPES = new Set(["dpop", "mac", "pop"]);
+
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;
+ // RFC 6749 section 7.1 lets a server name its own token types, and some name bearer tokens differently (Slack
+ // sends "user"). Only proof-of-possession tokens are refused, since they need proof the proxy can't give.
+ if (typeof body.token_type === "string" && PROOF_OF_POSSESSION_TOKEN_TYPES.has(body.token_type.toLowerCase())) {
+ return null;
+ }
const refreshToken = isUsableToken(body.refresh_token) ? body.refresh_token : undefined;
const { scopes, commaSeparated } = parseGrantedScopes(body.scope, requestedScopes);
@@ -330,7 +337,7 @@ export const requestToken = async ({
return {
ok: false,
errorCode: null,
- message: `'${host}' returned a token Infisical can't use (it must be a bearer token of printable characters).`,
+ message: `'${host}' returned a token Infisical can't use (it must be printable text that works as a bearer token).`,
resourceDropped: !withResource
};
}
@@ -356,6 +363,22 @@ export const requestToken = async ({
return result;
};
+// Refresh errors that mean the login is gone for good, so retrying on every poll only repeats the refusal. The
+// client codes mean the server dropped the registered client (the MCP SDK starts over on invalid_client too); the
+// rest are providers' own names for a dead refresh token.
+const DEAD_LOGIN_ERROR_CODES = new Set([
+ "invalid_grant",
+ "invalid_client",
+ "unauthorized_client",
+ "bad_refresh_token", // GitHub
+ "invalid_refresh_token", // Slack
+ "token_revoked", // Slack
+ "token_expired" // Slack
+]);
+
+export const isDeadLoginError = (errorCode: string | null) =>
+ errorCode !== null && DEAD_LOGIN_ERROR_CODES.has(errorCode);
+
export const exchangeAuthorizationCode = (
args: Omit<Parameters<typeof requestToken>[0], "params"> & { code: string; codeVerifier: string; redirectUri: string }
) =>
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.ts
index b424e05517..874ee5e61c 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
@@ -31,7 +31,7 @@ import {
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 { getServiceServerUrl } from "../agent-vault/agent-vault-service-type-fns";
import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";
import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";
import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";
@@ -582,7 +582,7 @@ export const agentVaultProxyServiceFactory = ({
// 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
+ serverUrl: getServiceServerUrl(row.config)
}
})
.then(({ credential }) => {
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
index ca30f07355..d374372847 100644
--- a/backend/src/ee/services/agent-vault/CLAUDE.md
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -255,8 +255,10 @@ 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.
+ in `encryptedCredential`. Each service has its own client, used only with the issuer it was registered at.
+ Reauthorizing registers a fresh client, since the server may have dropped the old one and the sign-in would then
+ die on its page; only a client entered by hand is kept, and the stored one is the fallback when registration
+ fails. Scopes carry over only at the same issuer.
- **Refresh writes the row, which no other credential does, so it races admin edits.** A refresh is a
compare-and-swap on `encryptedCredential` and a jsonb merge of only the token keys, so an admin who reauthorized
meanwhile keeps the newer tokens. An admin edit that keeps the tokens never writes `credentialConfig`, so it
@@ -285,11 +287,16 @@ code exchange and refresh; the proxy only ever receives the access token.
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.
+ that service a stale token and a `lastError`. A refresh error that means the login is dead (`invalid_grant`, a
+ dropped client, providers' own revoked or expired refresh token codes: `DEAD_LOGIN_ERROR_CODES`) moves the service
+ to needs reauthorization, so it isn't retried every poll. Any token type but a proof-of-possession one (DPoP, MAC,
+ PoP) is sent as a bearer token, since servers may name their own (Slack's is `user`).
- **Both proxy calls answer well inside the proxy's 15 second timeout.** Resolve waits 4 seconds in total for its
- refreshes and sends the stored token for any still running, which finish in the background. 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.
+ refreshes and sends the stored token for any still running, which finish in the background. Token requests (the
+ `invalid_target` retry included) share one 7 second budget. Resolve's refresh waits about 3 seconds for another's
+ lock; the proxy's refresh after a 401 waits about 10, so it outlasts the holder and gets the new token rather than
+ the rejected one. Either then answers with what is stored, and a waiter whose holder failed spends only the time
+ left before 13 seconds on its own request. Keep that under the proxy's timeout.
- **Neither refreshes nor resolve are audited.** Connect and reauthorize are recorded by the service create and
update events, which carry `oauthIssuer` and `oauthScopes`.
- **Non-conforming servers are supported through fallbacks**, each recorded in `compatibility`. A fallback may
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-type-fns.test.ts
similarity index 99%
rename from backend/src/ee/services/agent-vault/agent-vault-service-types.test.ts
rename to backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts
index ab8bea022e..c0def8cf2c 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-service-types.test.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts
@@ -10,7 +10,7 @@ import {
deriveMcpHostPattern,
findUnsupportedServiceFields,
resolveServiceHostPattern
-} from "./agent-vault-service-types";
+} from "./agent-vault-service-type-fns";
const http = AGENT_VAULT_SERVICE_TYPES[AgentVaultServiceType.Http];
const mcp = AGENT_VAULT_SERVICE_TYPES[AgentVaultServiceType.Mcp];
diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-types.ts b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts
similarity index 97%
rename from backend/src/ee/services/agent-vault/agent-vault-service-types.ts
rename to backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts
index f757e7e9aa..5fed32657a 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-service-types.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts
@@ -90,6 +90,10 @@ export type TAgentVaultServiceConfig =
| TAgentVaultMcpServiceConfig
| { [K in keyof TAgentVaultMcpServiceConfig]?: never };
+// The server an OAuth token is pinned to: a token is only ever sent to the server URL it was refreshed for.
+export const getServiceServerUrl = (config: unknown): string | null =>
+ (config as TAgentVaultServiceConfig | null)?.serverUrl ?? null;
+
export type TAgentVaultServiceTypeDefinition = {
type: AgentVaultServiceType;
label: string;
diff --git a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
index 4a40ae9614..bb07a5c294 100644
--- a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
@@ -25,7 +25,7 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
-import { AgentVaultOAuthStatus } from "@app/hooks/api/agentVault";
+import { AgentVaultOauthStatus } from "@app/hooks/api/agentVault";
import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
import {
@@ -47,14 +47,14 @@ const hostOf = (serverUrl: string) => {
};
const OAUTH_STATUS_VARIANTS = {
- [AgentVaultOAuthStatus.Connected]: "success",
- [AgentVaultOAuthStatus.NeedsReauthorization]: "danger",
- [AgentVaultOAuthStatus.NeedsAdditionalScopes]: "warning"
+ [AgentVaultOauthStatus.Connected]: "success",
+ [AgentVaultOauthStatus.NeedsReauthorization]: "danger",
+ [AgentVaultOauthStatus.NeedsAdditionalScopes]: "warning"
} as const;
-export const OAuthStatusBadge = ({ status }: { status: AgentVaultOAuthStatus }) => (
+export const OAuthStatusBadge = ({ status }: { status: AgentVaultOauthStatus }) => (
<Badge variant={OAUTH_STATUS_VARIANTS[status]}>
- {status === AgentVaultOAuthStatus.Connected ? <CheckIcon /> : <CircleAlertIcon />}
+ {status === AgentVaultOauthStatus.Connected ? <CheckIcon /> : <CircleAlertIcon />}
{OAUTH_STATUS_LABELS[status]}
</Badge>
);
@@ -212,7 +212,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
const isProblem =
state.status === "failed" ||
- (stored && stored.status !== AgentVaultOAuthStatus.Connected && !isNewlyAuthorized);
+ (stored && stored.status !== AgentVaultOauthStatus.Connected && !isNewlyAuthorized);
let authorizeLabel = `Authorize with ${host}`;
if (state.status === "failed") authorizeLabel = "Try Again";
@@ -267,22 +267,22 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
const authorizedAt = stored.authorizedAt ? new Date(stored.authorizedAt) : null;
let head: ReactNode;
- if (stored.status === AgentVaultOAuthStatus.NeedsReauthorization) {
+ if (stored.status === AgentVaultOauthStatus.NeedsReauthorization) {
head = (
<Status
icon={<CircleXIcon />}
tone="danger"
- title={OAUTH_STATUS_LABELS[AgentVaultOAuthStatus.NeedsReauthorization]}
+ title={OAUTH_STATUS_LABELS[AgentVaultOauthStatus.NeedsReauthorization]}
>
{host} no longer accepts this authorization.
</Status>
);
- } else if (stored.status === AgentVaultOAuthStatus.NeedsAdditionalScopes) {
+ } else if (stored.status === AgentVaultOauthStatus.NeedsAdditionalScopes) {
head = (
<Status
icon={<CircleAlertIcon />}
tone="warning"
- title={OAUTH_STATUS_LABELS[AgentVaultOAuthStatus.NeedsAdditionalScopes]}
+ title={OAUTH_STATUS_LABELS[AgentVaultOauthStatus.NeedsAdditionalScopes]}
>
An agent needed scopes this authorization doesn&apos;t have.
</Status>
@@ -311,7 +311,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
head,
details: (
<div className="flex flex-col gap-2">
- {stored.lastError && stored.status !== AgentVaultOAuthStatus.NeedsReauthorization && (
+ {stored.lastError && stored.status !== AgentVaultOauthStatus.NeedsReauthorization && (
<Tooltip>
<TooltipTrigger asChild>
<span
@@ -320,7 +320,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
className={twMerge(
"flex w-fit items-center gap-1.5 text-xs",
// Under a yellow status, Reauthorize already fixes this, so it shouldn't compete with it.
- stored.status === AgentVaultOAuthStatus.NeedsAdditionalScopes
+ stored.status === AgentVaultOauthStatus.NeedsAdditionalScopes
? "text-muted"
: "text-danger"
)}
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
index 1fa4227aac..c290015c0d 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import {
AgentVaultCredentialType,
AgentVaultMcpTransport,
- AgentVaultOAuthStatus,
+ AgentVaultOauthStatus,
AgentVaultServiceType
} from "@app/hooks/api/agentVault";
import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
@@ -56,7 +56,7 @@ const storedOAuthService = (serverUrl = SERVER_URL) =>
allowedPathPrefixes: null,
credential: {
type: AgentVaultCredentialType.OAuth,
- status: AgentVaultOAuthStatus.NeedsReauthorization,
+ status: AgentVaultOauthStatus.NeedsReauthorization,
issuer: "https://mcp.linear.app",
grantedScopes: ["read"],
requiredScopes: [],
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
index 56e7f3ba7c..b02ceeb4b8 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
@@ -7,12 +7,12 @@ import {
AgentVaultCredentialType,
AgentVaultHttpMethod,
AgentVaultMcpTransport,
- AgentVaultOAuthStatus,
+ AgentVaultOauthStatus,
AgentVaultServiceType,
AgentVaultSubstitutionSurface
} from "@app/hooks/api/agentVault";
import {
- TAgentVaultOAuthCredentialSummary,
+ TAgentVaultOauthCredentialSummary,
TAgentVaultService
} from "@app/hooks/api/agentVault/types";
import { slugSchema } from "@app/lib/schemas";
@@ -43,10 +43,10 @@ export const HTTP_CREDENTIAL_TYPES = [
AgentVaultCredentialType.Passthrough
];
-export const OAUTH_STATUS_LABELS: Record<AgentVaultOAuthStatus, string> = {
- [AgentVaultOAuthStatus.Connected]: "Connected",
- [AgentVaultOAuthStatus.NeedsReauthorization]: "Needs Reauthorization",
- [AgentVaultOAuthStatus.NeedsAdditionalScopes]: "Needs Additional Scopes"
+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> = {
@@ -194,7 +194,7 @@ export const newOAuthAuthorizationId = (form: TOAuthFormState) =>
export const storedOAuthCredential = (
service: TAgentVaultService | null | undefined,
serverUrl: string
-): TAgentVaultOAuthCredentialSummary | null =>
+): TAgentVaultOauthCredentialSummary | null =>
service?.type === AgentVaultServiceType.Mcp &&
service.credential.type === AgentVaultCredentialType.OAuth &&
service.serverUrl === serverUrl.trim()
diff --git a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts
index 5a44e9ca62..f2fe1ecced 100644
--- a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts
+++ b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts
@@ -2,13 +2,13 @@ import { useCallback, useEffect, useRef, useState } from "react";
import axios from "axios";
import {
- AgentVaultOAuthAuthorizationStatus,
- useCreateAgentVaultOAuthAuthorization,
- useGetAgentVaultOAuthAuthorization
+ AgentVaultOauthAuthorizationStatus,
+ useCreateAgentVaultOauthAuthorization,
+ useGetAgentVaultOauthAuthorization
} from "@app/hooks/api/agentVault";
import {
- TAgentVaultOAuthAuthorization,
- TCreateAgentVaultOAuthAuthorizationDTO
+ TAgentVaultOauthAuthorization,
+ TCreateAgentVaultOauthAuthorizationDTO
} from "@app/hooks/api/agentVault/types";
const POLL_TIMEOUT_MS = 5 * 60 * 1000;
@@ -19,7 +19,7 @@ export type TOAuthAuthorizeState =
| { status: "idle" }
| { status: "starting" }
| { status: "pending" }
- | { status: "authorized"; authorization: TAgentVaultOAuthAuthorization }
+ | { status: "authorized"; authorization: TAgentVaultOauthAuthorization }
| { status: "failed"; message: string };
const serverMessage = (error: unknown) => {
@@ -31,9 +31,9 @@ const serverMessage = (error: unknown) => {
export const useOAuthAuthorize = ({
onAuthorized
}: {
- onAuthorized: (authorization: TAgentVaultOAuthAuthorization) => void;
+ onAuthorized: (authorization: TAgentVaultOauthAuthorization) => void;
}) => {
- const createAuthorization = useCreateAgentVaultOAuthAuthorization();
+ const createAuthorization = useCreateAgentVaultOauthAuthorization();
const [state, setState] = useState<TOAuthAuthorizeState>({ status: "idle" });
const [isClientRequired, setIsClientRequired] = useState(false);
const [redirectUri, setRedirectUri] = useState<string | null>(null);
@@ -43,7 +43,7 @@ export const useOAuthAuthorize = ({
id: string;
attempt: number;
} | null>(null);
- const { data: authorization, error: authorizationError } = useGetAgentVaultOAuthAuthorization(
+ const { data: authorization, error: authorizationError } = useGetAgentVaultOauthAuthorization(
pendingAuthorization?.id ?? ""
);
@@ -77,13 +77,13 @@ export const useOAuthAuthorize = ({
return;
}
if (!authorization) return;
- if (authorization.status === AgentVaultOAuthAuthorizationStatus.Authorized) {
+ if (authorization.status === AgentVaultOauthAuthorizationStatus.Authorized) {
stop();
setState({ status: "authorized", authorization });
onAuthorizedRef.current(authorization);
return;
}
- if (authorization.status === AgentVaultOAuthAuthorizationStatus.Failed) {
+ if (authorization.status === AgentVaultOauthAuthorizationStatus.Failed) {
fail(authorization.error ?? "The server refused the authorization.");
}
}, [pendingAuthorization, authorization, authorizationError, fail, stop]);
@@ -101,7 +101,7 @@ export const useOAuthAuthorize = ({
// 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) => {
+ (params: TCreateAgentVaultOauthAuthorizationDTO) => {
stop();
const attempt = attemptRef.current;
diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.ts
index b353500498..78791f01ce 100644
--- a/frontend/src/hooks/api/agentVault/enums.ts
+++ b/frontend/src/hooks/api/agentVault/enums.ts
@@ -32,13 +32,13 @@ export enum AgentVaultCredentialType {
OAuth = "oauth"
}
-export enum AgentVaultOAuthStatus {
+export enum AgentVaultOauthStatus {
Connected = "connected",
NeedsReauthorization = "needs-reauthorization",
NeedsAdditionalScopes = "needs-additional-scopes"
}
-export enum AgentVaultOAuthAuthorizationStatus {
+export enum AgentVaultOauthAuthorizationStatus {
Pending = "pending",
Authorized = "authorized",
Failed = "failed"
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index 5ce907fd7f..ddcd99d6b2 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -15,17 +15,17 @@ import {
TAgentVaultGrantedMember,
TAgentVaultMemberWriteResult,
TAgentVaultMintedSession,
- TAgentVaultOAuthAuthorization,
+ TAgentVaultOauthAuthorization,
TAgentVaultProxy,
TAgentVaultProxySettingsDTO,
TAgentVaultService,
TAgentVaultSessionLogSettings,
TAgentVaultVariable,
TAgentVaultWrittenMember,
- TCompleteAgentVaultOAuthAuthorizationDTO,
+ TCompleteAgentVaultOauthAuthorizationDTO,
TCreateAgentVaultAccessBundleDTO,
- TCreateAgentVaultOAuthAuthorizationDTO,
- TCreateAgentVaultOAuthAuthorizationResponse,
+ TCreateAgentVaultOauthAuthorizationDTO,
+ TCreateAgentVaultOauthAuthorizationResponse,
TCreateAgentVaultServiceDTO,
TCreateAgentVaultSessionDTO,
TCreateAgentVaultVariableDTO,
@@ -459,13 +459,13 @@ export const useRevealAgentVaultVariableValue = () =>
}
});
-export const useCreateAgentVaultOAuthAuthorization = () =>
+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>(
+ mutationFn: async (params: TCreateAgentVaultOauthAuthorizationDTO) => {
+ const { data } = await apiRequest.post<TCreateAgentVaultOauthAuthorizationResponse>(
"/api/v1/agent-vault/oauth/authorizations",
params
);
@@ -473,15 +473,15 @@ export const useCreateAgentVaultOAuthAuthorization = () =>
}
});
-export const useCompleteAgentVaultOAuthAuthorization = () =>
+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 }>(
+ }: TCompleteAgentVaultOauthAuthorizationDTO) => {
+ const { data } = await apiRequest.post<{ authorization: TAgentVaultOauthAuthorization }>(
`/api/v1/agent-vault/oauth/authorizations/${encodeURIComponent(authorizationId)}/complete`,
params
);
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index 9e179e8932..d7974cd1d1 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -6,7 +6,7 @@ import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
import { VARIABLE_KEY_MAX_LENGTH, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";
-import { AgentVaultMemberType, AgentVaultOAuthAuthorizationStatus } from "./enums";
+import { AgentVaultMemberType, AgentVaultOauthAuthorizationStatus } from "./enums";
import {
createSessionLogChunkCache,
decryptSessionLogPage,
@@ -23,7 +23,7 @@ import {
TAgentVaultAccessBundleListItem,
TAgentVaultDecryptedSessionLogPage,
TAgentVaultMember,
- TAgentVaultOAuthAuthorization,
+ TAgentVaultOauthAuthorization,
TAgentVaultProductActor,
TAgentVaultProductMember,
TAgentVaultProductMemberOf,
@@ -48,11 +48,11 @@ export const fetchAgentVaultProjectId = async () => {
return data.projectId;
};
-export const fetchAgentVaultOAuthAuthorization = async (
+export const fetchAgentVaultOauthAuthorization = async (
authorizationId: string,
signal?: AbortSignal
) => {
- const { data } = await apiRequest.get<{ authorization: TAgentVaultOAuthAuthorization }>(
+ const { data } = await apiRequest.get<{ authorization: TAgentVaultOauthAuthorization }>(
`/api/v1/agent-vault/oauth/authorizations/${encodeURIComponent(authorizationId)}`,
{ signal }
);
@@ -128,19 +128,19 @@ export const agentVaultKeys = {
[...agentVaultKeys.sessions(orgId), sessionId, "logs-live", range ?? {}] as const
};
-export const useGetAgentVaultOAuthAuthorization = (authorizationId: string) => {
+export const useGetAgentVaultOauthAuthorization = (authorizationId: string) => {
const { currentOrg } = useOrganization();
return useQuery({
queryKey: agentVaultKeys.oauthAuthorization(currentOrg.id, authorizationId),
- queryFn: ({ signal }) => fetchAgentVaultOAuthAuthorization(authorizationId, signal),
+ 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)
+ (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.
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index a976391a5a..6539c15395 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -3,8 +3,8 @@ import {
AgentVaultHttpMethod,
AgentVaultMcpTransport,
AgentVaultMemberType,
- AgentVaultOAuthAuthorizationStatus,
- AgentVaultOAuthStatus,
+ AgentVaultOauthAuthorizationStatus,
+ AgentVaultOauthStatus,
AgentVaultServiceType,
AgentVaultSessionLogDecision,
AgentVaultSessionScope,
@@ -14,9 +14,9 @@ import {
AgentVaultVariableReferenceField
} from "./enums";
-export type TAgentVaultOAuthCredentialSummary = {
+export type TAgentVaultOauthCredentialSummary = {
type: AgentVaultCredentialType.OAuth;
- status: AgentVaultOAuthStatus;
+ status: AgentVaultOauthStatus;
issuer: string;
grantedScopes: string[];
requiredScopes: string[];
@@ -30,7 +30,7 @@ export type TAgentVaultCredentialSummary =
| { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }
| { type: AgentVaultCredentialType.Basic }
| { type: AgentVaultCredentialType.Passthrough }
- | TAgentVaultOAuthCredentialSummary;
+ | TAgentVaultOauthCredentialSummary;
export type TAgentVaultCredentialInput =
| {
@@ -42,7 +42,7 @@ export type TAgentVaultCredentialInput =
| { type: AgentVaultCredentialType.Basic; username: string; password: string }
| { type: AgentVaultCredentialType.Passthrough };
-export type TAgentVaultOAuthCredentialInput = {
+export type TAgentVaultOauthCredentialInput = {
type: AgentVaultCredentialType.OAuth;
authorizationId: string;
};
@@ -56,7 +56,7 @@ export type TAgentVaultCredentialUpdate =
}
| { type: AgentVaultCredentialType.Basic; username?: string; password?: string }
| { type: AgentVaultCredentialType.Passthrough }
- | TAgentVaultOAuthCredentialInput;
+ | TAgentVaultOauthCredentialInput;
export type TAgentVaultCustomHeaderSummary = { id: string; name: string; prefix: string };
@@ -311,7 +311,7 @@ export type TCreateAgentVaultServiceDTO =
transport: AgentVaultMcpTransport;
credential:
| Extract<TAgentVaultCredentialInput, { type: AgentVaultCredentialType.Bearer }>
- | TAgentVaultOAuthCredentialInput;
+ | TAgentVaultOauthCredentialInput;
customHeaders?: TAgentVaultCustomHeaderInput[];
};
@@ -329,14 +329,14 @@ export type TUpdateAgentVaultServiceDTO = {
substitutions?: TAgentVaultSubstitutionInput[];
};
-export type TAgentVaultOAuthAuthorization = {
+export type TAgentVaultOauthAuthorization = {
id: string;
- status: AgentVaultOAuthAuthorizationStatus;
+ status: AgentVaultOauthAuthorizationStatus;
error: string | null;
scopes: string[];
};
-export type TCreateAgentVaultOAuthAuthorizationDTO = {
+export type TCreateAgentVaultOauthAuthorizationDTO = {
accessBundleId: string;
serverUrl: string;
serviceId?: string;
@@ -344,7 +344,7 @@ export type TCreateAgentVaultOAuthAuthorizationDTO = {
clientSecret?: string;
};
-export type TCreateAgentVaultOAuthAuthorizationResponse = {
+export type TCreateAgentVaultOauthAuthorizationResponse = {
registrationRequired: boolean;
// False when the server answered but advertises no OAuth, which usually means a wrong URL.
oauthAdvertised: boolean;
@@ -353,13 +353,13 @@ export type TCreateAgentVaultOAuthAuthorizationResponse = {
registrationError: string | null;
authorization: {
id: string;
- status: AgentVaultOAuthAuthorizationStatus;
+ status: AgentVaultOauthAuthorizationStatus;
authorizeUrl: string;
scopes: string[];
} | null;
};
-export type TCompleteAgentVaultOAuthAuthorizationDTO = {
+export type TCompleteAgentVaultOauthAuthorizationDTO = {
authorizationId: string;
state: string;
code?: string;
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
index b58bc7a7e1..6f8e664c2b 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
@@ -60,7 +60,7 @@ import {
} from "@app/components/v3";
import {
AgentVaultCredentialType,
- AgentVaultOAuthStatus,
+ AgentVaultOauthStatus,
AgentVaultServiceType,
useDeleteAgentVaultService
} from "@app/hooks/api/agentVault";
@@ -310,7 +310,7 @@ export const ServicesCard = ({
<ServiceIcon hostPattern={service.hostPattern} />
{service.name}
{service.credential.type === AgentVaultCredentialType.OAuth &&
- service.credential.status !== AgentVaultOAuthStatus.Connected && (
+ service.credential.status !== AgentVaultOauthStatus.Connected && (
<OAuthStatusBadge status={service.credential.status} />
)}
</div>
diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx
index 4feb5b8b8b..684d6f27a4 100644
--- a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx
@@ -16,8 +16,8 @@ import {
CardTitle
} from "@app/components/v3";
import {
- AgentVaultOAuthAuthorizationStatus,
- useCompleteAgentVaultOAuthAuthorization
+ AgentVaultOauthAuthorizationStatus,
+ useCompleteAgentVaultOauthAuthorization
} from "@app/hooks/api/agentVault";
const CLOSE_AFTER_SUCCESS_MS = 1000;
@@ -40,7 +40,7 @@ const failureMessage = (error: unknown) => {
export const AgentVaultOAuthCallbackPage = () => {
const search = useSearch({ from: "/_authenticate/agent-vault/oauth/callback" });
- const completeAuthorization = useCompleteAgentVaultOAuthAuthorization();
+ const completeAuthorization = useCompleteAgentVaultOauthAuthorization();
const [outcome, setOutcome] = useState<TOutcome>({ status: "working" });
const hasStarted = useRef(false);
@@ -62,7 +62,7 @@ export const AgentVaultOAuthCallbackPage = () => {
completeAuthorization
.mutateAsync({ authorizationId, state, code, iss, error, errorDescription })
.then((authorization) => {
- if (authorization.status === AgentVaultOAuthAuthorizationStatus.Authorized) {
+ if (authorization.status === AgentVaultOauthAuthorizationStatus.Authorized) {
setOutcome({ status: "authorized" });
return;
}
diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.ts b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.ts
index 66af92dbfd..4c02d5bb3e 100644
--- a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.ts
+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { AgentVaultOAuthCallbackQueryParamsSchema } from "./callbackSchema";
+import { AgentVaultOauthCallbackQueryParamsSchema } from "./callbackSchema";
describe("OAuth callback input", () => {
it("keeps the UUID state and bounded values from a valid provider redirect", () => {
@@ -9,7 +9,7 @@ describe("OAuth callback input", () => {
code: "code",
iss: "https://provider.example.com"
};
- expect(AgentVaultOAuthCallbackQueryParamsSchema.parse(params)).toEqual(params);
+ expect(AgentVaultOauthCallbackQueryParamsSchema.parse(params)).toEqual(params);
});
it.each([
@@ -19,11 +19,11 @@ describe("OAuth callback input", () => {
"",
"x".repeat(257)
])("drops a state that could select another API path: %s", (state) => {
- expect(AgentVaultOAuthCallbackQueryParamsSchema.parse({ state }).state).toBeUndefined();
+ expect(AgentVaultOauthCallbackQueryParamsSchema.parse({ state }).state).toBeUndefined();
});
it("drops provider fields exceeding the API's bounds", () => {
- const parsed = AgentVaultOAuthCallbackQueryParamsSchema.parse({
+ const parsed = AgentVaultOauthCallbackQueryParamsSchema.parse({
code: "x".repeat(4097),
iss: "x".repeat(2049),
error: "x".repeat(1025),
diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.ts b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.ts
index 36e844d836..c2830dfe6f 100644
--- a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.ts
+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/callbackSchema.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
const authorizationIdSchema = z.string().uuid();
-export const AgentVaultOAuthCallbackQueryParamsSchema = z.object({
+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
diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsx
index de9221e2d4..e8dadba71a 100644
--- a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/route.tsx
@@ -2,9 +2,9 @@ import { createFileRoute } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { AgentVaultOAuthCallbackPage } from "./AgentVaultOAuthCallbackPage";
-import { AgentVaultOAuthCallbackQueryParamsSchema } from "./callbackSchema";
+import { AgentVaultOauthCallbackQueryParamsSchema } from "./callbackSchema";
export const Route = createFileRoute("/_authenticate/agent-vault/oauth/callback")({
component: AgentVaultOAuthCallbackPage,
- validateSearch: zodValidator(AgentVaultOAuthCallbackQueryParamsSchema)
+ validateSearch: zodValidator(AgentVaultOauthCallbackQueryParamsSchema)
});