58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
|
|
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||
|
|
import { NextRequest } from "next/server";
|
||
|
|
import { assertAgentAuth } from "./agent-auth";
|
||
|
|
|
||
|
|
describe("assertAgentAuth", () => {
|
||
|
|
const ORIGINAL_KEY = process.env.AGENT_API_KEY;
|
||
|
|
|
||
|
|
beforeEach(() => {
|
||
|
|
process.env.AGENT_API_KEY = "test-secret-token";
|
||
|
|
});
|
||
|
|
|
||
|
|
afterEach(() => {
|
||
|
|
if (ORIGINAL_KEY === undefined) {
|
||
|
|
delete process.env.AGENT_API_KEY;
|
||
|
|
} else {
|
||
|
|
process.env.AGENT_API_KEY = ORIGINAL_KEY;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
function reqWith(authHeader: string | null) {
|
||
|
|
const headers: Record<string, string> = {};
|
||
|
|
if (authHeader !== null) headers.authorization = authHeader;
|
||
|
|
return new NextRequest("http://localhost/api/v1/orders", { headers });
|
||
|
|
}
|
||
|
|
|
||
|
|
it("throws when AGENT_API_KEY env var is missing", () => {
|
||
|
|
delete process.env.AGENT_API_KEY;
|
||
|
|
expect(() => assertAgentAuth(reqWith("Bearer test-secret-token"))).toThrow(
|
||
|
|
/AGENT_API_KEY is not configured/
|
||
|
|
);
|
||
|
|
});
|
||
|
|
|
||
|
|
it("accepts a matching bearer token", () => {
|
||
|
|
expect(() => assertAgentAuth(reqWith("Bearer test-secret-token"))).not.toThrow();
|
||
|
|
});
|
||
|
|
|
||
|
|
it("rejects a wrong bearer token", () => {
|
||
|
|
expect(() => assertAgentAuth(reqWith("Bearer wrong"))).toThrow(/Unauthorized/);
|
||
|
|
});
|
||
|
|
|
||
|
|
it("rejects a request with no Authorization header", () => {
|
||
|
|
expect(() => assertAgentAuth(reqWith(null))).toThrow(/Unauthorized/);
|
||
|
|
});
|
||
|
|
|
||
|
|
it("rejects a non-Bearer scheme", () => {
|
||
|
|
expect(() => assertAgentAuth(reqWith("Basic test-secret-token"))).toThrow(/Unauthorized/);
|
||
|
|
});
|
||
|
|
|
||
|
|
it("tags the thrown error with status 401", () => {
|
||
|
|
try {
|
||
|
|
assertAgentAuth(reqWith("Bearer wrong"));
|
||
|
|
throw new Error("expected to throw");
|
||
|
|
} catch (err) {
|
||
|
|
expect((err as Error & { status?: number }).status).toBe(401);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|