Skip to content

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

fix(identity-access-token): answer the expiry recheck like any expired token

Scott Wilsonda614b034907
diff --git a/backend/src/services/identity-access-token/identity-access-token-expiry-response.test.ts b/backend/src/services/identity-access-token/identity-access-token-expiry-response.test.ts
new file mode 100644
index 0000000000..d42af25ec4
--- /dev/null
+++ b/backend/src/services/identity-access-token/identity-access-token-expiry-response.test.ts
@@ -0,0 +1,56 @@
+import fastify from "fastify";
+import jwt from "jsonwebtoken";
+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
+
+import { fastifyErrHandler } from "@app/server/plugins/error-handler";
+
+import { assertJwtNotExpired } from "./identity-access-token-fns";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ MAX_MACHINE_IDENTITY_TOKEN_AGE: 7_776_000 }),
+ getOriginalConfig: () => ({})
+}));
+
+const NOW = 1_700_000_000;
+
+// The expiry recheck runs after jwt.verify has already passed, so its refusal has to look exactly like
+// the one jwt.verify gives an expired token. Clients branch on the status code to decide whether to
+// re-authenticate.
+describe("expired-token response", () => {
+ const server = fastify();
+
+ beforeAll(async () => {
+ await server.register(fastifyErrHandler);
+ server.get("/recheck", async () => {
+ assertJwtNotExpired({ exp: NOW, nowSeconds: NOW });
+ return {};
+ });
+ server.get("/verify", async () => {
+ const token = jwt.sign({ exp: NOW }, "secret");
+ jwt.verify(token, "secret");
+ return {};
+ });
+ await server.ready();
+ });
+
+ afterAll(async () => {
+ await server.close();
+ });
+
+ test("the recheck answers like an expired token rejected by jwt.verify", async () => {
+ const recheck = await server.inject({ method: "GET", url: "/recheck" });
+ const verify = await server.inject({ method: "GET", url: "/verify" });
+
+ expect(recheck.statusCode).toBe(403);
+ expect(recheck.json()).toMatchObject({
+ statusCode: 403,
+ error: "TokenError",
+ message: "Your token has expired. Please re-authenticate."
+ });
+ const { reqId: recheckReqId, ...recheckBody } = recheck.json<Record<string, unknown>>();
+ const { reqId: verifyReqId, ...verifyBody } = verify.json<Record<string, unknown>>();
+ expect(recheckReqId).toBeDefined();
+ expect(verifyReqId).toBeDefined();
+ expect(recheckBody).toEqual(verifyBody);
+ });
+});
diff --git a/backend/src/services/identity-access-token/identity-access-token-fns.test.ts b/backend/src/services/identity-access-token/identity-access-token-fns.test.ts
index ba865ec3de..dea6a71af1 100644
--- a/backend/src/services/identity-access-token/identity-access-token-fns.test.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-fns.test.ts
@@ -1,6 +1,8 @@
+import jwt from "jsonwebtoken";
import { afterEach, describe, expect, test, vi } from "vitest";
import {
+ assertJwtNotExpired,
computeIssuedTtl,
computePerTokenMarkerExpiry,
computeReseededUsesRemainingTtl,
@@ -9,7 +11,6 @@ import {
computeTokenAuthRevokeMarkerExpiry,
computeUsesRemainingTtl,
evaluateRevocationMarkers,
- hasJwtExpired,
hasLegacyTokenWithoutExpExceededMaxAge,
IDENTITY_REVOCATION_MARKER_SKEW_SECONDS,
isMembershipDenyReason
@@ -210,14 +211,15 @@ describe("computeReseededUsesRemainingTtl", () => {
});
});
-describe("hasJwtExpired", () => {
- test("is true from the exp second onward", () => {
- expect(hasJwtExpired({ exp: NOW, nowSeconds: NOW })).toBe(true);
- expect(hasJwtExpired({ exp: NOW + 1, nowSeconds: NOW })).toBe(false);
+describe("assertJwtNotExpired", () => {
+ test("throws the jwt.verify expiry error from the exp second onward", () => {
+ expect(() => assertJwtNotExpired({ exp: NOW, nowSeconds: NOW })).toThrow(jwt.TokenExpiredError);
+ expect(() => assertJwtNotExpired({ exp: NOW, nowSeconds: NOW })).toThrow("jwt expired");
+ expect(() => assertJwtNotExpired({ exp: NOW + 1, nowSeconds: NOW })).not.toThrow();
});
- test("is false for a legacy JWT with no exp", () => {
- expect(hasJwtExpired({ nowSeconds: NOW })).toBe(false);
+ test("passes a legacy JWT with no exp", () => {
+ expect(() => assertJwtNotExpired({ nowSeconds: NOW })).not.toThrow();
});
});
diff --git a/backend/src/services/identity-access-token/identity-access-token-fns.ts b/backend/src/services/identity-access-token/identity-access-token-fns.ts
index 52c110b8af..eed598f6a1 100644
--- a/backend/src/services/identity-access-token/identity-access-token-fns.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-fns.ts
@@ -1,3 +1,5 @@
+import jwt from "jsonwebtoken";
+
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { generateCacheKeyFromData } from "@app/lib/crypto/cache";
@@ -148,13 +150,19 @@ export const computeIssuedTtl = ({
// so a revoked token can't slip through by dropping the record too early.
export const IDENTITY_REVOCATION_MARKER_SKEW_SECONDS = 300;
-export const hasJwtExpired = ({
+// For a JWT that was verified earlier in the request and has expired since. Throws the same error
+// jwt.verify throws, so the caller gets the response any other expired token gets.
+export const assertJwtNotExpired = ({
exp,
nowSeconds = Math.floor(Date.now() / 1000)
}: {
exp?: number;
nowSeconds?: number;
-}): boolean => typeof exp === "number" && nowSeconds >= exp;
+}): void => {
+ if (typeof exp === "number" && nowSeconds >= exp) {
+ throw new jwt.TokenExpiredError("jwt expired", new Date(exp * 1000));
+ }
+};
// The uses-remaining counter is read after the JWT is verified, so it has to outlive the JWT by
// enough to cover a request in flight. A counter that vanishes mid-request reads as lost, and a lost
diff --git a/backend/src/services/identity-access-token/identity-access-token-service.test.ts b/backend/src/services/identity-access-token/identity-access-token-service.test.ts
index d04270b269..ae2ce7e6ca 100644
--- a/backend/src/services/identity-access-token/identity-access-token-service.test.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-service.test.ts
@@ -1,3 +1,4 @@
+import jwt from "jsonwebtoken";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
import { IdentityAuthMethod, TableName } from "@app/db/schemas";
@@ -392,7 +393,7 @@ describe("identityAccessTokenServiceFactory", () => {
await expect(
service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3 }), "10.0.0.1")
- ).rejects.toThrow("has expired");
+ ).rejects.toThrow(jwt.TokenExpiredError);
expect(keyStore.setItemWithExpiry).not.toHaveBeenCalledWith(
expect.stringContaining("identity-token-uses-remaining:"),
expect.anything(),
@@ -498,7 +499,7 @@ describe("identityAccessTokenServiceFactory", () => {
return null;
});
- await expect(service.renewAccessToken({ accessToken })).rejects.toThrow("has expired");
+ await expect(service.renewAccessToken({ accessToken })).rejects.toThrow(jwt.TokenExpiredError);
expect(keyStore.setItemWithExpiry).not.toHaveBeenCalledWith(
expect.stringContaining("identity-token-uses-remaining:"),
expect.anything(),
diff --git a/backend/src/services/identity-access-token/identity-access-token-service.ts b/backend/src/services/identity-access-token/identity-access-token-service.ts
index fcfe86b692..442193f146 100644
--- a/backend/src/services/identity-access-token/identity-access-token-service.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-service.ts
@@ -17,6 +17,7 @@ import { TIdentityDALFactory } from "../identity/identity-dal";
import { TOrgDALFactory } from "../org/org-dal";
import { TIdentityAccessTokenDALFactory } from "./identity-access-token-dal";
import {
+ assertJwtNotExpired,
assertMinimalRenewClaims,
assertRevocableClaims,
computeIssuedTtl,
@@ -26,7 +27,6 @@ import {
computeUsesRemainingTtl,
evaluateRevocationMarkers,
hasFullRenewClaims,
- hasJwtExpired,
hasLegacyTokenWithoutExpExceededMaxAge,
hasNonWildcardTrustedIps,
isMembershipDenyReason,
@@ -496,11 +496,7 @@ export const identityAccessTokenServiceFactory = ({
// and allow this request; subsequent requests decrement the live counter.
// The JWT was verified before the read, so recheck it: a token that expired in
// between must not be handed a fresh budget.
- if (hasJwtExpired({ exp: token.exp })) {
- throw new UnauthorizedError({
- message: "Failed to authorize: identity access token has expired, please re-authenticate"
- });
- }
+ assertJwtNotExpired({ exp: token.exp });
await setUsesRemaining(
token.identityId,
tokenId,
@@ -629,8 +625,8 @@ export const identityAccessTokenServiceFactory = ({
}
const numUsesLimit = decodedToken.numUsesLimit ?? source.numUsesLimit;
- if (numUsesLimit > 0 && existingRemaining === null && hasJwtExpired({ exp: decodedToken.exp, nowSeconds })) {
- throw new UnauthorizedError({ message: "Cannot renew: identity access token has expired" });
+ if (numUsesLimit > 0 && existingRemaining === null) {
+ assertJwtNotExpired({ exp: decodedToken.exp, nowSeconds });
}
const ipRestrictionEnabled = Boolean(decodedToken.ipRestrictionEnabled);