Skip to content

Add JWT revocation list #205

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/api/plugins/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,11 +265,27 @@ const authPlugin: FastifyPluginAsync = async (fastify, _options) => {
request.log.debug(
`Start to verifying JWT took ${new Date().getTime() - startTime} ms.`,
);
request.tokenPayload = verifiedTokenData;
request.username =
// check revocation list for token
const proposedUsername =
verifiedTokenData.email ||
verifiedTokenData.upn?.replace("acm.illinois.edu", "illinois.edu") ||
verifiedTokenData.sub;
const { redisClient, log: logger } = fastify;
const revokedResult = await getKey<{ isInvalid: boolean }>({
redisClient,
key: `tokenRevocationList:${verifiedTokenData.uti}`,
logger,
});
if (revokedResult) {
fastify.log.info(
`Revoked token ${verifiedTokenData.uti} for ${proposedUsername} was attempted.`,
);
throw new UnauthenticatedError({
message: "Invalid token.",
});
}
request.tokenPayload = verifiedTokenData;
request.username = proposedUsername;
const expectedRoles = new Set(validRoles);
const cachedRoles = await getKey<string[]>({
key: `${AUTH_CACHE_PREFIX}${request.username}:roles`,
Expand Down
19 changes: 19 additions & 0 deletions src/api/routes/clearSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { FastifyPluginAsync } from "fastify";
import rateLimiter from "api/plugins/rateLimiter.js";
import { withRoles, withTags } from "api/components/index.js";
import { clearAuthCache } from "api/functions/authorization.js";
import { setKey } from "api/functions/redisCache.js";

const clearSessionPlugin: FastifyPluginAsync = async (fastify, _options) => {
fastify.register(rateLimiter, {
Expand All @@ -26,7 +27,25 @@ const clearSessionPlugin: FastifyPluginAsync = async (fastify, _options) => {
const username = [request.username!];
const { redisClient } = fastify;
const { log: logger } = fastify;

await clearAuthCache({ redisClient, username, logger });
if (!request.tokenPayload) {
return;
}
const now = Date.now() / 1000;
const tokenExpiry = request.tokenPayload.exp;
const expiresIn = Math.ceil(tokenExpiry - now);
const tokenId = request.tokenPayload.uti;
// if the token expires more than 10 seconds after now, add to a revoke list
if (expiresIn > 10) {
await setKey({
redisClient,
key: `tokenRevocationList:${tokenId}`,
data: JSON.stringify({ isInvalid: true }),
logger,
expiresIn,
});
}
},
);
};
Expand Down
40 changes: 40 additions & 0 deletions tests/live/clearSession.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, expect, test } from "vitest";
import { createJwt, getBaseEndpoint } from "./utils.js";
import { allAppRoles } from "../../src/common/roles.js";

const baseEndpoint = getBaseEndpoint();

describe("Session clearing tests", async () => {
test("Token is revoked on logout", async () => {
const token = await createJwt();
// token works
const response = await fetch(`${baseEndpoint}/api/v1/protected`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
expect(response.status).toBe(200);
const responseBody = await response.json();
expect(responseBody).toStrictEqual({
username: "[email protected]",
roles: allAppRoles,
});
// user logs out
const clearResponse = await fetch(`${baseEndpoint}/api/v1/clearSession`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
});
expect(clearResponse.status).toBe(201);
// token should be revoked
const responseFail = await fetch(`${baseEndpoint}/api/v1/protected`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
expect(responseFail.status).toBe(403);
});
});
5 changes: 3 additions & 2 deletions tests/live/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
SecretsManagerClient,
GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";
import { randomUUID } from "node:crypto";

export const getSecretValue = async (
secretId: string,
Expand Down Expand Up @@ -47,7 +48,7 @@ export async function createJwt(
iss: "custom_jwt",
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 3600 * 24, // Token expires after 24 hour
exp: Math.floor(Date.now() / 1000) + 3600 * 1, // Token expires after 1 hour
acr: "1",
aio: "AXQAi/8TAAAA",
amr: ["pwd"],
Expand All @@ -64,7 +65,7 @@ export async function createJwt(
sub: "subject",
tid: "tenant-id",
unique_name: username,
uti: "uti-value",
uti: randomUUID().toString(),
ver: "1.0",
};
const token = jwt.sign(payload, secretData.JWTKEY, { algorithm: "HS256" });
Expand Down
Loading