// /api/v1 end to end against a temporary SQLite database and a stubbed Hugging Face API: // token auth, scopes, every guardrail rejection, idempotency, approve/reject. // Runs with `--conditions=react-server` (see package.json) so "server-only" modules load. import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, before, describe, it } from "node:test"; const dir = mkdtempSync(join(tmpdir(), "kaname-api-")); process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`; process.env.MODELS_DIR = join(dir, "models"); delete process.env.HF_TOKEN; const GB = 1e9; const SHA = { a: "a".repeat(40), b: "b".repeat(40), c: "c".repeat(40), d: "d".repeat(40) }; /** Fake Hub: repo → commit + files. */ const REPOS: Record = { "unsloth/Test-GGUF": { sha: SHA.a, files: [ ["Test-Q4_K_M.gguf", 5 * GB], ["Test-Q8_0.gguf", 9 * GB], ["Test-F16.gguf", 70 * GB], ["README.md", 1000], ], }, "unsloth/Other-GGUF": { sha: SHA.b, files: [["Other-Q4_K_M.gguf", 2 * GB]] }, "ggml-org/Third-GGUF": { sha: SHA.c, files: [["Third-Q4_K_M.gguf", 3 * GB]] }, "TheBloke/Old-GGUF": { sha: SHA.d, files: [["Old-Q4_K_M.gguf", 1 * GB]] }, }; const realFetch = globalThis.fetch; globalThis.fetch = (async (input: string | URL | Request) => { const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url); const m = url.pathname.match(/^\/api\/models\/([^/]+\/[^/]+)\/(revision|tree)\/([^/]+)/); // Like the Hub: repo ids are case-insensitive, the response has the canonical one. const id = m && Object.keys(REPOS).find((k) => k.toLowerCase() === decodeURIComponent(m[1]).toLowerCase()); const repo = id && REPOS[id]; if (!m || !id || !repo) return new Response("not found", { status: 404 }); const rev = decodeURIComponent(m[3]); if (rev !== "main" && rev !== repo.sha) return new Response("", { status: 404, headers: { "x-error-code": "RevisionNotFound" } }); if (m[2] === "revision") return Response.json({ id, sha: repo.sha, gated: false, private: false, tags: [] }); return Response.json(repo.files.map(([path, size]) => ({ type: "file", path, size, oid: "0".repeat(40), lfs: { oid: "e".repeat(64), size } }))); }) as typeof fetch; type Mods = { db: typeof import("./db/client"); schema: typeof import("./db/schema"); tokens: typeof import("./api-tokens"); settings: typeof import("./settings"); agent: typeof import("./agent-downloads"); v1: typeof import("../app/api/v1/route"); downloads: typeof import("../app/api/v1/downloads/route"); job: typeof import("../app/api/v1/jobs/[id]/route"); models: typeof import("../app/api/v1/models/route"); disk: typeof import("../app/api/v1/disk/route"); }; let M: Mods; let full: string; // models:read + downloads:create let readOnly: string; const call = async (handler: (req: Request, ctx: never) => Promise, path: string, opts: { token?: string; body?: unknown; params?: Record } = {}) => { const req = new Request(`http://kaname.test${path}`, { method: opts.body ? "POST" : "GET", headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" }, body: opts.body ? JSON.stringify(opts.body) : undefined, }); const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never); return { status: res.status, body: (await res.json()) as Record }; // eslint-disable-line @typescript-eslint/no-explicit-any }; const request = (body: unknown, token = full) => call(M.downloads.POST, "/api/v1/downloads", { token, body }); async function setFree(bytes: number) { const { db } = M.db; const now = new Date(); await db() .insert(M.schema.workerState) .values({ id: "worker", startedAt: now, heartbeatAt: now, modelsDirFreeBytes: bytes, modelsDirTotalBytes: 2000 * GB }) .onConflictDoUpdate({ target: M.schema.workerState.id, set: { heartbeatAt: now, modelsDirFreeBytes: bytes } }); } before(async () => { const { runMigrations } = await import("./db/migrate"); await runMigrations(); M = { db: await import("./db/client"), schema: await import("./db/schema"), tokens: await import("./api-tokens"), settings: await import("./settings"), agent: await import("./agent-downloads"), v1: await import("../app/api/v1/route"), downloads: await import("../app/api/v1/downloads/route"), job: await import("../app/api/v1/jobs/[id]/route"), models: await import("../app/api/v1/models/route"), disk: await import("../app/api/v1/disk/route"), }; full = (await M.tokens.createToken("hermes", ["models:read", "downloads:create"])).token; readOnly = (await M.tokens.createToken("reader", ["models:read"])).token; await setFree(500 * GB); }); after(() => { globalThis.fetch = realFetch; // Close the database first; Windows can't delete an open file. (globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { // Windows may still hold the WAL file for a moment; a leftover temp dir is harmless. } }); describe("token auth", () => { it("rejects missing, malformed and unknown tokens with 401", async () => { assert.equal((await call(M.v1.GET, "/api/v1")).status, 401); assert.equal((await call(M.v1.GET, "/api/v1", { token: "kn_nope" })).status, 401); const unknown = (await import("./api-token-core")).generateToken().token; const r = await call(M.v1.GET, "/api/v1", { token: unknown }); assert.equal(r.status, 401); assert.match(r.body.error.message, /Settings → API tokens/); }); it("answers with the token's name, scopes and the guardrails", async () => { const r = await call(M.v1.GET, "/api/v1", { token: readOnly }); assert.equal(r.status, 200); assert.deepEqual(r.body.token, { name: "reader", scopes: ["models:read"] }); assert.equal(r.body.guardrails.approvalMode, "approve"); assert.equal(r.body.guardrails.maxRequestSize, "60.0 GB"); }); it("enforces scopes with 403", async () => { const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M" }, readOnly); assert.equal(r.status, 403); assert.match(r.body.error.message, /lacks the scope "downloads:create"/); assert.equal((await call(M.disk.GET, "/api/v1/disk", { token: readOnly })).status, 200); }); it("records last use and stops accepting a revoked token", async () => { const t = await M.tokens.createToken("temp", ["models:read"]); assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 200); const row = (await M.tokens.listTokens()).find((x) => x.name === "temp")!; assert.ok(row.lastUsedAt); await M.tokens.revokeToken(t.id); assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 401); await M.tokens.deleteToken(t.id); }); it("never stores the token itself", async () => { const rows = await M.db.db().select().from(M.schema.apiTokens); assert.ok(rows.every((r) => r.hash !== full && r.hash.length === 64 && !r.hash.startsWith("kn_"))); }); }); describe("download requests", () => { let first: { modelId: string; jobId: string }; it("validates the body", async () => { const r = await request({ repoId: "unsloth/Test-GGUF", sha: "main", quant: "Q4_K_M" }); assert.equal(r.status, 400); assert.match(r.body.error.message, /40-character commit SHA/); assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a })).status, 400); assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q2_K" })).status, 400); }); it("creates a model and a job that waits for approval, marked with the token name", async () => { const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M", tags: ["agent"] }); assert.equal(r.status, 201); assert.equal(r.body.state, "pending_approval"); assert.equal(r.body.requestedSize, "5.0 GB"); assert.deepEqual(r.body.files, ["Test-Q4_K_M.gguf"]); assert.match(r.body.message, /Do not retry/); first = { modelId: r.body.modelId, jobId: r.body.jobId }; const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}`, { token: readOnly, params: { id: first.jobId } }); assert.equal(job.body.state, "pending_approval"); assert.equal(job.body.requestedBy, "hermes"); assert.equal(job.body.log, undefined); assert.deepEqual(job.body.files.map((f: { path: string }) => f.path), ["Test-Q4_K_M.gguf"]); const model = await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, first.modelId) }); assert.equal(model?.requestedBy, "hermes"); assert.equal(model?.status, "pending"); // not "downloading" until approved }); it("is idempotent: the same repo + commit + files returns the existing job", async () => { const r = await request({ repoId: "unsloth/test-gguf", sha: SHA.a, quant: "q4_k_m" }); assert.equal(r.status, 200); assert.equal(r.body.created, false); assert.equal(r.body.jobId, first.jobId); const n = await M.db.db().select().from(M.schema.jobs); assert.equal(n.length, 1); }); it("refuses other files while the model has an open job", async () => { const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" }); assert.equal(r.status, 409); assert.match(r.body.error.message, /still pending approval/); }); it("refuses a different commit of a model in the library", async () => { REPOS["unsloth/Test-GGUF"].sha = SHA.d; try { const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.d, quant: "Q4_K_M" }); assert.equal(r.status, 409); assert.match(r.body.error.message, /pinned to commit a{40}.*Updating a model is done by the user/); } finally { REPOS["unsloth/Test-GGUF"].sha = SHA.a; } }); it("rejects over the max agent jobs at once", async () => { const second = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, quant: "Q4_K_M" }); assert.equal(second.status, 201); const third = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" }); assert.equal(third.status, 429); assert.equal(third.body.error.code, "too_many_jobs"); assert.match(third.body.error.message, /2 pending or running, the limit is 2/); // Reject the second request again; the model it added leaves the library. assert.deepEqual(await M.agent.rejectJob(second.body.jobId), { removedModel: true }); assert.equal(await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, second.body.modelId) }), undefined); }); it("rejects requests over the max size", async () => { await M.settings.saveGuardrails({ maxOpenJobs: 10 }); const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" }); assert.equal(r.status, 201); await M.agent.rejectJob(r.body.jobId); await M.settings.saveGuardrails({ maxRequestBytes: 2.5 * GB }); const big = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" }); assert.equal(big.status, 422); assert.equal(big.body.error.message, "exceeds max size per request 2.5 GB: requested 3.0 GB. Pick a smaller quant or fewer files."); await M.settings.saveGuardrails({ maxRequestBytes: 60 * GB }); }); it("rejects when the minimum free space would not remain (counting reserved bytes)", async () => { await setFree(107 * GB); // 5 GB reserved by the pending first request const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" }); assert.equal(r.status, 507); assert.equal(r.body.error.code, "disk_space"); assert.match(r.body.error.message, /107\.0 GB free \(5\.0 GB of it reserved by other downloads\), and at least 100\.0 GB must stay free/); const disk = await call(M.disk.GET, "/api/v1/disk", { token: readOnly }); assert.equal(disk.body.reservedBytes, 5 * GB); assert.equal(disk.body.availableForRequestsBytes, 2 * GB); await setFree(500 * GB); }); it("rejects when the worker is offline (free space unknown)", async () => { const { db } = M.db; await db().update(M.schema.workerState).set({ heartbeatAt: new Date(0) }); const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" }); assert.equal(r.status, 503); assert.equal(r.body.error.code, "disk_unknown"); await setFree(500 * GB); }); it("rejects authors outside the allowlist before asking the Hub", async () => { await M.settings.saveGuardrails({ allowedAuthors: ["unsloth", "ggml-org"] }); const r = await request({ repoId: "TheBloke/Old-GGUF", sha: SHA.d, quant: "Q4_K_M" }); assert.equal(r.status, 403); assert.equal(r.body.error.code, "author_not_allowed"); assert.match(r.body.error.message, /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/); await M.settings.saveGuardrails({ allowedAuthors: [] }); }); it("approve queues the job; the model then shows as downloading", async () => { await M.agent.approveJob(first.jobId); const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}?log=5`, { token: readOnly, params: { id: first.jobId } }); assert.equal(job.body.state, "queued"); assert.ok(Array.isArray(job.body.log)); await assert.rejects(M.agent.approveJob(first.jobId), /doesn't wait for approval/); }); it("extra files of a finished model are added; rejecting restores the selection", async () => { const { db } = M.db; await db().update(M.schema.jobs).set({ state: "completed", finishedAt: new Date() }).where((await import("drizzle-orm")).eq(M.schema.jobs.id, first.jobId)); const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" }); assert.equal(r.status, 201); assert.equal(r.body.requestedSize, "9.0 GB"); const selected = async () => (await db().query.modelFiles.findMany({ where: (f, { and, eq }) => and(eq(f.modelId, first.modelId), eq(f.selected, true)) })).map((f) => f.path).sort(); assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf", "Test-Q8_0.gguf"]); assert.deepEqual(await M.agent.rejectJob(r.body.jobId), { removedModel: false }); assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf"]); }); it("auto approval queues right away", async () => { await M.settings.saveGuardrails({ approvalMode: "auto" }); const r = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, include: ["*.gguf"] }); assert.equal(r.status, 201); assert.equal(r.body.state, "queued"); await M.settings.saveGuardrails({ approvalMode: "approve" }); }); it("lists models with the library filters, including requested_by", async () => { const all = await call(M.models.GET, "/api/v1/models", { token: readOnly }); assert.equal(all.body.count, 2); const mine = await call(M.models.GET, "/api/v1/models?requested_by=hermes&quant=Q4_K_M&author=unsloth", { token: readOnly }); assert.deepEqual(mine.body.models.map((m: { repoId: string }) => m.repoId).sort(), ["unsloth/Other-GGUF", "unsloth/Test-GGUF"]); assert.equal(mine.body.models[0].requestedBy, "hermes"); const none = await call(M.models.GET, "/api/v1/models?requested_by=someone-else", { token: readOnly }); assert.equal(none.body.count, 0); }); });