Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/chat/src/gateway-auth.server.test.ts
T

152 lines
6.9 KiB
TypeScript

import jwt, { type Algorithm, type JwtPayload } from "jsonwebtoken";
import { describe, expect, it } from "vitest";
import {
CHAT_GATEWAY_TOKEN_AUDIENCE,
CHAT_GATEWAY_TOKEN_ISSUER,
CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
CHAT_GATEWAY_TOKEN_PURPOSE,
issueChatGatewayToken,
verifyChatGatewayToken,
} from "./gateway-auth.server.js";
const SECRET = "chat-gateway-secret-at-least-32-bytes-long";
const OTHER_SECRET = "other-chat-secret-at-least-32-bytes-long";
const NOW = new Date("2026-07-15T12:00:00.000Z");
const NOW_SECONDS = Math.floor(NOW.getTime() / 1_000);
const TOKEN_ID = "123e4567-e89b-42d3-a456-426614174000";
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
const identity = {
userId: "user_1",
tenantId: "tenant_1",
sessionId: "session_1",
} as const;
function issue(overrides: Partial<Parameters<typeof issueChatGatewayToken>[0]> = {}): string {
return issueChatGatewayToken({ ...identity, secret: SECRET, now: NOW, ...overrides });
}
function signClaims(
claims: Record<string, unknown> = {},
options: {
algorithm?: Algorithm;
audience?: string | string[];
expiresIn?: number;
issuer?: string;
secret?: string;
} = {}
): string {
return jwt.sign(
{
tenantId: identity.tenantId,
sid: identity.sessionId,
purpose: CHAT_GATEWAY_TOKEN_PURPOSE,
iat: NOW_SECONDS,
...claims,
},
options.secret ?? SECRET,
{
algorithm: options.algorithm ?? "HS256",
audience: options.audience ?? CHAT_GATEWAY_TOKEN_AUDIENCE,
expiresIn: options.expiresIn ?? CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
issuer: options.issuer ?? CHAT_GATEWAY_TOKEN_ISSUER,
jwtid: TOKEN_ID,
subject: identity.userId,
}
);
}
describe("chat gateway JWT contract", () => {
it("issues a strict HS256 identity token and verifies it without authorization snapshots", () => {
const token = issue();
const decoded = jwt.decode(token) as JwtPayload;
const tokenId = decoded.jti as string;
expect(Object.keys(decoded).sort()).toEqual(["aud", "exp", "iat", "iss", "jti", "purpose", "sid", "sub", "tenantId"]);
expect(decoded).toMatchObject({
iss: CHAT_GATEWAY_TOKEN_ISSUER,
aud: CHAT_GATEWAY_TOKEN_AUDIENCE,
sub: identity.userId,
tenantId: identity.tenantId,
sid: identity.sessionId,
purpose: CHAT_GATEWAY_TOKEN_PURPOSE,
iat: NOW_SECONDS,
exp: NOW_SECONDS + CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
});
expect(tokenId).toMatch(UUID_PATTERN);
expect(decoded).not.toHaveProperty("permissions");
expect(decoded).not.toHaveProperty("channelIds");
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW })).toEqual({
userId: identity.userId,
tenantId: identity.tenantId,
sessionId: identity.sessionId,
tokenId,
issuedAt: NOW_SECONDS,
expiresAt: NOW_SECONDS + CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
});
});
it("allows a shorter lifetime but refuses issuance beyond 900 seconds", () => {
const shortToken = issue({ ttlSeconds: 60 });
expect((jwt.decode(shortToken) as JwtPayload).exp).toBe(NOW_SECONDS + 60);
expect(() => issue({ ttlSeconds: CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS + 1 })).toThrow("TTL is invalid");
expect(() => issue({ ttlSeconds: 0 })).toThrow("TTL is invalid");
});
it("refuses issuance with weak configuration or malformed identity claims", () => {
expect(() => issue({ secret: "too-short" })).toThrow("auth secret is unavailable");
expect(() => issue({ secret: ` ${SECRET}` })).toThrow("auth secret is unavailable");
expect(() => issue({ userId: " " })).toThrow("userId is invalid");
expect(() => issue({ tenantId: "tenant\u0000evil" })).toThrow("tenantId is invalid");
expect(() => issue({ sessionId: "" })).toThrow("sessionId is invalid");
expect(() => issue({ now: new Date(Number.NaN) })).toThrow("clock is invalid");
});
it("pins the signature algorithm, dedicated secret, issuer and audience", () => {
expect(verifyChatGatewayToken(signClaims({}, { algorithm: "HS384" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(issue(), { secret: OTHER_SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({}, { issuer: "other-service" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({}, { audience: "other-gateway" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({}, { audience: [CHAT_GATEWAY_TOKEN_AUDIENCE] }), { secret: SECRET, now: NOW })).toBeNull();
});
it("rejects wrong purpose, extra authorization claims and lifetimes beyond the contract", () => {
expect(verifyChatGatewayToken(signClaims({ purpose: "hocuspocus" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({ permissions: ["chat.admin"] }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({ channelIds: ["chat_1"] }), { secret: SECRET, now: NOW })).toBeNull();
expect(
verifyChatGatewayToken(signClaims({}, { expiresIn: CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS + 1 }), {
secret: SECRET,
now: NOW,
})
).toBeNull();
});
it("requires every identity and temporal claim", () => {
const validClaims = jwt.decode(issue()) as JwtPayload;
for (const key of ["sub", "tenantId", "sid", "purpose", "jti", "iat", "exp"] as const) {
const claims = { ...validClaims };
delete claims[key];
const token = jwt.sign(claims, SECRET, { algorithm: "HS256", noTimestamp: true });
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW }), key).toBeNull();
}
});
it("honors only a bounded clock tolerance and rejects expired or future-issued tokens", () => {
const token = issue({ ttlSeconds: 60 });
expect(verifyChatGatewayToken(token, { secret: SECRET, now: new Date(NOW.getTime() + 60_000), clockToleranceSeconds: 0 })).toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: new Date(NOW.getTime() + 60_000), clockToleranceSeconds: 1 })).not.toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: new Date(NOW.getTime() - 31_000), clockToleranceSeconds: 30 })).toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW, clockToleranceSeconds: 31 })).toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW, clockToleranceSeconds: -1 })).toBeNull();
});
it("fails closed for malformed tokens, weak verification secrets and invalid verifier clocks", () => {
expect(verifyChatGatewayToken("not-a-jwt", { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken("x".repeat(4_097), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(issue(), { secret: "too-short", now: NOW })).toBeNull();
expect(verifyChatGatewayToken(issue(), { secret: SECRET, now: new Date(Number.NaN) })).toBeNull();
});
});