Skip to content

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

accept native SPIFFE bundle format from spire-server

Thiago Araujo da Silva5cbb08822db4
diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.test.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.test.ts
new file mode 100644
index 0000000000..2712a35d3c
--- /dev/null
+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.test.ts
@@ -0,0 +1,70 @@
+import { createLocalJWKSet, exportJWK, generateKeyPair, JWK, jwtVerify, SignJWT } from "jose";
+import { beforeAll, describe, expect, test } from "vitest";
+
+import { BadRequestError } from "@app/lib/errors";
+
+import { parseSpiffeBundleJwtAuthorities } from "./identity-spiffe-auth-fns";
+
+describe("parseSpiffeBundleJwtAuthorities", () => {
+ let jwtSigningKey: JWK;
+ let signedJwtSvid: string;
+
+ beforeAll(async () => {
+ const { publicKey, privateKey } = await generateKeyPair("ES256");
+ jwtSigningKey = { ...(await exportJWK(publicKey)), kid: "jwt-authority-1" };
+ signedJwtSvid = await new SignJWT({ sub: "spiffe://example.org/workload" })
+ .setProtectedHeader({ alg: "ES256", kid: "jwt-authority-1" })
+ .setAudience("infisical")
+ .setExpirationTime("5m")
+ .sign(privateKey);
+ });
+
+ const spireBundle = () =>
+ JSON.stringify({
+ keys: [
+ { use: "x509-svid", kty: "EC", crv: "P-256", x: jwtSigningKey.x, y: jwtSigningKey.y, x5c: ["MIIB"] },
+ { ...jwtSigningKey, use: "jwt-svid" }
+ ],
+ spiffe_sequence: 1,
+ spiffe_refresh_hint: 300
+ });
+
+ test("verifies a JWT-SVID against the native SPIFFE bundle format", async () => {
+ const jwks = parseSpiffeBundleJwtAuthorities(spireBundle());
+
+ expect(jwks).toEqual({ keys: [{ ...jwtSigningKey, use: "sig" }] });
+ const { payload } = await jwtVerify(signedJwtSvid, createLocalJWKSet(jwks), { audience: "infisical" });
+ expect(payload.sub).toBe("spiffe://example.org/workload");
+ });
+
+ test.each([
+ ["use: sig", { use: "sig" }],
+ ["no use", {}]
+ ])("keeps keys from a plain RFC 7517 JWKS (%s)", async (_, extra) => {
+ const jwks = parseSpiffeBundleJwtAuthorities(JSON.stringify({ keys: [{ ...jwtSigningKey, ...extra }] }));
+
+ await expect(jwtVerify(signedJwtSvid, createLocalJWKSet(jwks), { audience: "infisical" })).resolves.toBeDefined();
+ });
+
+ test("drops keys for other SVID types", () => {
+ const jwks = parseSpiffeBundleJwtAuthorities(
+ JSON.stringify({
+ keys: [
+ { ...jwtSigningKey, use: "wit-svid", kid: "wit" },
+ { ...jwtSigningKey, use: "jwt-svid" }
+ ]
+ })
+ );
+
+ expect(jwks.keys.map((key) => key.kid)).toEqual(["jwt-authority-1"]);
+ });
+
+ test.each([
+ ["invalid JSON", "{not json"],
+ ["no keys array", JSON.stringify({ spiffe_sequence: 1 })],
+ ["null", "null"],
+ ["only X.509 authorities", JSON.stringify({ keys: [{ use: "x509-svid", kty: "EC", x5c: ["MIIB"] }] })]
+ ])("rejects a bundle with %s", (_, bundle) => {
+ expect(() => parseSpiffeBundleJwtAuthorities(bundle)).toThrow(BadRequestError);
+ });
+});
diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts
index cb0a41b628..cc0333d67b 100644
--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts
+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts
@@ -1,8 +1,10 @@
import https from "https";
+import { JSONWebKeySet, JWK } from "jose";
import picomatch from "picomatch";
import RE2 from "re2";
import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
const SPIFFE_ID_REGEX = new RE2("^spiffe:\\/\\/([^/]+)(\\/.*)?");
@@ -41,3 +43,40 @@ export const fetchRemoteBundleJwks = async (url: string, caCert?: string): Promi
return response.data;
};
+
+// SPIFFE bundles (`spire-server bundle show -format spiffe`, bundle endpoints) are JWKS with
+// `use` set to the SVID type. JWT-SVID verification only needs the "jwt-svid" keys, and jose
+// drops any key whose `use` is not "sig", so those keys are re-marked. Keys with `use: "sig"`
+// or no `use` are also kept so hand-converted RFC 7517 JWKS bundles keep working.
+export const parseSpiffeBundleJwtAuthorities = (bundleJson: string): JSONWebKeySet => {
+ let bundle: unknown;
+ try {
+ bundle = JSON.parse(bundleJson);
+ } catch {
+ throw new BadRequestError({ message: "The SPIFFE trust bundle is not valid JSON" });
+ }
+
+ const keys = (bundle as { keys?: unknown } | null)?.keys;
+ if (!Array.isArray(keys)) {
+ throw new BadRequestError({ message: 'The SPIFFE trust bundle must be a JSON object with a "keys" array' });
+ }
+
+ const jwtAuthorities = keys
+ .filter(
+ (key): key is JWK =>
+ typeof key === "object" &&
+ key !== null &&
+ !Array.isArray(key) &&
+ ((key as JWK).use === undefined || (key as JWK).use === "jwt-svid" || (key as JWK).use === "sig")
+ )
+ .map((key) => ({ ...key, use: "sig" }));
+
+ if (!jwtAuthorities.length) {
+ throw new BadRequestError({
+ message:
+ 'The SPIFFE trust bundle contains no JWT-SVID signing keys. Expected at least one key with "use": "jwt-svid", as output by `spire-server bundle show -format spiffe`.'
+ });
+ }
+
+ return { keys: jwtAuthorities };
+};
diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
index a4ecf13f31..32abedead4 100644
--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
@@ -1,6 +1,6 @@
import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";
-import { createLocalJWKSet, errors as joseErrors, JSONWebKeySet, jwtVerify } from "jose";
+import { createLocalJWKSet, errors as joseErrors, jwtVerify } from "jose";
import {
AccessScope,
@@ -51,7 +51,8 @@ import {
doesSpiffeIdMatchPattern,
extractTrustDomainFromSpiffeId,
fetchRemoteBundleJwks,
- isValidSpiffeId
+ isValidSpiffeId,
+ parseSpiffeBundleJwtAuthorities
} from "./identity-spiffe-auth-fns";
import {
FIPS_APPROVED_JWT_ALGORITHMS,
@@ -87,8 +88,10 @@ type TIdentitySpiffeAuthServiceFactoryDep = {
export type TIdentitySpiffeAuthServiceFactory = ReturnType<typeof identitySpiffeAuthServiceFactory>;
+const JWT_SVID_NO_MATCHING_KEY_MESSAGE = "No key in the SPIFFE trust bundle matches the JWT-SVID signing key";
+
const verifyJwtSvid = async (jwtValue: string, jwksJson: string, allowedAudiences: string[]) => {
- const jwks = createLocalJWKSet(JSON.parse(jwksJson) as JSONWebKeySet);
+ const jwks = createLocalJWKSet(parseSpiffeBundleJwtAuthorities(jwksJson));
try {
const { payload } = await jwtVerify(jwtValue, jwks, {
@@ -106,6 +109,9 @@ const verifyJwtSvid = async (jwtValue: string, jwksJson: string, allowedAudience
if (error instanceof joseErrors.JWTClaimValidationFailed) {
throw new UnauthorizedError({ message: "JWT-SVID audience validation failed" });
}
+ if (error instanceof joseErrors.JWKSNoMatchingKey) {
+ throw new UnauthorizedError({ message: JWT_SVID_NO_MATCHING_KEY_MESSAGE });
+ }
throw new UnauthorizedError({ message: "JWT-SVID verification failed" });
}
};
@@ -193,17 +199,13 @@ export const identitySpiffeAuthServiceFactory = ({
const $validateSpiffeConfig = async (dist: TSpiffeTrustBundleDistribution) => {
if (dist.profile === SpiffeTrustBundleProfile.STATIC) {
- try {
- createLocalJWKSet(JSON.parse(dist.bundle) as JSONWebKeySet);
- } catch {
- throw new BadRequestError({ message: "The provided CA Bundle JWKS is not valid JWKS" });
- }
+ parseSpiffeBundleJwtAuthorities(dist.bundle);
return;
}
try {
const bundleJwks = await fetchRemoteBundleJwks(dist.endpointUrl, dist.caCert);
- createLocalJWKSet(JSON.parse(bundleJwks) as JSONWebKeySet);
+ parseSpiffeBundleJwtAuthorities(bundleJwks);
} catch (error) {
if (error instanceof BadRequestError) throw error;
throw new BadRequestError({
@@ -284,6 +286,8 @@ export const identitySpiffeAuthServiceFactory = ({
throw new BadRequestError({ message: `Failed to fetch SPIFFE trust bundle from remote endpoint: ${msg}` });
}
+ parseSpiffeBundleJwtAuthorities(bundleJson);
+
const { cipherTextBlob: encryptedCachedBundleJwks } = orgDataKeyEncryptor({
plainText: Buffer.from(bundleJson)
});
@@ -336,7 +340,11 @@ export const identitySpiffeAuthServiceFactory = ({
tokenData = await verifyJwtSvid(jwtValue, jwksJson, allowedAudiences);
} catch (verifyError) {
// Kid-miss retry: if we used a cached JWKS and the kid wasn't found, force-refresh once
- if (fromCache && verifyError instanceof Error && verifyError.message.includes("No key found in JWKS")) {
+ if (
+ fromCache &&
+ verifyError instanceof UnauthorizedError &&
+ verifyError.message === JWT_SVID_NO_MATCHING_KEY_MESSAGE
+ ) {
({ jwksJson, fromCache } = await $resolveJwks({
config: identitySpiffeAuth,
orgId: identity.orgId,
diff --git a/docs/documentation/platform/identities/spiffe-auth.mdx b/docs/documentation/platform/identities/spiffe-auth.mdx
index 1808a4b999..7942b056e4 100644
--- a/docs/documentation/platform/identities/spiffe-auth.mdx
+++ b/docs/documentation/platform/identities/spiffe-auth.mdx
@@ -93,9 +93,11 @@ In the following steps, we explore how to create and use identities to access th
<Tabs>
<Tab title="Static">
- Best for air-gapped environments or environments where the trust bundle does not change frequently. You provide the SPIRE JWKS JSON directly.
+ Best for air-gapped environments or environments where the trust bundle doesn't change frequently. You paste your SPIRE server's trust bundle directly.
- - **CA Bundle JWKS (required):** The JWKS JSON containing the public keys used to verify JWT-SVID signatures. You can obtain this from your SPIRE server's bundle endpoint or via `spire-server bundle show -format jwks`.
+ - **CA Bundle JWKS (required):** The output of `spire-server bundle show -format spiffe`, which holds the public keys Infisical uses to verify JWT-SVID signatures
+
+ Paste the bundle as SPIRE prints it. Infisical uses only the JWT-SVID signing keys in the bundle, so you don't need to remove the X.509-SVID keys or the `spiffe_sequence` field.
</Tab>
<Tab title="HTTPS Web Bundle">
Best for dynamic environments where keys rotate regularly. Infisical automatically fetches and caches the trust bundle from a SPIRE bundle endpoint.
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx
index 0a20d9549d..af8d00087e 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx
@@ -390,7 +390,7 @@ export const IdentitySpiffeAuthForm = ({
<TextArea
{...field}
id="trustBundleBundle"
- placeholder="Paste SPIRE JWKS JSON"
+ placeholder="Paste the output of spire-server bundle show -format spiffe"
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>