import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { describe, it } from "node:test"; import { checkAuthor, checkGuardrails, DEFAULT_GUARDRAILS, type GuardrailError, type GuardrailInput, parseAuthorList, parseGuardrails } from "./agent-guardrails"; import { newPaths, quantSummary, resolveRequestPaths } from "./agent-selection"; import { bearerToken, generateToken, hashToken, isScope } from "./api-token-core"; import { parseModelFilters } from "./api-v1-filters"; import { EMPTY_FILTERS, facetValues, matchesFilters, type SearchableModel } from "./search"; const GB = 1e9; describe("API tokens", () => { it("generates kn_ tokens whose hash and prefix match", () => { const t = generateToken(); assert.match(t.token, /^kn_[A-Za-z0-9_-]{43}$/); assert.equal(t.hash, hashToken(t.token)); assert.ok(t.token.startsWith(t.prefix)); assert.notEqual(generateToken().token, t.token); }); it("reads only well-formed bearer headers", () => { const { token } = generateToken(); assert.equal(bearerToken(`Bearer ${token}`), token); assert.equal(bearerToken(`bearer ${token} `), token); assert.equal(bearerToken(token), null); assert.equal(bearerToken("Bearer kn_short"), null); assert.equal(bearerToken("Basic abc"), null); assert.equal(bearerToken(null), null); }); it("knows the scopes", () => { assert.ok(isScope("models:read")); assert.ok(isScope("downloads:create")); assert.ok(!isScope("models:delete")); assert.ok(!isScope("settings:write")); }); }); describe("guardrails", () => { const ok: GuardrailInput = { repoId: "unsloth/Qwen3-8B-GGUF", requestBytes: 5 * GB, freeBytes: 500 * GB, reservedBytes: 0, openAgentJobs: 0 }; const rejects = (g: Partial, x: Partial, code: GuardrailError["code"], message: RegExp) => assert.throws( () => checkGuardrails({ ...DEFAULT_GUARDRAILS, ...g }, { ...ok, ...x }), (err: GuardrailError) => err.code === code && message.test(err.message), ); it("defaults: approve, 60 GB, 100 GB free, 2 jobs, any author", () => { assert.deepEqual(parseGuardrails(null), DEFAULT_GUARDRAILS); assert.equal(DEFAULT_GUARDRAILS.approvalMode, "approve"); assert.equal(DEFAULT_GUARDRAILS.maxRequestBytes, 60 * GB); assert.equal(DEFAULT_GUARDRAILS.minFreeBytes, 100 * GB); assert.equal(DEFAULT_GUARDRAILS.maxOpenJobs, 2); assert.deepEqual(DEFAULT_GUARDRAILS.allowedAuthors, []); }); it("falls back to defaults for invalid stored values", () => { const g = parseGuardrails({ approvalMode: "yolo", maxRequestBytes: -1, minFreeBytes: "x", maxOpenJobs: 0, allowedAuthors: ["ok", "../bad"] }); assert.equal(g.approvalMode, "approve"); assert.equal(g.maxRequestBytes, DEFAULT_GUARDRAILS.maxRequestBytes); assert.equal(g.minFreeBytes, DEFAULT_GUARDRAILS.minFreeBytes); assert.equal(g.maxOpenJobs, DEFAULT_GUARDRAILS.maxOpenJobs); assert.deepEqual(g.allowedAuthors, ["ok"]); }); it("passes a request within all limits", () => { checkGuardrails(DEFAULT_GUARDRAILS, ok); }); it("rejects requests over the max size, with both sizes in the message", () => { rejects({}, { requestBytes: 74.2 * GB }, "too_large", /exceeds max size per request 60\.0 GB: requested 74\.2 GB/); }); it("rejects when the minimum free space would not remain", () => { rejects({}, { requestBytes: 20 * GB, freeBytes: 110 * GB }, "disk_space", /at least 100\.0 GB must stay free/); }); it("counts space reserved by other open downloads", () => { checkGuardrails(DEFAULT_GUARDRAILS, { ...ok, requestBytes: 20 * GB, freeBytes: 130 * GB }); rejects({}, { requestBytes: 20 * GB, freeBytes: 130 * GB, reservedBytes: 20 * GB }, "disk_space", /20\.0 GB of it reserved/); }); it("rejects when free space is unknown (worker offline)", () => { rejects({}, { freeBytes: null }, "disk_unknown", /worker is offline/); }); it("rejects when too many agent jobs are open", () => { rejects({}, { openAgentJobs: 2 }, "too_many_jobs", /2 pending or running, the limit is 2/); checkGuardrails({ ...DEFAULT_GUARDRAILS, maxOpenJobs: 3 }, { ...ok, openAgentJobs: 2 }); }); it("enforces the author allowlist case-insensitively", () => { const g = { allowedAuthors: ["unsloth", "ggml-org"] }; checkAuthor({ ...DEFAULT_GUARDRAILS, ...g }, "Unsloth/x"); rejects(g, { repoId: "TheBloke/x-GGUF" }, "author_not_allowed", /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/); }); it("parses the allowlist text", () => { assert.deepEqual(parseAuthorList("unsloth, ggml-org Qwen,unsloth"), ["unsloth", "ggml-org", "Qwen"]); assert.deepEqual(parseAuthorList(" "), []); assert.throws(() => parseAuthorList("ok, ../x"), /not a valid/); }); }); describe("request file selection", () => { const files = [ { path: "Qwen3-8B-Q4_K_M.gguf", size: 5 * GB }, { path: "Qwen3-8B-Q8_0.gguf", size: 8.7 * GB }, { path: "mmproj-F16.gguf", size: 0.6 * GB }, { path: "BF16/Qwen3-8B-BF16-00001-of-00002.gguf", size: 8 * GB }, { path: "BF16/Qwen3-8B-BF16-00002-of-00002.gguf", size: 8 * GB }, { path: "README.md", size: 1000 }, ]; it("summarizes quants (weights only, split parts together)", () => { assert.deepEqual( quantSummary(files).map((q) => [q.quant, q.files]), [ ["Q4_K_M", 1], ["Q8_0", 1], ["BF16", 2], ], ); }); it("resolves a quant to its weights plus recommended companions", () => { assert.deepEqual(resolveRequestPaths(files, { quant: "q4_k_m" }, ["vision"]), ["Qwen3-8B-Q4_K_M.gguf", "mmproj-F16.gguf"]); assert.deepEqual(resolveRequestPaths(files, { quant: "Q4_K_M" }, []), ["Qwen3-8B-Q4_K_M.gguf"]); assert.deepEqual(resolveRequestPaths(files, { quant: "BF16" }, []), ["BF16/Qwen3-8B-BF16-00001-of-00002.gguf", "BF16/Qwen3-8B-BF16-00002-of-00002.gguf"]); }); it("explains a missing quant with the available ones", () => { assert.throws(() => resolveRequestPaths(files, { quant: "Q2_K" }, []), /quant "Q2_K" not found in this repo\. Available: .*Q4_K_M/); assert.throws(() => resolveRequestPaths([{ path: "model.safetensors", size: 1 }], { quant: "Q4_K_M" }, []), /no GGUF quants\. Use "include"/); }); it("resolves include globs and rejects ones that match nothing", () => { assert.deepEqual(resolveRequestPaths(files, { include: ["*Q8_0*", "README.md"] }, []), ["Qwen3-8B-Q8_0.gguf", "README.md"]); assert.throws(() => resolveRequestPaths(files, { include: ["*.safetensors"] }, []), /no file in this repo matches/); }); it("finds what a request adds to the selection", () => { assert.deepEqual(newPaths(["a", "b", "c"], ["b"]), ["a", "c"]); assert.deepEqual(newPaths(["a"], ["a", "b"]), []); }); }); describe("GET /api/v1/models filters", () => { it("reads repeated and comma-separated values, requested_by → requester", () => { const { query, filters } = parseModelFilters(new URLSearchParams("q=qwen 8b&author=unsloth,bartowski&quant=Q4_K_M&quant=Q8_0&requested_by=hermes&status=pending_approval")); assert.equal(query, "qwen 8b"); assert.deepEqual(filters, { ...EMPTY_FILTERS, author: ["unsloth", "bartowski"], quant: ["Q4_K_M", "Q8_0"], requester: ["hermes"], status: ["pending_approval"] }); }); it("filters by requester and pending approval like the library", () => { const m: SearchableModel = { repoId: "unsloth/Qwen3-8B-GGUF", author: "unsloth", families: ["Qwen"], baseModels: [], architecture: null, quants: ["Q4_K_M"], tags: [], hubTags: [], pipelineTag: null, license: null, status: "pending", hubStatus: null, requestedBy: "hermes", pendingApproval: true, }; assert.deepEqual(facetValues(m, "status"), ["pending", "pending_approval"]); assert.ok(matchesFilters(m, { ...EMPTY_FILTERS, requester: ["Hermes"] })); assert.ok(!matchesFilters({ ...m, requestedBy: null }, { ...EMPTY_FILTERS, requester: ["hermes"] })); }); }); describe("proxy", () => { // The OIDC gate must skip exactly /api/v1 (bearer tokens), nothing that merely starts like it. const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8"); const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string; const gated = (path: string) => new RegExp(`^${matcher}$`).test(path); it("leaves /api/v1 to token auth and gates everything else", () => { assert.ok(!gated("/api/v1")); assert.ok(!gated("/api/v1/models")); assert.ok(!gated("/api/v1/jobs/01ABC")); assert.ok(gated("/api/v1x")); assert.ok(gated("/api/models")); assert.ok(gated("/api/api-tokens")); assert.ok(gated("/settings/api-tokens")); }); });