Files
0pt/tests/auth/internal-token.test.ts
T

54 lines
2.3 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { verifyInternalServiceToken, INTERNAL_TOKEN_HEADER } from "@/src/auth/internal-token";
function headers(map: Record<string, string> = {}): { get(name: string): string | null } {
const lower = new Map(Object.entries(map).map(([k, v]) => [k.toLowerCase(), v]));
return { get: (name: string) => lower.get(name.toLowerCase()) ?? null };
}
describe("verifyInternalServiceToken", () => {
it("accepts a header that matches the configured INTERNAL_TOKEN exactly", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "s3cr3t" }), {
INTERNAL_TOKEN: "s3cr3t",
});
expect(ok).toBe(true);
});
it("rejects a mismatched token", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "wrong" }), {
INTERNAL_TOKEN: "s3cr3t",
});
expect(ok).toBe(false);
});
it("rejects a missing header even when INTERNAL_TOKEN is configured", () => {
const ok = verifyInternalServiceToken(headers({}), { INTERNAL_TOKEN: "s3cr3t" });
expect(ok).toBe(false);
});
it("FAILS CLOSED: an unset INTERNAL_TOKEN never authenticates, even against an empty header value", () => {
// Regression guard: quality_bridge.py sends `os.getenv("INTERNAL_TOKEN", "")`
// -- if the edge's own INTERNAL_TOKEN were also unset, a naive `provided
// === expected` comparison of two empty strings would wrongly authenticate.
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "" }), { INTERNAL_TOKEN: undefined });
expect(ok).toBe(false);
});
it("FAILS CLOSED: an unset INTERNAL_TOKEN never authenticates even a non-empty header", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "anything" }), {
INTERNAL_TOKEN: undefined,
});
expect(ok).toBe(false);
});
it("rejects a whitespace-only configured token (trimmed to empty)", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: " " }), { INTERNAL_TOKEN: " " });
expect(ok).toBe(false);
});
it("is case-sensitive on the header name lookup contract but tolerant of header-name casing via the HeaderLookup adapter", () => {
const ok = verifyInternalServiceToken(headers({ "X-Internal-Token": "s3cr3t" }), { INTERNAL_TOKEN: "s3cr3t" });
expect(ok).toBe(true);
});
});