Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/api/src/auth.test.ts
T

30 lines
2.0 KiB
TypeScript

import { describe, expect, test } from "vitest";
import { authenticateServiceRequest, extractApiKeyFromRequest, extractBearerToken, isValidServiceToken } from "./auth.js";
describe("api auth primitives", () => {
test("extracts bearer tokens with compatible casing and spacing", () => {
expect(extractBearerToken(new Request("https://api.test", { headers: { authorization: "Bearer service-token" } }))).toBe("service-token");
expect(extractBearerToken(new Request("https://api.test", { headers: { authorization: "bearer service-token" } }))).toBe("service-token");
expect(extractBearerToken(new Request("https://api.test", { headers: { authorization: "Basic service-token" } }))).toBeUndefined();
});
test("extracts API keys from JSON body or x-api-key header without using bearer tokens", () => {
expect(extractApiKeyFromRequest(new Request("https://api.test"), { apiKey: "json-key" })).toBe("json-key");
expect(extractApiKeyFromRequest(new Request("https://api.test", { headers: { "x-api-key": "header-key" } }), undefined)).toBe("header-key");
expect(extractApiKeyFromRequest(new Request("https://api.test", { headers: { authorization: "Bearer bearer-key" } }), undefined)).toBeNull();
});
test("validates configured service tokens and creates service principals", () => {
const config = { apiAccessToken: "secret" };
expect(isValidServiceToken("secret", config)).toBe(true);
expect(isValidServiceToken("wrong", config)).toBe(false);
expect(isValidServiceToken("secret", "secret")).toBe(true);
expect(authenticateServiceRequest(new Request("https://api.test", { headers: { authorization: "Bearer secret" } }), config)).toEqual({
type: "service-token",
});
expect(authenticateServiceRequest(new Request("https://api.test", { headers: { "x-api-key": "secret" } }), config)).toBeNull();
expect(authenticateServiceRequest(new Request("https://api.test", { headers: { authorization: "Bearer wrong" } }), config)).toBeNull();
});
});