Skip to content

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

use RFC errro format

Thiago Araujo da Silva120c2eadd735
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 9c278eda3d..9efada9f79 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -250,6 +250,43 @@ leaves it unset only for `delegation: "full"`; `getDelegatedOauthScopes` reads a
narrowing". Matching full delegation positively is what makes a dropped claim fail closed instead of
quietly promoting the token.
+**The token endpoint answers failures in RFC 6749 terms, not the house envelope.** `POST /v1/oauth/token`
+is the one route that does, because its contract is the RFC rather than our API conventions: generic OAuth
+client libraries branch on the `error` code, and `{ statusCode, message, error: "UnauthorizedError" }`
+leaves them unable to tell "rotate the client secret" from "re-authenticate the user" from "retry later".
+`OauthTokenError` (`oauth-token-error.ts`) carries the code, derives the status from it (400 for
+everything, 401 for `invalid_client`, 500 for `server_error`), and the shared error handler renders
+`{ error, error_description }` for it. When extending this:
+- **The handler's `try`/`catch` is the endpoint's only exit**, and every `return` inside it is awaited —
+ a bare `return promise` would resolve outside the `catch` and escape in the house envelope.
+- **The code a rejected grant earns depends on the grant.** RFC 8693 section 2.2.2 overrides RFC 6749 for
+ token exchange, and not in the direction you would guess: a `subject_token` "invalid for any reason, or
+ unacceptable based on policy" MUST be `invalid_request`, where the same class of failure on the redirect
+ and refresh grants is `invalid_grant`. So the exchange collapses "your token is bad" into "your request
+ is bad", and never returns `invalid_grant` at all. `REJECTED_GRANT_CODE_BY_GRANT_TYPE` holds this, and
+ `toOauthTokenError` takes the grant type to pick it. Client authentication stays `invalid_client` under
+ both, because there it is the client that failed rather than the token.
+- **`toOauthTokenError` defaults by error class**, never by message text: `UnauthorizedError` means a grant
+ we won't act on (the grant-dependent code above), `BadRequestError` a request we can't use
+ (`invalid_request`), and anything else is a bug or an outage, so it becomes a generic `server_error`
+ whose response carries no detail and whose original is logged. Throw `OauthTokenError` directly wherever
+ that default is wrong:
+ client authentication (`invalid_client`), a grant the client doesn't hold (`unauthorized_client`), a
+ mismatched redirect URI or PKCE verifier (`invalid_grant`, not `invalid_request`), the unsupported
+ `scope` (`invalid_scope`) and `audience`/`resource` (`invalid_target`) parameters, and org
+ misconfiguration or identity provider outages (`server_error`, since the request was fine).
+ `unauthorized_client` and `invalid_scope` are deliberate reads of RFC 8693's blanket "the request itself
+ is not valid" clause: both are the more specific RFC 6749 code for what actually went wrong, and worth
+ more to a caller than a third flavour of `invalid_request`. `invalid_target` is RFC 8693's own SHOULD.
+- **The route sets `attachValidation`** so a schema failure reaches the handler instead of being answered
+ by Fastify in the house envelope. An unrecognized `grant_type` earns `unsupported_grant_type`.
+- **`error_description` is sanitized, not trusted.** RFC 6749 section 5.2 allows only printable ASCII
+ without `"` or `\`, and our messages are written for humans; `toErrorDescription` normalises and bounds
+ them at the render boundary so no throw site has to remember.
+- Messages shared with a management route (the OIDC-config checks) take an error factory rather than
+ throwing, since registering an application and exchanging a token owe the same explanation in different
+ envelopes.
+
**Token exchange trusts the org's OIDC SSO config, not per-client configuration**
(`oauth-token-exchange-fns.ts`), so the issuers that can vouch for a user through exchange are exactly the
ones that can already log them in. The one per-application field is `tokenExchangeAudience`, and it does
diff --git a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts
index 374e8de7af..60155ce0d9 100644
--- a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts
+++ b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts
@@ -36,11 +36,11 @@ const consent = async (body: Record<string, string>) =>
body
});
-const postToken = async (body: Record<string, string>) =>
+const postToken = async (body: Record<string, string>, headers: Record<string, string> = {}) =>
testServer.inject({
method: "POST",
url: "/api/v1/oauth/token",
- headers: { "content-type": "application/x-www-form-urlencoded" },
+ headers: { "content-type": "application/x-www-form-urlencoded", ...headers },
payload: new URLSearchParams(body).toString()
});
@@ -220,18 +220,53 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {
...overrides
});
+ // RFC 6749 section 5.2 and RFC 8693 section 2.2.2: the token endpoint answers with an `error` code
+ // from a fixed list plus an `error_description`, never the house `{ statusCode, message, error }`
+ // envelope, because generic client libraries branch on that code.
+ const expectOauthError = (
+ res: { statusCode: number; payload: string },
+ statusCode: number,
+ code: string,
+ descriptionFragment: string
+ ) => {
+ expect(res.statusCode).toBe(statusCode);
+
+ const body = JSON.parse(res.payload) as { error?: string; error_description?: string; message?: string };
+ expect(body.error).toBe(code);
+ expect(body.error_description).toContain(descriptionFragment);
+ expect(body.message).toBeUndefined();
+ };
+
test("rejects invalid client credentials", async () => {
const res = await postToken(exchangeBody({ client_secret: "not-the-secret" }));
- expect(res.statusCode).toBe(401);
- expect(res.payload).toContain("Invalid OAuth client credentials");
+ expectOauthError(res, 401, "invalid_client", "Invalid OAuth client credentials");
+ });
+
+ // RFC 6749 section 5.2 requires a challenge for the scheme the client authenticated with.
+ test("challenges a basic-auth client whose credentials are rejected", async () => {
+ const body = exchangeBody();
+ delete (body as Record<string, string>).client_id;
+ delete (body as Record<string, string>).client_secret;
+
+ const res = await postToken(body, {
+ authorization: `Basic ${Buffer.from(`${clientId}:not-the-secret`).toString("base64")}`
+ });
+
+ expectOauthError(res, 401, "invalid_client", "Invalid OAuth client credentials");
+ expect(res.headers["www-authenticate"]).toContain("Basic");
});
test("rejects a client that is not registered for the exchange grant", async () => {
const res = await postToken(exchangeBody());
- expect(res.statusCode).toBe(401);
- expect(res.payload).toContain(TOKEN_EXCHANGE_GRANT);
+ expectOauthError(res, 400, "unauthorized_client", TOKEN_EXCHANGE_GRANT);
+ });
+
+ test("rejects an unrecognized grant type", async () => {
+ const res = await postToken(exchangeBody({ grant_type: "client_credentials" }));
+
+ expectOauthError(res, 400, "unsupported_grant_type", "grant_type");
});
test("requires a subject token", async () => {
@@ -240,8 +275,7 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {
const res = await postToken(body);
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("subject_token");
+ expectOauthError(res, 400, "invalid_request", "subject_token");
});
test("requires a subject token type", async () => {
@@ -250,15 +284,13 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {
const res = await postToken(body);
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("subject_token_type");
+ expectOauthError(res, 400, "invalid_request", "subject_token_type");
});
test("rejects an unsupported requested token type", async () => {
const res = await postToken(exchangeBody({ requested_token_type: OauthTokenType.IdToken }));
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("requested_token_type");
+ expectOauthError(res, 400, "invalid_request", "requested_token_type");
});
// RFC 8693 allows both, but this grant has no scopes and its audience is fixed per application, so
@@ -266,15 +298,13 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {
test("rejects a scope parameter rather than ignoring it", async () => {
const res = await postToken(exchangeBody({ scope: "secrets:read" }));
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("'scope' parameter is not supported");
+ expectOauthError(res, 400, "invalid_scope", "'scope' parameter is not supported");
});
test("rejects an audience parameter rather than ignoring it", async () => {
const res = await postToken(exchangeBody({ audience: "api://something-else" }));
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("not supported");
+ expectOauthError(res, 400, "invalid_target", "not supported");
});
// Ignoring these would answer a delegation request with an impersonation token, since the issued
@@ -282,15 +312,13 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {
test("rejects an actor token rather than ignoring it", async () => {
const res = await postToken(exchangeBody({ actor_token: "some.actor.jwt" }));
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("'actor_token'");
+ expectOauthError(res, 400, "invalid_request", "'actor_token'");
});
test("rejects an actor token type on its own", async () => {
const res = await postToken(exchangeBody({ actor_token_type: OauthTokenType.Jwt }));
- expect(res.statusCode).toBe(400);
- expect(res.payload).toContain("'actor_token'");
+ expectOauthError(res, 400, "invalid_request", "'actor_token'");
});
});
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index b0a585c86b..b91fcd8e1c 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -30,6 +30,7 @@ import {
rateLimitExceededCounter,
shouldRecordHighCardinalityMetrics
} from "@app/lib/telemetry/metrics";
+import { OauthTokenError, OauthTokenErrorCode, toErrorDescription } from "@app/services/oauth-client/oauth-token-error";
enum JWTErrors {
JwtExpired = "jwt expired",
@@ -75,6 +76,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
error instanceof ForbiddenRequestError ||
error instanceof PermissionBoundaryError ||
error instanceof ZodError ||
+ (error instanceof OauthTokenError && error.statusCode < HttpStatusCodes.InternalServerError) ||
error instanceof RateLimitError ||
error instanceof PolicyViolationError ||
(error instanceof ScimRequestError && error.status < 500) ||
@@ -187,7 +189,23 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
coreHttpErrorCounter.add(1, coreAttrs);
}
- if (error instanceof BadRequestError) {
+ // The OAuth token endpoint's error contract is RFC 6749 section 5.2, not the house envelope. See
+ // OauthTokenError; only that endpoint raises this, and it maps everything it can throw itself.
+ if (error instanceof OauthTokenError) {
+ // RFC 6749 section 5.2: a client that authenticated with the Authorization header must get a 401
+ // carrying a challenge for the scheme it used.
+ if (
+ error.oauthErrorCode === OauthTokenErrorCode.InvalidClient &&
+ req.headers.authorization?.toLowerCase().startsWith("basic ")
+ ) {
+ void res.header("WWW-Authenticate", 'Basic realm="Infisical", charset="UTF-8"');
+ }
+
+ void res.status(error.statusCode).send({
+ error: error.oauthErrorCode,
+ error_description: toErrorDescription(error.message)
+ });
+ } else if (error instanceof BadRequestError) {
void res.status(HttpStatusCodes.BadRequest).send({
reqId: req.id,
statusCode: HttpStatusCodes.BadRequest,
diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.ts
index 9d97a31784..588806cdd0 100644
--- a/backend/src/server/routes/v1/oauth-router.ts
+++ b/backend/src/server/routes/v1/oauth-router.ts
@@ -16,6 +16,7 @@ import {
OauthGrantType,
OauthTokenType
} from "@app/services/oauth-client/oauth-client-types";
+import { OauthTokenError, OauthTokenErrorCode, toOauthTokenError } from "@app/services/oauth-client/oauth-token-error";
const SanitizedOauthClientSchema = OauthClientsSchema.omit({ clientSecretHash: true });
@@ -61,6 +62,16 @@ const tokenExchangeIdpSatisfiesMfaSchema = z
"Declares that authentication at the identity provider satisfies this organization's MFA requirement. Required for token exchange in an organization that enforces MFA."
);
+// The zod validator compiler hands Fastify the raw ZodError, whose `message` is the whole issue list
+// stringified as JSON. Summarise it instead, so error_description names the offending fields.
+const describeValidationError = (error: Error) => {
+ if (!(error instanceof z.ZodError)) return error.message;
+
+ return error.issues
+ .map((issue) => (issue.path.length ? `${issue.path.join(".")}: ${issue.message}` : issue.message))
+ .join("; ");
+};
+
export const registerOAuthRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
@@ -428,6 +439,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {
config: {
rateLimit: authRateLimit
},
+ attachValidation: true,
schema: {
body: z.object({
grant_type: z.nativeEnum(OauthGrantType),
@@ -458,86 +470,110 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req, res) => {
- const basicAuth = parseBasicAuthHeader(req.headers.authorization);
- const clientId = basicAuth?.clientId ?? req.body.client_id;
- const clientSecret = basicAuth?.clientSecret ?? req.body.client_secret;
-
void res.header("Cache-Control", "no-store");
void res.header("Pragma", "no-cache");
- if (req.body.grant_type === OauthGrantType.AuthorizationCode) {
- if (!req.body.code) throw new BadRequestError({ message: "Missing authorization code" });
+ if (req.validationError) {
+ const grantType = (req.body as { grant_type?: unknown } | undefined)?.grant_type;
+ const isKnownGrantType =
+ typeof grantType === "string" && Object.values(OauthGrantType).includes(grantType as OauthGrantType);
- return server.services.oauthClient.exchangeToken({
- grantType: OauthGrantType.AuthorizationCode,
- code: req.body.code,
- redirectUri: req.body.redirect_uri,
- codeVerifier: req.body.code_verifier,
- clientId,
- clientSecret
+ throw new OauthTokenError({
+ code: isKnownGrantType ? OauthTokenErrorCode.InvalidRequest : OauthTokenErrorCode.UnsupportedGrantType,
+ message: isKnownGrantType
+ ? describeValidationError(req.validationError)
+ : `Unsupported 'grant_type'. Supported values are: ${Object.values(OauthGrantType).join(", ")}`
});
}
- if (req.body.grant_type === OauthGrantType.TokenExchange) {
- if (!req.body.subject_token) {
- throw new BadRequestError({ message: "Missing 'subject_token'" });
- }
-
- if (!req.body.subject_token_type) {
- throw new BadRequestError({ message: "Missing 'subject_token_type'" });
- }
+ const basicAuth = parseBasicAuthHeader(req.headers.authorization);
+ const clientId = basicAuth?.clientId ?? req.body.client_id;
+ const clientSecret = basicAuth?.clientSecret ?? req.body.client_secret;
- if (!ACCEPTED_SUBJECT_TOKEN_TYPES.includes(req.body.subject_token_type)) {
- throw new BadRequestError({
- message: `Unsupported 'subject_token_type'. Supported values are: ${ACCEPTED_SUBJECT_TOKEN_TYPES.join(", ")}`
+ try {
+ if (req.body.grant_type === OauthGrantType.AuthorizationCode) {
+ if (!req.body.code) throw new BadRequestError({ message: "Missing authorization code" });
+
+ return await server.services.oauthClient.exchangeToken({
+ grantType: OauthGrantType.AuthorizationCode,
+ code: req.body.code,
+ redirectUri: req.body.redirect_uri,
+ codeVerifier: req.body.code_verifier,
+ clientId,
+ clientSecret
});
}
- if (req.body.requested_token_type && req.body.requested_token_type !== OauthTokenType.AccessToken) {
- throw new BadRequestError({
- message: `Unsupported 'requested_token_type'. Only '${OauthTokenType.AccessToken}' can be issued.`
- });
- }
+ if (req.body.grant_type === OauthGrantType.TokenExchange) {
+ if (!req.body.subject_token) {
+ throw new BadRequestError({ message: "Missing 'subject_token'" });
+ }
- if (req.body.actor_token || req.body.actor_token_type) {
- throw new BadRequestError({
- message:
- "The 'actor_token' and 'actor_token_type' parameters are not supported. This grant issues a token that acts as the user in the subject token, and does not record the application as a separate acting party."
- });
- }
+ if (!req.body.subject_token_type) {
+ throw new BadRequestError({ message: "Missing 'subject_token_type'" });
+ }
- if (req.body.scope) {
- throw new BadRequestError({
- message:
- "The 'scope' parameter is not supported on the token exchange grant. The issued token carries the user's own permissions."
- });
- }
+ if (!ACCEPTED_SUBJECT_TOKEN_TYPES.includes(req.body.subject_token_type)) {
+ throw new BadRequestError({
+ message: `Unsupported 'subject_token_type'. Supported values are: ${ACCEPTED_SUBJECT_TOKEN_TYPES.join(", ")}`
+ });
+ }
+
+ if (req.body.requested_token_type && req.body.requested_token_type !== OauthTokenType.AccessToken) {
+ throw new BadRequestError({
+ message: `Unsupported 'requested_token_type'. Only '${OauthTokenType.AccessToken}' can be issued.`
+ });
+ }
+
+ if (req.body.actor_token || req.body.actor_token_type) {
+ throw new BadRequestError({
+ message:
+ "The 'actor_token' and 'actor_token_type' parameters are not supported. This grant issues a token that acts as the user in the subject token, and does not record the application as a separate acting party."
+ });
+ }
+
+ if (req.body.scope) {
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.InvalidScope,
+ message:
+ "The 'scope' parameter is not supported on the token exchange grant. The issued token carries the user's own permissions."
+ });
+ }
- if (req.body.audience || req.body.resource) {
- throw new BadRequestError({
- message:
- "The 'audience' and 'resource' parameters are not supported. The expected subject token audience is configured on the application."
+ if (req.body.audience || req.body.resource) {
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.InvalidTarget,
+ message:
+ "The 'audience' and 'resource' parameters are not supported. The expected subject token audience is configured on the application."
+ });
+ }
+
+ return await server.services.oauthClient.exchangeToken({
+ grantType: OauthGrantType.TokenExchange,
+ subjectToken: req.body.subject_token,
+ clientId,
+ clientSecret,
+ ip: req.realIp,
+ userAgent: req.headers["user-agent"]
});
}
- return server.services.oauthClient.exchangeToken({
- grantType: OauthGrantType.TokenExchange,
- subjectToken: req.body.subject_token,
+ if (!req.body.refresh_token) throw new BadRequestError({ message: "Missing refresh token" });
+
+ return await server.services.oauthClient.exchangeToken({
+ grantType: OauthGrantType.RefreshToken,
+ refreshToken: req.body.refresh_token,
clientId,
- clientSecret,
- ip: req.realIp,
- userAgent: req.headers["user-agent"]
+ clientSecret
});
- }
-
- if (!req.body.refresh_token) throw new BadRequestError({ message: "Missing refresh token" });
+ } catch (error) {
+ const tokenError = toOauthTokenError(error, req.body.grant_type);
+ if (tokenError !== error && tokenError.oauthErrorCode === OauthTokenErrorCode.ServerError) {
+ req.log.error(error, "OAuth token request failed unexpectedly");
+ }
- return server.services.oauthClient.exchangeToken({
- grantType: OauthGrantType.RefreshToken,
- refreshToken: req.body.refresh_token,
- clientId,
- clientSecret
- });
+ throw tokenError;
+ }
}
});
diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.ts
index d7ea278033..ed24f609d3 100644
--- a/backend/src/services/oauth-client/oauth-client-service.ts
+++ b/backend/src/services/oauth-client/oauth-client-service.ts
@@ -48,6 +48,7 @@ import {
TUpdateOauthClientDTO
} from "./oauth-client-types";
import { getOauthScopeDescriptions, parseOauthScopeString } from "./oauth-scope";
+import { OauthTokenError, OauthTokenErrorCode } from "./oauth-token-error";
import { verifySubjectToken } from "./oauth-token-exchange-fns";
type TOauthClientServiceFactoryDep = {
@@ -210,22 +211,25 @@ export const oauthClientServiceFactory = ({
// Without a live OIDC config there's nothing to verify subject tokens against. Failing at config time
// puts the message in front of the admin setting the application up.
- const getActiveOidcConfigOrThrow = async (orgId: string) => {
+ //
+ // `buildError` is a parameter because the two callers owe the same explanation in different envelopes:
+ // registering an application is a bad request from the admin making it, while an exchange hitting this
+ // is an org misconfiguration the caller can do nothing about, and the token endpoint has to say so in
+ // RFC 6749 terms. Keeping the wording in one place is the point.
+ const getActiveOidcConfigOrThrow = async (orgId: string, buildError: (message: string) => Error) => {
const org = await getClientOrg(orgId);
const oidcConfig = await oidcConfigDAL.findOne({ orgId: org.id });
if (!oidcConfig) {
- throw new BadRequestError({
- message:
- "Token exchange verifies user tokens against your organization's OIDC SSO issuer, and your organization has no OIDC SSO configuration. Set one up under Settings > SSO & Provisioning first."
- });
+ throw buildError(
+ "Token exchange verifies user tokens against your organization's OIDC SSO issuer, and your organization has no OIDC SSO configuration. Set one up under Settings > SSO & Provisioning first."
+ );
}
if (!oidcConfig.isActive) {
- throw new BadRequestError({
- message:
- "Token exchange verifies user tokens against your organization's OIDC SSO issuer, and your organization's OIDC SSO is disabled. Enable it under Settings > SSO & Provisioning first."
- });
+ throw buildError(
+ "Token exchange verifies user tokens against your organization's OIDC SSO issuer, and your organization's OIDC SSO is disabled. Enable it under Settings > SSO & Provisioning first."
+ );
}
return { oidcConfig, org };
@@ -279,7 +283,9 @@ export const oauthClientServiceFactory = ({
}
});
- if (establishesTokenExchangeTrust) await getActiveOidcConfigOrThrow(actor.orgId);
+ if (establishesTokenExchangeTrust) {
+ await getActiveOidcConfigOrThrow(actor.orgId, (message) => new BadRequestError({ message }));
+ }
return {
grantTypes,
@@ -454,8 +460,9 @@ export const oauthClientServiceFactory = ({
const assertGrantEnabled = (client: TOauthClients, grantType: OauthGrantType) => {
if (!getGrantTypes(client).includes(grantType)) {
- throw new UnauthorizedError({
- message: `This application is not registered for the '${grantType}' grant type`
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.UnauthorizedClient,
+ message: `This application is not registered for the '${grantType}' grant type.`
});
}
};
@@ -572,15 +579,18 @@ export const oauthClientServiceFactory = ({
};
const authenticateClient = async (clientId?: string, clientSecret?: string) => {
+ const invalidCredentials = (message: string) =>
+ new OauthTokenError({ code: OauthTokenErrorCode.InvalidClient, message });
+
if (!clientId || !clientSecret) {
- throw new UnauthorizedError({ message: "Missing OAuth client credentials" });
+ throw invalidCredentials("Missing OAuth client credentials.");
}
const client = await oauthClientDAL.findOne({ clientId });
- if (!client) throw new UnauthorizedError({ message: "Invalid OAuth client credentials" });
+ if (!client) throw invalidCredentials("Invalid OAuth client credentials.");
const isValidSecret = await crypto.hashing().compareHash(clientSecret, client.clientSecretHash);
- if (!isValidSecret) throw new UnauthorizedError({ message: "Invalid OAuth client credentials" });
+ if (!isValidSecret) throw invalidCredentials("Invalid OAuth client credentials.");
return client;
};
@@ -613,13 +623,17 @@ export const oauthClientServiceFactory = ({
dto: Extract<TOauthTokenExchangeDTO, { grantType: OauthGrantType.TokenExchange }>
) => {
if (!client.tokenExchangeAudience) {
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message:
"This application has no token exchange audience configured, so subject tokens cannot be verified. Set one on the application under Organization Settings > OAuth Applications."
});
}
- const { oidcConfig, org } = await getActiveOidcConfigOrThrow(client.orgId);
+ const { oidcConfig, org } = await getActiveOidcConfigOrThrow(
+ client.orgId,
+ (message) => new OauthTokenError({ code: OauthTokenErrorCode.ServerError, message })
+ );
const { subject } = await verifySubjectToken({
subjectToken: dto.subjectToken,
@@ -714,12 +728,17 @@ export const oauthClientServiceFactory = ({
ip: dto.ip,
userAgent: getOauthClientSessionUserAgent(client.clientId)
});
- if (!tokenSession) throw new BadRequestError({ message: "Failed to create user token session" });
+ if (!tokenSession)
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
+ message: "Failed to create a session for the user this token identifies."
+ });
const currentClient = await oauthClientDAL.findByIdOnPrimary(client.id);
if (hasClientAuthorityChanged(client, currentClient, OauthGrantType.TokenExchange)) {
await tokenService.revokeSessionsByUserAgent(getOauthClientSessionUserAgent(client.clientId));
- throw new UnauthorizedError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.InvalidClient,
message:
"This application's credentials or configuration changed while the token was being issued. Retry with the application's current client secret."
});
@@ -801,7 +820,7 @@ export const oauthClientServiceFactory = ({
}
if (!dto.redirectUri || dto.redirectUri !== codePayload.redirectUri) {
- throw new BadRequestError({ message: "Redirect URI mismatch" });
+ throw new OauthTokenError({ code: OauthTokenErrorCode.InvalidGrant, message: "Redirect URI mismatch." });
}
if (codePayload.codeChallenge) {
@@ -812,7 +831,7 @@ export const oauthClientServiceFactory = ({
});
}
if (computePkceChallenge(dto.codeVerifier) !== codePayload.codeChallenge) {
- throw new BadRequestError({ message: "PKCE challenge mismatch" });
+ throw new OauthTokenError({ code: OauthTokenErrorCode.InvalidGrant, message: "PKCE challenge mismatch." });
}
} else if (client.requirePkce) {
throw new BadRequestError({ message: "This OAuth client requires PKCE" });
diff --git a/backend/src/services/oauth-client/oauth-token-error.test.ts b/backend/src/services/oauth-client/oauth-token-error.test.ts
new file mode 100644
index 0000000000..c702d39b02
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-token-error.test.ts
@@ -0,0 +1,89 @@
+import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
+
+import { OauthGrantType } from "./oauth-client-types";
+import { OauthTokenError, OauthTokenErrorCode, toErrorDescription, toOauthTokenError } from "./oauth-token-error";
+
+describe("OauthTokenError", () => {
+ test("derives the status code from the RFC error code", () => {
+ // RFC 6749 section 5.2 puts every code at 400 and allows 401 for invalid_client alone.
+ expect(new OauthTokenError({ code: OauthTokenErrorCode.InvalidGrant, message: "x" }).statusCode).toBe(400);
+ expect(new OauthTokenError({ code: OauthTokenErrorCode.InvalidRequest, message: "x" }).statusCode).toBe(400);
+ expect(new OauthTokenError({ code: OauthTokenErrorCode.UnauthorizedClient, message: "x" }).statusCode).toBe(400);
+ expect(new OauthTokenError({ code: OauthTokenErrorCode.InvalidTarget, message: "x" }).statusCode).toBe(400);
+ expect(new OauthTokenError({ code: OauthTokenErrorCode.InvalidClient, message: "x" }).statusCode).toBe(401);
+ expect(new OauthTokenError({ code: OauthTokenErrorCode.ServerError, message: "x" }).statusCode).toBe(500);
+ });
+});
+
+describe("toOauthTokenError", () => {
+ test("passes an already-mapped error through untouched", () => {
+ const error = new OauthTokenError({ code: OauthTokenErrorCode.InvalidClient, message: "bad secret" });
+
+ expect(toOauthTokenError(error)).toBe(error);
+ });
+
+ test("maps a rejected grant to invalid_grant on the redirect and refresh grants", () => {
+ const rejected = new UnauthorizedError({ message: "Invalid or expired authorization code" });
+
+ expect(toOauthTokenError(rejected, OauthGrantType.AuthorizationCode).oauthErrorCode).toBe(
+ OauthTokenErrorCode.InvalidGrant
+ );
+ expect(toOauthTokenError(rejected, OauthGrantType.RefreshToken).oauthErrorCode).toBe(
+ OauthTokenErrorCode.InvalidGrant
+ );
+ });
+
+ // RFC 8693 section 2.2.2: a subject_token invalid for any reason, or unacceptable based on policy,
+ // MUST be answered with invalid_request rather than the invalid_grant RFC 6749 would suggest.
+ test("maps a rejected subject token to invalid_request on the exchange grant", () => {
+ const mapped = toOauthTokenError(
+ new UnauthorizedError({ message: "The subject token has expired." }),
+ OauthGrantType.TokenExchange
+ );
+
+ expect(mapped.oauthErrorCode).toBe(OauthTokenErrorCode.InvalidRequest);
+ expect(mapped.statusCode).toBe(400);
+ expect(mapped.message).toBe("The subject token has expired.");
+ });
+
+ test("maps a bad request to invalid_request, keeping its message", () => {
+ const mapped = toOauthTokenError(new BadRequestError({ message: "Missing 'subject_token'" }));
+
+ expect(mapped.oauthErrorCode).toBe(OauthTokenErrorCode.InvalidRequest);
+ expect(mapped.message).toBe("Missing 'subject_token'");
+ });
+
+ // Anything else escaped a path that was never meant to answer this endpoint, so its message was
+ // written for a different envelope and could carry internals.
+ test("maps anything else to a generic server_error and keeps the original for logging", () => {
+ const original = new NotFoundError({ message: "auth_token_sessions row 41 not found" });
+ const mapped = toOauthTokenError(original);
+
+ expect(mapped.oauthErrorCode).toBe(OauthTokenErrorCode.ServerError);
+ expect(mapped.statusCode).toBe(500);
+ expect(mapped.message).not.toContain("auth_token_sessions");
+ expect(mapped.error).toBe(original);
+ });
+});
+
+describe("toErrorDescription", () => {
+ // RFC 6749 section 5.2 allows only %x20-21 / %x23-5B / %x5D-7E.
+ test("replaces the two characters the charset excludes", () => {
+ expect(toErrorDescription('audience "api://x" is wrong')).toBe("audience 'api://x' is wrong");
+ expect(toErrorDescription("path a\\b")).toBe("path a'b");
+ });
+
+ test("collapses everything outside the charset to single spaces", () => {
+ expect(toErrorDescription("first\n\tsecondéthird")).toBe("first second third");
+ });
+
+ test("keeps the punctuation our messages actually use", () => {
+ const message = "Set one up under Settings > SSO & Provisioning first. Yours uses 'HS256' (bad).";
+
+ expect(toErrorDescription(message)).toBe(message);
+ });
+
+ test("bounds the length, so a schema failure cannot echo an unbounded issue list", () => {
+ expect(toErrorDescription("a".repeat(900))).toHaveLength(512);
+ });
+});
diff --git a/backend/src/services/oauth-client/oauth-token-error.ts b/backend/src/services/oauth-client/oauth-token-error.ts
new file mode 100644
index 0000000000..0de331e1ae
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-token-error.ts
@@ -0,0 +1,111 @@
+import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
+
+import { OauthGrantType } from "./oauth-client-types";
+
+// The token endpoint answers failures in the shape RFC 6749 section 5.2 defines, extended by the
+// `invalid_target` code from RFC 8693 section 2.2.2: a JSON body carrying an `error` code from a fixed
+// list plus a human-readable `error_description`. Generic OAuth client libraries branch on that code,
+// so the house envelope (`{ statusCode, message, error: "UnauthorizedError" }`) leaves them unable to
+// tell "rotate the client secret" from "re-authenticate the user" from "retry later".
+//
+// This is the only endpoint that responds this way. It exists because the endpoint's contract is the
+// RFC rather than our own API conventions.
+export enum OauthTokenErrorCode {
+ InvalidRequest = "invalid_request",
+ InvalidClient = "invalid_client",
+ InvalidGrant = "invalid_grant",
+ UnauthorizedClient = "unauthorized_client",
+ UnsupportedGrantType = "unsupported_grant_type",
+ InvalidScope = "invalid_scope",
+ InvalidTarget = "invalid_target",
+ ServerError = "server_error"
+}
+
+// RFC 6749 section 5.2 puts every code at 400 and allows 401 for `invalid_client` alone. `server_error`
+// is not in that list (it belongs to the authorization endpoint) but is the conventional code for a
+// request the server cannot fulfil, and 500 is what tells a client to retry rather than rewrite.
+const STATUS_CODE_BY_ERROR_CODE: Record<OauthTokenErrorCode, number> = {
+ [OauthTokenErrorCode.InvalidRequest]: 400,
+ [OauthTokenErrorCode.InvalidClient]: 401,
+ [OauthTokenErrorCode.InvalidGrant]: 400,
+ [OauthTokenErrorCode.UnauthorizedClient]: 400,
+ [OauthTokenErrorCode.UnsupportedGrantType]: 400,
+ [OauthTokenErrorCode.InvalidScope]: 400,
+ [OauthTokenErrorCode.InvalidTarget]: 400,
+ [OauthTokenErrorCode.ServerError]: 500
+};
+
+// RFC 6749 section 5.2 restricts error_description to %x20-21 / %x23-5B / %x5D-7E: printable ASCII
+// without the double quote or the backslash. Messages here are written for a human reading a terminal,
+// not filtered for that, so normalise at the boundary rather than constraining every throw site. The cap
+// is there because a schema failure can otherwise carry an issue list of unbounded length.
+const MAX_ERROR_DESCRIPTION_LENGTH = 512;
+const DISALLOWED_DESCRIPTION_CHARS = /[^\x20-\x21\x23-\x5B\x5D-\x7E]/g;
+
+export const toErrorDescription = (message: string) =>
+ message
+ .replace(/["\\]/g, "'")
+ .replace(DISALLOWED_DESCRIPTION_CHARS, " ")
+ .replace(/\s+/g, " ")
+ .trim()
+ .slice(0, MAX_ERROR_DESCRIPTION_LENGTH);
+
+export class OauthTokenError extends Error {
+ name: string;
+
+ oauthErrorCode: OauthTokenErrorCode;
+
+ statusCode: number;
+
+ error: unknown;
+
+ constructor({ code, message, error }: { code: OauthTokenErrorCode; message: string; error?: unknown }) {
+ super(message);
+ this.name = "OauthTokenError";
+ this.oauthErrorCode = code;
+ this.statusCode = STATUS_CODE_BY_ERROR_CODE[code];
+ this.error = error;
+ }
+}
+
+// RFC 8693 section 2.2.2 overrides RFC 6749 for the token-exchange grant, and not in the direction you
+// would guess: a `subject_token` that is "invalid for any reason, or unacceptable based on policy" MUST
+// be answered with `invalid_request`, where the same class of failure on the redirect and refresh grants
+// is `invalid_grant` under RFC 6749 section 5.2. So the code a rejected grant earns depends on which
+// grant was used, and only the exchange collapses "your token is bad" into "your request is bad".
+const REJECTED_GRANT_CODE_BY_GRANT_TYPE: Record<OauthGrantType, OauthTokenErrorCode> = {
+ [OauthGrantType.AuthorizationCode]: OauthTokenErrorCode.InvalidGrant,
+ [OauthGrantType.RefreshToken]: OauthTokenErrorCode.InvalidGrant,
+ [OauthGrantType.TokenExchange]: OauthTokenErrorCode.InvalidRequest
+};
+
+// Translates whatever escaped the token endpoint into an RFC code. Sites where the class default is
+// wrong throw `OauthTokenError` directly and pass through here untouched; the defaults below only have
+// to cover the rest, so they key off the error class and never the message text.
+//
+// `UnauthorizedError` on this path always means a grant we will not act on (a bad authorization code,
+// refresh token or subject token, or a subject we cannot resolve to a usable account), so it takes
+// whichever code that grant owes. Client authentication is the exception and throws `invalid_client`
+// explicitly, which RFC 8693 leaves to RFC 6749 because it is the client that failed, not the token.
+//
+// Anything that is neither is a bug or an outage rather than a bad request, so it becomes a generic
+// `server_error`: its message was written for a different envelope and could carry internals.
+export const toOauthTokenError = (error: unknown, grantType?: OauthGrantType): OauthTokenError => {
+ if (error instanceof OauthTokenError) return error;
+
+ if (error instanceof UnauthorizedError) {
+ const code = grantType ? REJECTED_GRANT_CODE_BY_GRANT_TYPE[grantType] : OauthTokenErrorCode.InvalidGrant;
+
+ return new OauthTokenError({ code, message: error.message, error });
+ }
+
+ if (error instanceof BadRequestError) {
+ return new OauthTokenError({ code: OauthTokenErrorCode.InvalidRequest, message: error.message, error });
+ }
+
+ return new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
+ message: "The authorization server could not complete the token request.",
+ error
+ });
+};
diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts
index e223417055..81a94b9fb6 100644
--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts
+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts
@@ -3,10 +3,12 @@ import { JwksClient } from "jwks-rsa";
import { TOidcConfigs } from "@app/db/schemas";
import { OIDCConfigurationType, OIDCJWTSignatureAlgorithm } from "@app/ee/services/oidc/oidc-config-types";
-import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
+import { UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { buildSsrfSafeAgent, safeRequest } from "@app/lib/validator/safe-request";
+import { OauthTokenError, OauthTokenErrorCode } from "./oauth-token-error";
+
const SSO_TAB_HINT = "Check Settings > SSO & Provisioning.";
// HS256 is left out because it's symmetric: the verification key is the signing key, so anyone who can
@@ -114,14 +116,16 @@ export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<
const algorithm = oidcConfig.jwtSignatureAlgorithm || OIDCJWTSignatureAlgorithm.RS256;
if (!ASYMMETRIC_SIGNATURE_ALGORITHMS.includes(algorithm)) {
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Token exchange requires an OIDC SSO configuration that uses an asymmetric JWT signature algorithm, but yours uses '${algorithm}'. Switch it to one of ${ASYMMETRIC_SIGNATURE_ALGORITHMS.join(", ")}. ${SSO_TAB_HINT}`
});
}
if (oidcConfig.configurationType === OIDCConfigurationType.DISCOVERY_URL) {
if (!oidcConfig.discoveryURL) {
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Your organization's OIDC SSO configuration has no discovery URL, so the identity provider's signing keys cannot be located. ${SSO_TAB_HINT}`
});
}
@@ -134,21 +138,24 @@ export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<
{ error, orgId: oidcConfig.orgId },
`OIDC discovery failed during token exchange [orgId=${oidcConfig.orgId}]`
);
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Could not reach your organization's identity provider to load its signing keys. ${SSO_TAB_HINT}`
});
}
const jwksUri = metadata.jwks_uri;
if (!jwksUri) {
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Your organization's identity provider did not publish a 'jwks_uri' in its discovery document, so subject tokens cannot be verified. ${SSO_TAB_HINT}`
});
}
const issuer = oidcConfig.issuer || metadata.issuer;
if (!issuer) {
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Your organization's identity provider did not publish an issuer in its discovery document. ${SSO_TAB_HINT}`
});
}
@@ -157,7 +164,8 @@ export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<
}
if (!oidcConfig.issuer || !oidcConfig.jwksUri) {
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Your organization's OIDC SSO configuration is missing an issuer or JWKS URI, so subject tokens cannot be verified. ${SSO_TAB_HINT}`
});
}
@@ -255,7 +263,8 @@ export const verifySubjectToken = async ({ subjectToken, oidcConfig, expectedAud
});
}
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Could not load signing keys from your organization's identity provider. ${SSO_TAB_HINT}`
});
}
@@ -269,7 +278,8 @@ export const verifySubjectToken = async ({ subjectToken, oidcConfig, expectedAud
`Subject token signing key could not be imported during token exchange [orgId=${oidcConfig.orgId}] [kid=${kid}]`
);
- throw new BadRequestError({
+ throw new OauthTokenError({
+ code: OauthTokenErrorCode.ServerError,
message: `Your organization's identity provider published a signing key ('${kid}') that cannot be used with the JWT signature algorithm its OIDC SSO configuration declares ('${anchor.algorithm}'). ${SSO_TAB_HINT}`
});
}
diff --git a/docs/documentation/platform/oauth-applications/token-exchange.mdx b/docs/documentation/platform/oauth-applications/token-exchange.mdx
index 963e3db66f..c214364aba 100644
--- a/docs/documentation/platform/oauth-applications/token-exchange.mdx
+++ b/docs/documentation/platform/oauth-applications/token-exchange.mdx
@@ -149,6 +149,35 @@ The response is an access token for the user the subject token identified:
Access token lifetime is the shortest of the application's **access token lifetime** (1 day by default), your organization's session length, and the instance default of 10 days. The application's own value is a ceiling rather than an override: it can shorten the lifetime but never extend it past what the organization allows. Because the middleware holds a credential that acts as the user, shorten it on the application rather than relying on the default.
+### When an exchange fails
+
+Failures follow [RFC 8693 section 2.2.2](https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.2), which builds on [RFC 6749 section 5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2), so an RFC-aware client library can classify them without reading the prose:
+
+```json
+{
+ "error": "invalid_request",
+ "error_description": "The subject token has expired."
+}
+```
+
+| `error` | Status | What it means |
+| ------------------------ | ------ | -------------------------------------------------------------------------------------------------- |
+| `invalid_client` | 401 | The client ID or secret is wrong, or the secret was rotated mid-request. Reload your credentials. |
+| `unauthorized_client` | 400 | The application is not registered for this grant. An admin enables it on the application. |
+| `invalid_request` | 400 | A parameter is missing or malformed, **or the subject token was rejected**. See below. |
+| `unsupported_grant_type` | 400 | The `grant_type` is not one Infisical issues tokens for. |
+| `invalid_scope` | 400 | A `scope` was sent. This grant has none. |
+| `invalid_target` | 400 | An `audience` or `resource` was sent. The audience is fixed on the application. |
+| `server_error` | 500 | Your OIDC SSO configuration is incomplete, or your identity provider could not be reached. Retry. |
+
+<Warning>
+ RFC 8693 requires `invalid_request` for a subject token that is invalid for any reason or unacceptable by policy, so an expired token, a wrong audience, and a user who is not an active member all arrive under the same code as a malformed request. This grant never returns `invalid_grant`, which is what the authorization code flow uses for the equivalent failure.
+
+ The distinction lives in `error_description`, which names the specific check that failed. Branch on the description, or simply re-authenticate the user and retry once, rather than expecting a code per cause.
+</Warning>
+
+Retry on `server_error`. `invalid_client` and `unauthorized_client` need an operator, not a retry.
+
<Note>
`scope`, `audience`, `resource`, and `actor_token` are rejected rather than ignored. This grant has no scope concept, and the expected audience is fixed on the application, so silently dropping those parameters would leave you believing a restriction was applied when it was not.