Skip to content

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

use same library as web

Thiago Araujo da Silvaad69422a82cc
diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts
index d4113e6184..8c8381d627 100644
--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts
+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts
@@ -1,5 +1,6 @@
import nodeCrypto from "node:crypto";
+import { importPKCS8, SignJWT } from "jose";
import jwt from "jsonwebtoken";
import { TOidcConfigs } from "@app/db/schemas";
@@ -10,10 +11,13 @@ import { resolveOidcTrustAnchor, verifySubjectToken } from "./oauth-token-exchan
const { publicKey, privateKey } = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
const otherKeyPair = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
+const ed25519KeyPair = nodeCrypto.generateKeyPairSync("ed25519");
const PUBLIC_KEY_PEM = publicKey.export({ type: "spki", format: "pem" }).toString();
const PRIVATE_KEY_PEM = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
const OTHER_PRIVATE_KEY_PEM = otherKeyPair.privateKey.export({ type: "pkcs8", format: "pem" }).toString();
+const ED25519_PUBLIC_KEY_PEM = ed25519KeyPair.publicKey.export({ type: "spki", format: "pem" }).toString();
+const ED25519_PRIVATE_KEY_PEM = ed25519KeyPair.privateKey.export({ type: "pkcs8", format: "pem" }).toString();
const getSigningKey = vi.fn<(kid: string) => Promise<{ getPublicKey: () => string }>>();
@@ -95,6 +99,21 @@ const signSubjectToken = ({
...(keyId ? { keyid: keyId } : {})
});
+// jsonwebtoken cannot sign EdDSA, so the EdDSA cases mint their tokens with jose.
+const signEddsaSubjectToken = async ({
+ audience = AUDIENCE,
+ issuer = ISSUER
+}: { audience?: string; issuer?: string } = {}) => {
+ const signingKey = await importPKCS8(ED25519_PRIVATE_KEY_PEM, OIDCJWTSignatureAlgorithm.EDDSA);
+
+ return new SignJWT({ sub: SUBJECT })
+ .setProtectedHeader({ alg: OIDCJWTSignatureAlgorithm.EDDSA, kid: "adfs-key-1" })
+ .setIssuer(issuer)
+ .setAudience(audience)
+ .setExpirationTime("10m")
+ .sign(signingKey);
+};
+
beforeAll(async () => {
process.env.FIPS_ENABLED = "false";
await crypto.initialize({} as never, {} as never, {} as never);
@@ -261,15 +280,14 @@ describe("verifySubjectToken", () => {
await expect(verify(token)).rejects.toThrow(/could not be verified against your organization/);
});
- // Pinning `algorithms` closes this off. jsonwebtoken reports it as a missing signature rather than an
- // algorithm mismatch, so assert on the generic message.
+ // Pinning `algorithms` closes this off before the signature is ever looked at.
test("rejects an unsigned (alg: none) token", async () => {
const token = jwt.sign({ sub: SUBJECT, aud: AUDIENCE, iss: ISSUER }, "", {
algorithm: "none",
keyid: "adfs-key-1"
});
- await expect(verify(token)).rejects.toThrow(/could not be verified against your organization/);
+ await expect(verify(token)).rejects.toThrow(/not signed with the algorithm/);
});
test("rejects a token signed with an algorithm the configuration does not expect", async () => {
@@ -278,6 +296,36 @@ describe("verifySubjectToken", () => {
await expect(verify(token)).rejects.toThrow(/not signed with the algorithm/);
});
+ // EdDSA is selectable in the OIDC SSO configuration and works for browser SSO login, so it has to work
+ // here too. jsonwebtoken cannot verify it at all, which is why verification runs through jose.
+ test("verifies an EdDSA-signed token for an EdDSA configuration", async () => {
+ getSigningKey.mockResolvedValue({ getPublicKey: () => ED25519_PUBLIC_KEY_PEM });
+ const token = await signEddsaSubjectToken();
+
+ await expect(
+ verify(token, buildOidcConfig({ jwtSignatureAlgorithm: OIDCJWTSignatureAlgorithm.EDDSA }))
+ ).resolves.toEqual({ subject: SUBJECT, issuer: ISSUER });
+ });
+
+ test("still enforces the audience on an EdDSA-signed token", async () => {
+ getSigningKey.mockResolvedValue({ getPublicKey: () => ED25519_PUBLIC_KEY_PEM });
+ const token = await signEddsaSubjectToken({ audience: "api://expenses-app" });
+
+ await expect(
+ verify(token, buildOidcConfig({ jwtSignatureAlgorithm: OIDCJWTSignatureAlgorithm.EDDSA }))
+ ).rejects.toThrow(/audience does not match/);
+ });
+
+ // An RSA key cannot carry EdDSA. That is the provider's configuration disagreeing with itself, not a
+ // bad token, so it must not surface as an unhandled 500.
+ test("reports a signing key that cannot carry the configured algorithm", async () => {
+ const token = await signEddsaSubjectToken();
+
+ await expect(
+ verify(token, buildOidcConfig({ jwtSignatureAlgorithm: OIDCJWTSignatureAlgorithm.EDDSA }))
+ ).rejects.toThrow(/cannot be used with the JWT signature algorithm/);
+ });
+
test("rejects a token with no kid header", async () => {
const token = signSubjectToken({ keyId: null });
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 1172d59f81..a1ec083903 100644
--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts
+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts
@@ -1,9 +1,8 @@
-import jwt, { JwtPayload } from "jsonwebtoken";
+import { decodeProtectedHeader, errors as joseErrors, importSPKI, JWTPayload, jwtVerify } from "jose";
import { JwksClient } from "jwks-rsa";
import { TOidcConfigs } from "@app/db/schemas";
import { OIDCConfigurationType, OIDCJWTSignatureAlgorithm } from "@app/ee/services/oidc/oidc-config-types";
-import { crypto } from "@app/lib/crypto";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { buildSsrfSafeAgent, safeRequest } from "@app/lib/validator/safe-request";
@@ -131,38 +130,42 @@ export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<
return { issuer: oidcConfig.issuer, jwksUri: oidcConfig.jwksUri, algorithm };
};
-// jsonwebtoken reports failures with terse developer-facing text ("jwt audience invalid"). Translate to
-// something the caller can act on without leaking the raw message.
+// jose reports failures with terse developer-facing text ("unexpected \"aud\" claim value"). Translate to
+// something the caller can act on without leaking the raw message. Each branch keys off jose's error
+// class and its `claim` field rather than the message text, so a wording change upstream cannot silently
+// collapse a specific failure into the generic one.
const toSubjectTokenError = (error: unknown, anchor: TOidcTrustAnchor, expectedAudience: string) => {
- if (error instanceof jwt.TokenExpiredError) {
+ if (error instanceof joseErrors.JWTExpired) {
return new UnauthorizedError({ message: "The subject token has expired." });
}
- if (error instanceof jwt.NotBeforeError) {
- return new UnauthorizedError({ message: "The subject token is not valid yet (its 'nbf' claim is in the future)." });
- }
-
- if (error instanceof jwt.JsonWebTokenError) {
- const reason = error.message;
-
- if (reason.includes("audience")) {
+ if (error instanceof joseErrors.JWTClaimValidationFailed) {
+ if (error.claim === "aud") {
return new UnauthorizedError({
message: `The subject token's audience does not match this application's configured token exchange audience ('${expectedAudience}').`
});
}
- if (reason.includes("issuer")) {
+ if (error.claim === "iss") {
return new UnauthorizedError({
message: `The subject token was not issued by your organization's configured OIDC SSO issuer ('${anchor.issuer}').`
});
}
- if (reason.includes("algorithm")) {
+ if (error.claim === "nbf") {
return new UnauthorizedError({
- message: `The subject token is not signed with the algorithm your organization's OIDC SSO configuration expects ('${anchor.algorithm}').`
+ message: "The subject token is not valid yet (its 'nbf' claim is in the future)."
});
}
+ }
+
+ if (error instanceof joseErrors.JOSEAlgNotAllowed) {
+ return new UnauthorizedError({
+ message: `The subject token is not signed with the algorithm your organization's OIDC SSO configuration expects ('${anchor.algorithm}').`
+ });
+ }
+ if (error instanceof joseErrors.JOSEError) {
return new UnauthorizedError({
message: "The subject token could not be verified against your organization's identity provider."
});
@@ -182,12 +185,14 @@ type TVerifySubjectTokenDTO = {
export const verifySubjectToken = async ({ subjectToken, oidcConfig, expectedAudience }: TVerifySubjectTokenDTO) => {
const anchor = await resolveOidcTrustAnchor(oidcConfig);
- const decoded = crypto.jwt().decode(subjectToken, { complete: true });
- if (!decoded) {
+ let header: ReturnType<typeof decodeProtectedHeader>;
+ try {
+ header = decodeProtectedHeader(subjectToken);
+ } catch {
throw new UnauthorizedError({ message: "The subject token is not a well-formed JWT." });
}
- const { kid } = decoded.header;
+ const { kid } = header;
if (!kid) {
throw new UnauthorizedError({
message:
@@ -216,13 +221,27 @@ export const verifySubjectToken = async ({ subjectToken, oidcConfig, expectedAud
});
}
- let claims: JwtPayload;
+ let publicKey;
+ try {
+ publicKey = await importSPKI(signingKey.getPublicKey(), anchor.algorithm);
+ } catch (error) {
+ logger.error(
+ { error, orgId: oidcConfig.orgId, kid },
+ `Subject token signing key could not be imported during token exchange [orgId=${oidcConfig.orgId}] [kid=${kid}]`
+ );
+
+ throw new BadRequestError({
+ 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}`
+ });
+ }
+
+ let claims: JWTPayload;
try {
- claims = crypto.jwt().verify(subjectToken, signingKey.getPublicKey(), {
+ ({ payload: claims } = await jwtVerify(subjectToken, publicKey, {
issuer: anchor.issuer,
audience: expectedAudience,
- algorithms: [anchor.algorithm as jwt.Algorithm]
- }) as JwtPayload;
+ algorithms: [anchor.algorithm]
+ }));
} catch (error) {
logger.error(
{ error, orgId: oidcConfig.orgId },