Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pki-118): fix the migration and jwt logic
Tre Dubravae73f44cf6c01
diff --git a/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.ts b/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.tsindex c55c9fc64a..8029d6c26e 100644--- a/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.ts+++ b/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.ts@@ -1,10 +1,37 @@import { Knex } from "knex";+import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";export async function up(knex: Knex): Promise<void> {-}+ if (!(await knex.schema.hasTable(TableName.IdentitySpiffeAuth))) {+ await knex.schema.createTable(TableName.IdentitySpiffeAuth, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("identityId").notNullable().unique();+ t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");+ t.string("trustDomain").notNullable();+ t.string("allowedSpiffeIds").notNullable();+ t.string("allowedAudiences").notNullable();+ t.string("configurationType").notNullable();+ t.binary("encryptedCaBundleJwks").nullable();+ t.string("bundleEndpointUrl").nullable();+ t.string("bundleEndpointProfile").nullable();+ t.binary("encryptedBundleEndpointCaCert").nullable();+ t.binary("encryptedCachedBundleJwks").nullable();+ t.datetime("cachedBundleLastRefreshedAt").nullable();+ t.integer("bundleRefreshHintSeconds").defaultTo(300).notNullable();+ t.bigInteger("accessTokenTTL").defaultTo(7200).notNullable();+ t.bigInteger("accessTokenMaxTTL").defaultTo(7200).notNullable();+ t.bigInteger("accessTokenNumUsesLimit").defaultTo(0).notNullable();+ t.jsonb("accessTokenTrustedIps").notNullable();+ t.timestamps(true, true, true);+ });+ }+ await createOnUpdateTrigger(knex, TableName.IdentitySpiffeAuth);+}export async function down(knex: Knex): Promise<void> {+ await knex.schema.dropTableIfExists(TableName.IdentitySpiffeAuth);+ await dropOnUpdateTrigger(knex, TableName.IdentitySpiffeAuth);}-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.tsindex 9837903ae2..af964ef532 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,7 +1,6 @@import { ForbiddenError, subject } from "@casl/ability";import { requestContext } from "@fastify/request-context";-import jwt from "jsonwebtoken";-import { importJWK } from "jose";+import { decodeProtectedHeader, errors as joseErrors, importJWK, jwtVerify } from "jose";import {AccessScope,@@ -72,27 +71,30 @@ type TIdentitySpiffeAuthServiceFactoryDep = {export type TIdentitySpiffeAuthServiceFactory = ReturnType<typeof identitySpiffeAuthServiceFactory>;const verifyJwtSvid = async (jwtValue: string, jwksJson: string) => {- const decodedToken = crypto.jwt().decode(jwtValue, { complete: true });- if (!decodedToken || typeof decodedToken === "string") {- throw new UnauthorizedError({ message: "Invalid JWT" });- }-- const { kid, alg } = (decodedToken as jwt.Jwt).header;- if (!kid) {+ const header = decodeProtectedHeader(jwtValue);+ if (!header.kid) {throw new UnauthorizedError({ message: "JWT missing kid header" });}- const jwk = findSigningKeyInJwks(jwksJson, kid);- const keyLike = await importJWK(jwk, alg);+ let jwk;+ try {+ jwk = findSigningKeyInJwks(jwksJson, header.kid);+ } catch {+ throw new UnauthorizedError({ message: `No key found in JWKS matching kid: ${header.kid}` });+ }+ const key = await importJWK(jwk, header.alg);try {- const tokenData = crypto.jwt().verify(jwtValue, keyLike as jwt.Secret) as Record<string, unknown>;- return { tokenData, kid };+ const { payload } = await jwtVerify(jwtValue, key);+ return { tokenData: payload as Record<string, unknown>, kid: header.kid };} catch (error) {- if (error instanceof jwt.JsonWebTokenError) {- throw new UnauthorizedError({ message: `Access denied: ${error.message}` });+ if (error instanceof joseErrors.JWTExpired) {+ throw new UnauthorizedError({ message: "JWT-SVID has expired" });}- throw error;+ if (error instanceof joseErrors.JWSSignatureVerificationFailed) {+ throw new UnauthorizedError({ message: "JWT-SVID signature verification failed" });+ }+ throw new UnauthorizedError({ message: "JWT-SVID verification failed" });}};@@ -194,7 +196,13 @@ export const identitySpiffeAuthServiceFactory = ({caCert = orgDataKeyDecryptor({ cipherTextBlob: config.encryptedBundleEndpointCaCert }).toString();}- const bundleJson = await fetchRemoteBundleJwks(config.bundleEndpointUrl, caCert);+ let bundleJson: string;+ try {+ bundleJson = await fetchRemoteBundleJwks(config.bundleEndpointUrl, caCert);+ } catch (error) {+ const msg = error instanceof Error ? error.message : "Unknown error";+ throw new BadRequestError({ message: `Failed to fetch SPIFFE trust bundle from remote endpoint: ${msg}` });+ }const { cipherTextBlob: encryptedCachedBundleJwks } = orgDataKeyEncryptor({plainText: Buffer.from(bundleJson)