Files
OmniRoute/tests/unit/proxy-management-v1-route.test.ts
Diego Rodrigues de Sa e Souza 68e4d0c599 Release v3.8.19 (#3526)
* chore(release): open v3.8.19 development cycle

* chore(release): sync electron lockfile to 3.8.19

* feat(quality): quality-gate ratchet + anti-hallucination/rule-enforcement guardrails (Phases 0-6) (#3471)

* feat(quality): generic ratchet comparator (multi-metric, regression-only)

* chore(ci): Fase 0 quality-gate fixes — reconcile coverage gate (40->60), tier npm audit, wire orphaned contract gates, re-enable cheap husky pre-commit

* feat(quality): ratchet engine (collector + frozen baseline + CI job) and provider-consistency gate

- collect-metrics.mjs: emits quality-metrics.json (ESLint warnings + coverage when present)
- quality-baseline.json: frozen baseline (eslintWarnings=3482, regression-only)
- ci.yml: quality-gate job (ratchet + step summary + artifact) and check:provider-consistency in lint job
- check-provider-consistency.ts: every REGISTRY id must be a canonical provider (found krutrim half-registered → allowlisted as known pre-existing, blocks any NEW orphan)
- TDD: 9 tests (5 ratchet + 4 provider-consistency)

* feat(quality): Fase 2 anti-hallucination gates — fetch-targets, openapi-routes, deps allowlist

- check-fetch-targets: every dashboard fetch(/api/...) resolves to a real route.ts; found 7 pre-existing dashboard->route mismatches frozen as KNOWN_MISSING for triage
- check-openapi-routes: every openapi.yaml path resolves to a real route; found 1 stale spec entry (agent-bridge agents/{id}/state) frozen as KNOWN_STALE_SPEC
- check-deps: anti-slopsquatting allowlist (105 deps); new deps need explicit human-reviewed entry
- all wired into CI lint/docs jobs; TDD +12 tests (21 total across 5 gates)

* docs(quality): add quality-gates report + implementation plan to repo root

* feat(quality): Fase 3a — file-size ratchet (freeze 91 files >800 LOC, cap 800 for new)

- check-file-size.mjs: frozen files can only shrink; new files must be <= cap (kills the next 12k-line god-component)
- file-size-baseline.json: 91 files frozen at current LOC (largest 12883)
- wired into CI lint job; TDD 5 tests; --update ratchets the baseline down on shrink

* feat(quality): Fase 3b — duplication ratchet (jscpd@4, baseline 5.72%)

- check-duplication.mjs: runs jscpd@4 (pinned; v5 is an incompatible Rust rewrite) over src+open-sse, fails if duplication % rises vs frozen baseline (5.72%, measured: 1358 clones / 22967 dup lines). Targets the executor copy-paste (48/50 override execute() wholesale)
- wired into the parallel quality-gate CI job (off the lint critical path); TDD 4 tests; --update ratchets down
- snapshot now complete: coverage ~82.6%, eslint 3482 (98.5% no-explicit-any), duplication 5.72%, 91 files >800 LOC

* feat(quality): Fase 4a — anti test-masking gate

- check-test-masking.mjs: for each MODIFIED test file in a PR, flags net assert removal + new assert.ok(true) tautologies (base...HEAD diff). Directly enforces CLAUDE.md 'never weaken asserts to go green'
- wired into pr-test-policy CI job (reuses base fetch); no-op outside PR; TDD 5 tests

* feat(quality): Fase 4b — coverage ratchet (conservative floors, CI consumes merged coverage)

- quality-baseline.json: coverage.{statements,lines,functions,branches} floors (80/80/82/73, real ~82.58/82.58/84.23/75.22 with margin; tighten via --update after a green main run)
- check-quality-ratchet.mjs: --allow-missing (local quality:gate skips coverage.* without a coverage run; CI runs strict)
- ci.yml quality-gate job: needs test-coverage + downloads merged coverage-report so the ratchet enforces 'coverage cannot drop'
- TDD +1 test (6 total)

* feat(quality): Fase 6 — 8 new gates (Rule #11/#12, migrations, known-symbols, route-guard, complexity, docs-symbols, db-rules)

Deterministic gates, each freezing pre-existing violations in a documented allowlist (ratchet) so they pass now and block only NEW regressions:
- check-error-helper (Rule #12): 7 executors/handlers forwarding raw err.message frozen
- check-public-creds (Rule #11): 5 literal client_ids (Claude/Codex/Qwen/Kimi/Copilot) frozen
- check-migration-numbering: gaps 026/055 + dup 041 frozen (prevents the git-rm-deleted-migration incident)
- check-known-symbols: 93 executors conformance + 15 combo strategies + 18 translator pairs
- check-route-guard-membership (#15/#17): all 25 spawn-capable routes verified local-only (0 gaps)
- check-complexity: cyclomatic>15 / fn-length>80 ratchet (baseline 1739)
- check-docs-symbols: 30 stale doc /api refs frozen (docs hallucination)
- check-db-rules (#2/#5): 25 unexported db modules + 15 raw-SQL routes frozen
Wired into CI (lint / docs-sync-strict / quality-gate jobs). 115 TDD tests, all green. ESLint ratchet held at 3482.

* docs(quality): Phase 7 plan (security/dead-code/mutation/community tooling) — GATED to 2026-06-16

Stored, not active. 7 suggested gates + all discussed OSS/Community tools (SonarQube Community + osv-scanner + CodeQL + knip + sonarjs + type-coverage + lockfile-lint + Stryker + size-limit + axe-core + semcheck + agent-lsp + Qlty). Activation gate: do not start before 2026-06-16 (use Phases 0-6 in production for 1 week, validate in practice, then evolve).

* docs(quality): Phase 6A critical-audit plan + Phase 7 additions — gated to 2026-06-16 (#3530)

PLANO-QUALITY-GATES-FASE6A.md (12-task audit of Phases 0-6: orphan tests, stale-allowlist enforcement, scope gaps) + Phase 7 additions (gitleaks, actionlint+zizmor, license compliance). Both stored, activation gated to 2026-06-16. Tasks 6A.1/6A.2 were fast-tracked separately (#3536).

* feat(quality): 6A.1+6A.2 — test-discovery gate, 135 orphan tests re-wired, 2 production bug fixes, vitest in CI (#3536)

check-test-discovery gate (TDD; 195 orphans found, 135 re-wired into the node runner, 60 frozen+annotated). Triage fixed 2 real production bugs: missing BYPASS_PREFIX_NOT_ALLOWED zod refine (spawn-capable prefixes accepted into the bypass list, Hard Rules #15/#17) and resetDbInstance not firing stateReset resetters (stale schema memo → 503 instead of 403; also hit backup-restore). New test-vitest CI job: test:vitest blocking (146/146), test:vitest:ui informational (14 pre-existing fails, triage 2026-06-16).

* chore: ignore generated yt-downloader artifact files

Add dated yt-downloader output files to .gitignore to prevent
local automation artifacts from being accidentally committed.

* chore(quality): green-light the quality-gate — conscious file-size + eslintWarnings re-baselines (#3538)

file-size: 9 files frozen at current sizes (v3.8.18-era growth + core.ts +7 from #3536 fix). eslintWarnings 3482→3501: the published v3.8.18 tag already measures 3501 (delta predates the quality-gate job); v3.8.19 cycle is neutral. Reduction + --require-tighten = Phase 6A (2026-06-16).

* fix(check): exclude internal planning docs (docs/superpowers/) from the docs-symbols gate

docs/superpowers/plans/*.md are historical implementation-plan snapshots that
may cite planned/abandoned routes — not claims about the current code. Three
such refs entered during the v3.8.18 cycle, before this gate was on the
pipeline, and would have blocked the v3.8.19 release merge.

* chore(release): v3.8.19 — 2026-06-09

CHANGELOG section for the quality-infrastructure release (7 commits, 1:1
coverage), [3.8.18] label corrected to its real release date, local prompt
artifacts ignored.

* test: hermetic auth context for 2 re-wired suites + real headroom on the breaker reset-timeout flake

CI shards exposed what the dev DATA_DIR was masking locally: detect.test.ts
and managementCliToken.test.ts asserted 401/403/reject outcomes that only
exist when login protection is configured — on a fresh CI DB isAuthRequired()
is false and the policy anonymous-allows. Both now create an isolated
DATA_DIR with requireLogin+password (the established pattern).

observability-fase04: the breaker reset-timeout test ran with a 5ms margin
(resetTimeout 10 / sleep 15) — lazy HALF_OPEN refresh under shard contention
flipped the first OPEN assert. Now 250/300ms.

* test: align bypass-prefix schema test to the restored layer-1 contract + real waitFor headroom

appearance-widget-settings-schema asserted that /api/cli-tools/runtime/ was
ACCEPTED into the bypass list — written against the buggy schema (missing
BYPASS_PREFIX_NOT_ALLOWED refine, restored in #3536) and consecrating the
bug the AC-8 orphan test guards against. Split into accept-safe +
reject-spawn-capable cases. chatcore waitFor ceiling 1500→10000ms (green
runs return immediately; observed 1580ms expiry on 2-core CI runners).

* test(chatcore): fix structurally-broken pending-detail predicate (flatten before find)

pendingRequests.details[connectionId] is Record<modelKey, PendingRequestDetail[]>
— the upstream-timeout test's waitFor tested each ARRAY's .providerRequest
(always undefined), so it could never resolve and expired (failed on 3 CI jobs;
reproduced deterministically isolated, including at the published v3.8.18 tag).
Flatten to the actual details + declare the call_log_pipeline_enabled dependency
explicitly + waitFor ceiling with real CI headroom.

* chore(quality): re-baseline coverage floors to the honest post-re-wire denominator + changelog coverage for the stabilization commits

The 135 re-wired tests import modules that were never loaded before, so the
c8 denominator grew: the old ~82.5% was inflated by never-imported modules
being invisible. CI merged coverage now measures 78.4/78.4/83.84/75.73 —
floors set ~2pt below (76.5/76.5; functions/branches floors already hold).
Tightening via --require-tighten is Phase 6A work (2026-06-16).
2026-06-09 22:57:12 -03:00

796 lines
25 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-proxy-v1-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const providersDb = await import("../../src/lib/db/providers.ts");
const proxyV1Route = await import("../../src/app/api/v1/management/proxies/route.ts");
const proxyAssignmentsV1Route =
await import("../../src/app/api/v1/management/proxies/assignments/route.ts");
const proxyHealthV1Route = await import("../../src/app/api/v1/management/proxies/health/route.ts");
const proxyBulkAssignV1Route =
await import("../../src/app/api/v1/management/proxies/bulk-assign/route.ts");
const proxyLogger = await import("../../src/lib/proxyLogger.ts");
async function withEnv(name, value, fn) {
const previous = process.env[name];
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
try {
return await fn();
} finally {
if (previous === undefined) {
delete process.env[name];
} else {
process.env[name] = previous;
}
}
}
async function resetStorage() {
delete process.env.INITIAL_PASSWORD;
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
async function withPrepareFailure(match, message, fn) {
const db = core.getDbInstance();
const originalPrepare = db.prepare.bind(db);
db.prepare = (sql, ...args) => {
const sqlText = String(sql);
const matched = typeof match === "function" ? match(sqlText) : sqlText.includes(match);
if (matched) {
throw new Error(message);
}
return originalPrepare(sql, ...args);
};
try {
return await fn();
} finally {
db.prepare = originalPrepare;
}
}
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("v1 management proxies supports create/list/pagination", async () => {
await resetStorage();
const createA = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Proxy A",
type: "http",
host: "proxy-a.local",
port: 8080,
}),
})
);
assert.equal(createA.status, 201);
const createB = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Proxy B",
type: "https",
host: "proxy-b.local",
port: 443,
}),
})
);
assert.equal(createB.status, 201);
const listRes = await proxyV1Route.GET(
new Request("http://localhost/api/v1/management/proxies?limit=1&offset=0")
);
assert.equal(listRes.status, 200);
const listPayload = (await listRes.json()) as any;
assert.equal(Array.isArray(listPayload.items), true);
assert.equal(listPayload.items.length, 1);
assert.equal(listPayload.page.total >= 2, true);
});
test("v1 management proxies main route covers auth, lookup variants, update and delete branches", async () => {
await resetStorage();
await withEnv("INITIAL_PASSWORD", "secret", async () => {
const getAuthRes = await proxyV1Route.GET(
new Request("http://localhost/api/v1/management/proxies")
);
assert.equal(getAuthRes.status, 401);
const postAuthRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer invalid-management-token",
},
body: JSON.stringify({
name: "Denied Proxy",
type: "http",
host: "denied.local",
port: 8080,
}),
})
);
assert.equal(postAuthRes.status, 403);
const patchAuthRes = await proxyV1Route.PATCH(
new Request("http://localhost/api/v1/management/proxies", {
method: "PATCH",
headers: { Authorization: "Bearer invalid-management-token" },
body: JSON.stringify({ id: "proxy-1", notes: "denied" }),
})
);
assert.equal(patchAuthRes.status, 403);
const deleteAuthRes = await proxyV1Route.DELETE(
new Request("http://localhost/api/v1/management/proxies?id=proxy-1", {
method: "DELETE",
})
);
assert.equal(deleteAuthRes.status, 401);
});
const providerConn = await providersDb.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "v1-main-route",
apiKey: "sk-test-main-route",
});
const createdRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Primary Proxy",
type: "http",
host: "primary.local",
port: 8080,
}),
})
);
assert.equal(createdRes.status, 201);
const created = (await createdRes.json()) as any;
const defaultListRes = await proxyV1Route.GET(
new Request("http://localhost/api/v1/management/proxies")
);
assert.equal(defaultListRes.status, 200);
const defaultListBody = (await defaultListRes.json()) as any;
assert.equal(defaultListBody.page.limit, 50);
assert.equal(defaultListBody.page.offset, 0);
assert.equal(defaultListBody.items.length, 1);
const byIdRes = await proxyV1Route.GET(
new Request(`http://localhost/api/v1/management/proxies?id=${created.id}`)
);
assert.equal(byIdRes.status, 200);
const byIdBody = (await byIdRes.json()) as any;
assert.equal(byIdBody.id, created.id);
const assignRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "account",
scopeId: providerConn.id,
proxyId: created.id,
}),
})
);
assert.equal(assignRes.status, 200);
const whereUsedRes = await proxyV1Route.GET(
new Request(`http://localhost/api/v1/management/proxies?id=${created.id}&where_used=1`)
);
assert.equal(whereUsedRes.status, 200);
const whereUsedBody = (await whereUsedRes.json()) as any;
assert.equal(whereUsedBody.count, 1);
assert.equal(whereUsedBody.assignments[0].scopeId, providerConn.id);
const missingGetRes = await proxyV1Route.GET(
new Request("http://localhost/api/v1/management/proxies?id=missing-proxy")
);
assert.equal(missingGetRes.status, 404);
const updatedRes = await proxyV1Route.PATCH(
new Request("http://localhost/api/v1/management/proxies", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: created.id,
host: "updated.local",
port: 9090,
notes: "updated via patch",
}),
})
);
assert.equal(updatedRes.status, 200);
const updatedBody = (await updatedRes.json()) as any;
assert.equal(updatedBody.host, "updated.local");
assert.equal(updatedBody.port, 9090);
const missingPatchRes = await proxyV1Route.PATCH(
new Request("http://localhost/api/v1/management/proxies", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: "missing-proxy",
notes: "not found",
}),
})
);
assert.equal(missingPatchRes.status, 404);
const missingIdDeleteRes = await proxyV1Route.DELETE(
new Request("http://localhost/api/v1/management/proxies", {
method: "DELETE",
})
);
assert.equal(missingIdDeleteRes.status, 400);
const missingDeleteRes = await proxyV1Route.DELETE(
new Request("http://localhost/api/v1/management/proxies?id=missing-proxy", {
method: "DELETE",
})
);
assert.equal(missingDeleteRes.status, 404);
const inUseDeleteRes = await proxyV1Route.DELETE(
new Request(`http://localhost/api/v1/management/proxies?id=${created.id}`, {
method: "DELETE",
})
);
assert.equal(inUseDeleteRes.status, 409);
const inUseDeleteBody = (await inUseDeleteRes.json()) as any;
assert.match(inUseDeleteBody.error.message, /remove assignments first/i);
const forceDeleteRes = await proxyV1Route.DELETE(
new Request(`http://localhost/api/v1/management/proxies?id=${created.id}&force=1`, {
method: "DELETE",
})
);
assert.equal(forceDeleteRes.status, 200);
assert.deepEqual(await forceDeleteRes.json(), { success: true });
});
test("v1 management proxies main route validates malformed and invalid payloads", async () => {
await resetStorage();
const invalidPostJsonRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{",
})
);
assert.equal(invalidPostJsonRes.status, 400);
const invalidPostBodyRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Missing Host",
type: "http",
port: 8080,
}),
})
);
assert.equal(invalidPostBodyRes.status, 400);
const invalidPatchJsonRes = await proxyV1Route.PATCH(
new Request("http://localhost/api/v1/management/proxies", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: "{",
})
);
assert.equal(invalidPatchJsonRes.status, 400);
const invalidPatchBodyRes = await proxyV1Route.PATCH(
new Request("http://localhost/api/v1/management/proxies", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: "",
port: 70000,
}),
})
);
assert.equal(invalidPatchBodyRes.status, 400);
});
test("v1 management proxies main route returns server errors when persistence fails", async () => {
await resetStorage();
await withPrepareFailure(
"ORDER BY datetime(updated_at) DESC, name ASC",
"list proxy failure",
async () => {
const response = await proxyV1Route.GET(
new Request("http://localhost/api/v1/management/proxies")
);
assert.equal(response.status, 500);
assert.match((await response.json()).error.message, /list proxy failure/i);
}
);
await withPrepareFailure("INSERT INTO proxy_registry", "create proxy failure", async () => {
const response = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Broken Create",
type: "http",
host: "broken-create.local",
port: 8080,
}),
})
);
assert.equal(response.status, 500);
assert.match((await response.json()).error.message, /create proxy failure/i);
});
const createdRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Broken Update",
type: "http",
host: "broken-update.local",
port: 8081,
}),
})
);
assert.equal(createdRes.status, 201);
const created = (await createdRes.json()) as any;
await withPrepareFailure("UPDATE proxy_registry", "update proxy failure", async () => {
const response = await proxyV1Route.PATCH(
new Request("http://localhost/api/v1/management/proxies", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: created.id,
notes: "should fail",
}),
})
);
assert.equal(response.status, 500);
assert.match((await response.json()).error.message, /update proxy failure/i);
});
await withPrepareFailure("DELETE FROM proxy_registry", "delete proxy failure", async () => {
const response = await proxyV1Route.DELETE(
new Request(`http://localhost/api/v1/management/proxies?id=${created.id}`, {
method: "DELETE",
})
);
assert.equal(response.status, 500);
assert.match((await response.json()).error.message, /delete proxy failure/i);
});
});
test("v1 management assignments supports put and filtered get", async () => {
await resetStorage();
const providerConn = await providersDb.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "v1-assignment",
apiKey: "sk-test-v1",
});
const createdRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Proxy Assign",
type: "http",
host: "assign.local",
port: 8000,
}),
})
);
const created = (await createdRes.json()) as any;
const assignRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "account",
scopeId: providerConn.id,
proxyId: created.id,
}),
})
);
assert.equal(assignRes.status, 200);
const filteredRes = await proxyAssignmentsV1Route.GET(
new Request(
`http://localhost/api/v1/management/proxies/assignments?scope=account&scope_id=${providerConn.id}`
)
);
assert.equal(filteredRes.status, 200);
const payload = (await filteredRes.json()) as any;
assert.equal(payload.items.length, 1);
assert.equal(payload.items[0].proxyId, created.id);
});
test("v1 management assignments covers unfiltered listing and error branches", async () => {
await resetStorage();
const listRes = await proxyAssignmentsV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/assignments?limit=5&offset=0")
);
assert.equal(listRes.status, 200);
const listPayload = (await listRes.json()) as any;
assert.deepEqual(listPayload.items, []);
assert.equal(listPayload.page.limit, 5);
assert.equal(listPayload.page.offset, 0);
assert.equal(listPayload.page.total, 0);
await withPrepareFailure(
"FROM proxy_assignments ORDER BY scope, scope_id",
"assignment list failure",
async () => {
const response = await proxyAssignmentsV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/assignments")
);
assert.equal(response.status, 500);
assert.match((await response.json()).error.message, /assignment list failure/i);
}
);
const invalidJsonRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: "{",
})
);
assert.equal(invalidJsonRes.status, 400);
assert.match((await invalidJsonRes.json()).error.message, /invalid json body/i);
const invalidPayloadRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "account",
}),
})
);
assert.equal(invalidPayloadRes.status, 400);
const invalidPayloadBody = (await invalidPayloadRes.json()) as any;
assert.equal(invalidPayloadBody.error.type, "invalid_request");
assert.equal(Array.isArray(invalidPayloadBody.error.details), true);
const clearGlobalRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "global",
proxyId: null,
}),
})
);
assert.equal(clearGlobalRes.status, 200);
assert.deepEqual(await clearGlobalRes.json(), { success: true, assignment: null });
const missingProxyRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "global",
proxyId: "missing-proxy",
}),
})
);
assert.equal(missingProxyRes.status, 404);
assert.match((await missingProxyRes.json()).error.message, /proxy not found/i);
});
test("v1 management health endpoint aggregates proxy log metrics", async () => {
await resetStorage();
const createdRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Proxy Health",
type: "http",
host: "health.local",
port: 8080,
}),
})
);
const created = (await createdRes.json()) as any;
proxyLogger.logProxyEvent({
status: "success",
proxy: { type: "http", host: "health.local", port: 8080 },
latencyMs: 120,
level: "provider",
levelId: "openai",
provider: "openai",
});
proxyLogger.logProxyEvent({
status: "error",
proxy: { type: "http", host: "health.local", port: 8080 },
latencyMs: 200,
level: "provider",
levelId: "openai",
provider: "openai",
});
const healthRes = await proxyHealthV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/health?hours=24")
);
assert.equal(healthRes.status, 200);
const healthPayload = (await healthRes.json()) as any;
const row = healthPayload.items.find((item) => item.proxyId === created.id);
assert.ok(row);
assert.equal(row.totalRequests >= 2, true);
assert.equal(row.errorCount >= 1, true);
});
test("v1 management health endpoint covers default window and error handling", async () => {
await resetStorage();
const createdRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Proxy Health Default",
type: "http",
host: "health-default.local",
port: 8080,
}),
})
);
assert.equal(createdRes.status, 201);
const defaultRes = await proxyHealthV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/health")
);
assert.equal(defaultRes.status, 200);
const defaultBody = (await defaultRes.json()) as any;
assert.equal(defaultBody.windowHours, 24);
assert.equal(defaultBody.total, 1);
await withPrepareFailure("FROM proxy_registry p", "proxy health failure", async () => {
const errorRes = await proxyHealthV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/health")
);
assert.equal(errorRes.status, 500);
assert.match((await errorRes.json()).error.message, /proxy health failure/i);
});
});
test("v1 bulk assignment updates multiple scope IDs in one request", async () => {
await resetStorage();
const proxyRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Bulk Proxy",
type: "http",
host: "bulk.local",
port: 8080,
}),
})
);
const proxy = (await proxyRes.json()) as any;
const bulkRes = await proxyBulkAssignV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/bulk-assign", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "provider",
scopeIds: ["openai", "anthropic"],
proxyId: proxy.id,
}),
})
);
assert.equal(bulkRes.status, 200);
const bulkPayload = (await bulkRes.json()) as any;
assert.equal(bulkPayload.updated, 2);
const checkRes = await proxyAssignmentsV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/assignments?scope=provider")
);
const checkPayload = (await checkRes.json()) as any;
assert.equal(checkPayload.items.length >= 2, true);
});
test("v1 proxy management companion routes require auth when login protection is enabled", async () => {
await resetStorage();
await withEnv("INITIAL_PASSWORD", "secret", async () => {
const assignmentsGetRes = await proxyAssignmentsV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/assignments")
);
assert.equal(assignmentsGetRes.status, 401);
const assignmentsPutRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer invalid-management-token",
},
body: JSON.stringify({
scope: "global",
proxyId: null,
}),
})
);
// Invalid bearer → deterministic 403 "Invalid management token". The old
// [401, 503] accommodation existed because a stale schema memo in apiKeys.ts
// made isValidApiKey throw ("no such column") → 503; that bug is fixed
// (closeDbInstance now fires resetAllDbModuleState — 6A.1b, 2026-06-09).
assert.equal(assignmentsPutRes.status, 403);
const healthRes = await proxyHealthV1Route.GET(
new Request("http://localhost/api/v1/management/proxies/health", {
headers: {
Authorization: "Bearer invalid-management-token",
},
})
);
// Same contract as above: invalid bearer → 403 (no longer 503 via the
// stale-schema throw).
assert.equal(healthRes.status, 403);
const bulkRes = await proxyBulkAssignV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/bulk-assign", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "global",
proxyId: null,
}),
})
);
assert.equal(bulkRes.status, 401);
});
});
test("v1 assignments route resolves connection proxies and bulk assignment covers validation branches", async () => {
await resetStorage();
const providerConn = await providersDb.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "v1-resolve",
apiKey: "sk-test-v1-resolve",
});
const proxyRes = await proxyV1Route.POST(
new Request("http://localhost/api/v1/management/proxies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Resolve Proxy",
type: "http",
host: "resolve.local",
port: 9000,
}),
})
);
const proxy = (await proxyRes.json()) as any;
const assignRes = await proxyAssignmentsV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/assignments", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "account",
scopeId: providerConn.id,
proxyId: proxy.id,
}),
})
);
assert.equal(assignRes.status, 200);
const resolveRes = await proxyAssignmentsV1Route.GET(
new Request(
`http://localhost/api/v1/management/proxies/assignments?resolve_connection_id=${providerConn.id}`
)
);
assert.equal(resolveRes.status, 200);
const resolvePayload = (await resolveRes.json()) as any;
assert.equal(resolvePayload.level, "account");
assert.equal(resolvePayload.proxy.host, "resolve.local");
const invalidJsonRes = await proxyBulkAssignV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/bulk-assign", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: "{",
})
);
assert.equal(invalidJsonRes.status, 400);
const invalidPayloadRes = await proxyBulkAssignV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/bulk-assign", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "provider",
scopeIds: [],
}),
})
);
assert.equal(invalidPayloadRes.status, 400);
const normalizedRes = await proxyBulkAssignV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/bulk-assign", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "key",
scopeIds: [providerConn.id, providerConn.id],
proxyId: proxy.id,
}),
})
);
assert.equal(normalizedRes.status, 200);
const normalizedPayload = (await normalizedRes.json()) as any;
assert.equal(normalizedPayload.scope, "account");
assert.equal(normalizedPayload.requested, 2);
assert.equal(normalizedPayload.updated, 1);
const globalRes = await proxyBulkAssignV1Route.PUT(
new Request("http://localhost/api/v1/management/proxies/bulk-assign", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
scope: "global",
proxyId: proxy.id,
}),
})
);
assert.equal(globalRes.status, 200);
const globalPayload = (await globalRes.json()) as any;
assert.equal(globalPayload.scope, "global");
assert.equal(globalPayload.requested, 1);
assert.equal(globalPayload.updated, 1);
});