| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| import test from "node:test";
|
| import assert from "node:assert/strict";
|
| import Module from "node:module";
|
|
|
|
|
|
|
|
|
| type ValidateFn = (key: string) => boolean | Promise<boolean>;
|
| let mockValidateApiKey: ValidateFn = () => false;
|
|
|
| const originalResolve = (Module as unknown as { _resolveFilename: typeof Module._resolveFilename })
|
| ._resolveFilename;
|
|
|
|
|
|
|
|
|
| const POLICY_IMPORT_TARGET = "src/lib/db/apiKeys";
|
|
|
| (Module as unknown as { _resolveFilename: typeof Module._resolveFilename })._resolveFilename =
|
| function patched(this: unknown, request: string, ...rest: unknown[]) {
|
| if (request.includes(POLICY_IMPORT_TARGET)) {
|
|
|
| const stubPath = new URL("./__stub_apiKeys.mjs", import.meta.url).pathname;
|
|
|
| return originalResolve.call(this, stubPath, ...rest);
|
| }
|
|
|
| return originalResolve.call(this, request, ...rest);
|
| };
|
|
|
|
|
| import fs from "node:fs";
|
| import os from "node:os";
|
| import path from "node:path";
|
| import { fileURLToPath } from "node:url";
|
|
|
| const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
|
| const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omr-clientapi-policy-fallback-"));
|
| process.env.DATA_DIR = TEST_DATA_DIR;
|
|
|
| const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
| const STUB_PATH = path.join(__dirname, "__stub_apiKeys.mjs");
|
| fs.writeFileSync(
|
| STUB_PATH,
|
| `export const validateApiKey = (key) => globalThis.__mockValidateApiKey(key);\n`
|
| );
|
|
|
|
|
| (globalThis as unknown as { __mockValidateApiKey: ValidateFn }).__mockValidateApiKey = (key) =>
|
| mockValidateApiKey(key);
|
|
|
| test.after(() => {
|
| try {
|
| fs.unlinkSync(STUB_PATH);
|
| } catch {
|
|
|
| }
|
| fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
| if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
|
| else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
|
| });
|
|
|
|
|
|
|
| async function loadPolicy() {
|
| const mod = await import(`../../../src/server/authz/policies/clientApi.ts?ts=${Date.now()}`);
|
| return mod.clientApiPolicy;
|
| }
|
|
|
| function ctx(headers: Headers, normalizedPath = "/api/v1/chat/completions") {
|
| return {
|
| request: { method: "POST", headers, url: `http://localhost${normalizedPath}` },
|
| classification: {
|
| routeClass: "CLIENT_API" as const,
|
| reason: "client_api_v1" as const,
|
| normalizedPath,
|
| },
|
| requestId: "req_test",
|
| };
|
| }
|
|
|
|
|
|
|
| test.beforeEach(() => {
|
|
|
| mockValidateApiKey = () => false;
|
| delete process.env.REQUIRE_API_KEY;
|
| });
|
|
|
| test("#2257 β invalid bearer + REQUIRE_API_KEY=true β 401", async () => {
|
| process.env.REQUIRE_API_KEY = "true";
|
| const policy = await loadPolicy();
|
| const headers = new Headers({ authorization: "Bearer sk-stub-bogus" });
|
| const out = await policy.evaluate(ctx(headers));
|
| assert.equal(out.allow, false);
|
| if (!out.allow) {
|
| assert.equal(out.status, 401);
|
| assert.equal(out.code, "AUTH_002");
|
| }
|
| });
|
|
|
| test("#2257 β invalid bearer + REQUIRE_API_KEY=false β anonymous (with warning log)", async () => {
|
| const originalWarn = console.warn;
|
| const warnings: string[] = [];
|
| console.warn = (msg: string) => warnings.push(String(msg));
|
| try {
|
| const policy = await loadPolicy();
|
| const headers = new Headers({ authorization: "Bearer sk-stub-bogus" });
|
| const out = await policy.evaluate(ctx(headers));
|
| assert.equal(out.allow, true);
|
| if (out.allow) {
|
| assert.equal(out.subject.kind, "anonymous");
|
| assert.equal(out.subject.id, "local");
|
| }
|
| assert.ok(
|
| warnings.some((w) => w.includes("[clientApiPolicy]") && w.includes("REQUIRE_API_KEY=false")),
|
| "expected a warning about the fallback"
|
| );
|
| } finally {
|
| console.warn = originalWarn;
|
| }
|
| });
|
|
|
| test("#2257 β invalid x-api-key + REQUIRE_API_KEY=false β anonymous (with warning log)", async () => {
|
| const originalWarn = console.warn;
|
| const warnings: string[] = [];
|
| console.warn = (msg: string) => warnings.push(String(msg));
|
| try {
|
| const policy = await loadPolicy();
|
| const headers = new Headers({ "x-api-key": "sk-stub-bogus" });
|
| const out = await policy.evaluate(ctx(headers));
|
| assert.equal(out.allow, true);
|
| if (out.allow) {
|
| assert.equal(out.subject.kind, "anonymous");
|
| assert.equal(out.subject.id, "local");
|
| }
|
| assert.ok(
|
| warnings.some((w) => w.includes("[clientApiPolicy]") && w.includes("REQUIRE_API_KEY=false")),
|
| "expected a warning about the fallback"
|
| );
|
| } finally {
|
| console.warn = originalWarn;
|
| }
|
| });
|
|
|
| test("#2257 β fallback warning masks the x-api-key (only last-4 in log)", async () => {
|
| const originalWarn = console.warn;
|
| const warnings: string[] = [];
|
| console.warn = (msg: string) => warnings.push(String(msg));
|
| try {
|
| const policy = await loadPolicy();
|
| const headers = new Headers({ "x-api-key": "sk-secretprefix-secretmiddle-XYZW" });
|
| const out = await policy.evaluate(ctx(headers));
|
| assert.equal(out.allow, true);
|
| assert.ok(
|
| warnings.every((w) => !w.includes("secretprefix") && !w.includes("secretmiddle")),
|
| "warning leaked the full bearer; only masked key id should be logged"
|
| );
|
| assert.ok(
|
| warnings.some((w) => w.includes("key_XYZW")),
|
| "expected masked key id (last-4) in the warning"
|
| );
|
| } finally {
|
| console.warn = originalWarn;
|
| }
|
| });
|
|
|
| test("#2257 β fallback warning masks the bearer (only last-4 in log)", async () => {
|
| const originalWarn = console.warn;
|
| const warnings: string[] = [];
|
| console.warn = (msg: string) => warnings.push(String(msg));
|
| try {
|
| const policy = await loadPolicy();
|
| const headers = new Headers({ authorization: "Bearer sk-secretprefix-secretmiddle-XYZW" });
|
| const out = await policy.evaluate(ctx(headers));
|
| assert.equal(out.allow, true);
|
| assert.ok(
|
| warnings.every((w) => !w.includes("secretprefix") && !w.includes("secretmiddle")),
|
| "warning leaked the full bearer; only masked key id should be logged"
|
| );
|
| assert.ok(
|
| warnings.some((w) => w.includes("key_XYZW")),
|
| "expected masked key id (last-4) in the warning"
|
| );
|
| } finally {
|
| console.warn = originalWarn;
|
| }
|
| });
|
|
|
| test("#2257 β no bearer + REQUIRE_API_KEY=false β anonymous (unchanged, no fallback warning)", async () => {
|
| const originalWarn = console.warn;
|
| const warnings: string[] = [];
|
| console.warn = (msg: string) => warnings.push(String(msg));
|
| try {
|
| const policy = await loadPolicy();
|
| const out = await policy.evaluate(ctx(new Headers()));
|
| assert.equal(out.allow, true);
|
| if (out.allow) {
|
| assert.equal(out.subject.kind, "anonymous");
|
| }
|
|
|
|
|
| assert.ok(
|
| warnings.every((w) => !w.includes("[clientApiPolicy]")),
|
| "no fallback warning expected when no bearer was sent"
|
| );
|
| } finally {
|
| console.warn = originalWarn;
|
| }
|
| });
|
|
|