mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-08 08:12:20 +03:00
feat(discovery): Phase 2 — reporter, /api/discovery/* routes (strict loopback-only) + dashboard UI (#5939)
* feat(discovery): Phase 2 reporter — discoveryResults DB module + service wiring
Adds src/lib/db/discoveryResults.ts (CRUD over the discovery_results table
from migration 074) and wires the opt-in discovery service to persist and read
findings through it: persistDiscoveryResult / getDiscoveryResults /
getDiscoveryResultById / markVerified / deleteDiscoveryResult, with
(provider, method, endpoint) upsert de-duplication. Re-exported from localDb.
The service stays opt-in / default-off. The /api/discovery/* routes and the
dashboard UI tab are intentionally deferred to Phase 2b — they need the
local-only enforcement model (Hard Rules #15/#17 territory) decided first.
TDD: tests/unit/db/discovery-results.test.ts (8 cases, DB + service delegation),
isolated DATA_DIR with resetDbInstance cleanup.
* feat(discovery): Phase 2b — /api/discovery/* routes (strict loopback-only)
Adds the discovery HTTP surface on top of the reporter DB module:
GET /api/discovery/results list findings (optional ?providerId)
GET /api/discovery/results/:id one finding (404 if absent)
DELETE /api/discovery/results/:id delete a finding
POST /api/discovery/scan scan a provider + persist findings
POST /api/discovery/verify/:id mark a finding verified
Authorization: strict loopback-only. "/api/discovery/" is added to
LOCAL_ONLY_API_PREFIXES so the central authz pipeline (proxy.ts →
runAuthzPipeline → managementPolicy) rejects non-loopback callers with a 403
LOCAL_ONLY before any handler runs. It is deliberately NOT in
LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES — no remote manage-scope bypass —
because POST /scan issues outbound probes to provider endpoints (SSRF-adjacent)
and must never be tunnel-reachable. Handlers also call requireManagementAuth
(defense in depth) and return sanitized errors via createErrorResponse.
Tests:
- tests/unit/authz/discovery-routes-local-only.test.ts (8) — security guard:
isLocalOnlyPath true + not manage-scope-bypassable for all four paths.
- tests/unit/api/discovery-routes.test.ts (6) — handler integration over an
isolated DATA_DIR: list/filter, by-id 200/404/400, scan persist + 400 on
empty/malformed body, verify 200/404, delete 200/404, no stack-trace leak.
* feat(discovery): Phase 2c — dashboard UI tab (Tools → Discovery)
Adds the /dashboard/discovery page (DiscoveryPageClient) that consumes the
Phase 2b /api/discovery/* routes: scan a provider, list findings, verify or
delete them. Registered in the sidebar under the Tools group (icon
travel_explore) and given a "discovery" i18n namespace + sidebar keys in
en.json (other locales fall back to en via next-intl until synced — the
locale files are in a pre-existing coverage deficit unrelated to this change).
Registers the UI test path in vitest.config.ts (advisory ui suite).
Tests: src/app/(dashboard)/dashboard/discovery/__tests__/DiscoveryPageClient.test.tsx
(3 cases: loads+renders results, empty state, fetches /api/discovery/results on
mount; stable useTranslations mock to avoid the fetch-loop). NOTE: the ui vitest
suite cannot run in this workspace — @testing-library/dom (a @testing-library/
react peer dep) is absent from node_modules, which fails ALL existing ui tests
equally; the test runs in CI. Component verified locally via typecheck + lint.
* test(discovery): register discovery-routes-local-only in stryker tap.testFiles
The mutation-test-coverage gate (--strict) flags any unit test covering a
mutated module that isn't listed in stryker.conf.json tap.testFiles. This PR's
tests/unit/authz/discovery-routes-local-only.test.ts covers src/server/authz/
routeGuard.ts (a mutated module, which this PR edits by adding the
/api/discovery/ local-only prefix), so it must be registered for its mutant
kills to count. No behavior change.
* refactor(discovery): split DiscoveryPageClient to satisfy max-lines-per-function
The complexity ratchet (max-lines-per-function: 80) flagged the single
184-line DiscoveryPageClient function (+1 over baseline). Extract the data
layer into two hooks (useDiscoveryResults for list/loading/feedback,
useDiscoveryActions for scan/verify/delete), a shared callApi helper, and two
presentational sub-components (DiscoveryScanForm, DiscoveryResultCard). Every
function is now under the 80-line ceiling; complexity gate back to baseline
1995. No behavior change — same exported component, same endpoints, same props.
* test(sidebar): include discovery in omni-proxy item-order snapshot
Adding the Discovery item to the Tools group (this PR's sidebar entry) extends
the ordered omni-proxy section list. Update the exact-match deepEqual snapshot
in sidebar-visibility.test.ts to include "discovery" in its position (after
traffic-inspector). The assertion stays exact — this reflects the intentional
new item, it does not weaken the check.
* docs(changelog): restore release bullets eaten by merge auto-resolve; re-add discovery bullet additively
* chore(quality): bump testFrozen for translator-openai-responses-req.test.ts (1097 -> 1172)
Base-red inherited from #5933, which grew the test file to 1171 lines
(Hard Rule #18 regression tests) without adjusting the frozen cap. The
release tip itself fails check:file-size; this unblocks every PR into
release/v3.8.44. File untouched by this PR.
* chore(quality): restore stryker tap.testFiles entries eaten by merge auto-resolve
The merge of origin/release/v3.8.44 silently dropped the 3 entries added
on the release side (#5903, clinepass, #5923). Took the release version
verbatim and re-added only this PR's entry (discovery-routes-local-only)
in alphabetical order. check:mutation-test-coverage green locally.
* chore(quality): reconcile inherited v3.8.44 merge-burst drift + include discovery in tools-group order test
- complexity 1995->2003 and cognitive 856->859: both measure IDENTICAL on
the pristine release tip (3a3d618fe) and this PR's merged HEAD — the PR
is complexity-net-zero; drift is from the 2026-07-02 merge burst
(notes added to both baselines, same family as prior reconciliations).
- sidebar-tools-group.test.ts: append 'discovery' to the expected
TOOLS_GROUP order — the intentional new sidebar item this PR adds
(same expected-value update already made in sidebar-visibility.test.ts).
This commit is contained in:
committed by
GitHub
parent
9e5d2d1480
commit
0965c54245
155
tests/unit/api/discovery-routes.test.ts
Normal file
155
tests/unit/api/discovery-routes.test.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { describe, test, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
// Isolated DB + auth disabled so requireManagementAuth passes (no key configured).
|
||||
let tmpDataDir: string;
|
||||
let core: typeof import("@/lib/db/core");
|
||||
let db: typeof import("@/lib/db/discoveryResults");
|
||||
let resultsRoute: typeof import("@/app/api/discovery/results/route");
|
||||
let resultByIdRoute: typeof import("@/app/api/discovery/results/[id]/route");
|
||||
let scanRoute: typeof import("@/app/api/discovery/scan/route");
|
||||
let verifyRoute: typeof import("@/app/api/discovery/verify/[id]/route");
|
||||
|
||||
function req(method: string, url: string, body?: unknown): Request {
|
||||
return new Request(`http://localhost${url}`, {
|
||||
method,
|
||||
headers: { "content-type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
tmpDataDir = mkdtempSync(join(tmpdir(), "omniroute-discovery-routes-"));
|
||||
process.env.DATA_DIR = tmpDataDir;
|
||||
delete process.env.REQUIRE_API_KEY;
|
||||
process.env.OMNIROUTE_DISABLE_AUTH = "1";
|
||||
core = await import("@/lib/db/core");
|
||||
core.resetDbInstance();
|
||||
core.getDbInstance();
|
||||
db = await import("@/lib/db/discoveryResults");
|
||||
resultsRoute = await import("@/app/api/discovery/results/route");
|
||||
resultByIdRoute = await import("@/app/api/discovery/results/[id]/route");
|
||||
scanRoute = await import("@/app/api/discovery/scan/route");
|
||||
verifyRoute = await import("@/app/api/discovery/verify/[id]/route");
|
||||
});
|
||||
|
||||
after(() => {
|
||||
core.resetDbInstance();
|
||||
if (tmpDataDir) rmSync(tmpDataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("discovery API routes", () => {
|
||||
test("GET /results lists persisted findings (and filters by providerId)", async () => {
|
||||
db.upsertDiscoveryResult({
|
||||
providerId: "acme",
|
||||
method: "free_tier",
|
||||
authType: "none",
|
||||
feasibility: 3,
|
||||
riskLevel: "none",
|
||||
status: "pending",
|
||||
});
|
||||
const res = await resultsRoute.GET(req("GET", "/api/discovery/results?providerId=acme"));
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json();
|
||||
assert.ok(Array.isArray(body.results));
|
||||
assert.ok(body.results.some((r: { providerId: string }) => r.providerId === "acme"));
|
||||
});
|
||||
|
||||
test("GET /results/:id returns the row, 404 when missing, 400 on bad id", async () => {
|
||||
const created = db.upsertDiscoveryResult({
|
||||
providerId: "beta",
|
||||
method: "trial",
|
||||
authType: "api_key",
|
||||
feasibility: 2,
|
||||
riskLevel: "low",
|
||||
status: "pending",
|
||||
});
|
||||
const ok = await resultByIdRoute.GET(req("GET", `/api/discovery/results/${created.id}`), {
|
||||
params: Promise.resolve({ id: String(created.id) }),
|
||||
});
|
||||
assert.equal(ok.status, 200);
|
||||
|
||||
const missing = await resultByIdRoute.GET(req("GET", "/api/discovery/results/999999"), {
|
||||
params: Promise.resolve({ id: "999999" }),
|
||||
});
|
||||
assert.equal(missing.status, 404);
|
||||
|
||||
const bad = await resultByIdRoute.GET(req("GET", "/api/discovery/results/abc"), {
|
||||
params: Promise.resolve({ id: "abc" }),
|
||||
});
|
||||
assert.equal(bad.status, 400);
|
||||
});
|
||||
|
||||
test("POST /scan persists findings; rejects an empty providerId with 400", async () => {
|
||||
const res = await scanRoute.POST(req("POST", "/api/discovery/scan", { providerId: "gamma" }));
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json();
|
||||
assert.ok(Array.isArray(body.results) && body.results.length > 0);
|
||||
assert.ok(body.results[0].id > 0);
|
||||
// the persisted row is now queryable
|
||||
assert.ok(db.getDiscoveryResults("gamma").length > 0);
|
||||
|
||||
const invalid = await scanRoute.POST(req("POST", "/api/discovery/scan", { providerId: "" }));
|
||||
assert.equal(invalid.status, 400);
|
||||
|
||||
const malformed = new Request("http://localhost/api/discovery/scan", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: "{not json",
|
||||
});
|
||||
const malformedRes = await scanRoute.POST(malformed);
|
||||
assert.equal(malformedRes.status, 400);
|
||||
});
|
||||
|
||||
test("POST /verify/:id marks verified, 404 when missing", async () => {
|
||||
const created = db.upsertDiscoveryResult({
|
||||
providerId: "delta",
|
||||
method: "public_api",
|
||||
authType: "api_key",
|
||||
feasibility: 5,
|
||||
riskLevel: "none",
|
||||
status: "pending",
|
||||
});
|
||||
const res = await verifyRoute.POST(req("POST", `/api/discovery/verify/${created.id}`), {
|
||||
params: Promise.resolve({ id: String(created.id) }),
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json();
|
||||
assert.equal(body.result.status, "verified");
|
||||
|
||||
const missing = await verifyRoute.POST(req("POST", "/api/discovery/verify/999999"), {
|
||||
params: Promise.resolve({ id: "999999" }),
|
||||
});
|
||||
assert.equal(missing.status, 404);
|
||||
});
|
||||
|
||||
test("DELETE /results/:id removes the row, 404 on second delete", async () => {
|
||||
const created = db.upsertDiscoveryResult({
|
||||
providerId: "epsilon",
|
||||
method: "free_tier",
|
||||
authType: "none",
|
||||
feasibility: 1,
|
||||
riskLevel: "none",
|
||||
status: "pending",
|
||||
});
|
||||
const first = await resultByIdRoute.DELETE(req("DELETE", `/api/discovery/results/${created.id}`), {
|
||||
params: Promise.resolve({ id: String(created.id) }),
|
||||
});
|
||||
assert.equal(first.status, 200);
|
||||
const second = await resultByIdRoute.DELETE(req("DELETE", `/api/discovery/results/${created.id}`), {
|
||||
params: Promise.resolve({ id: String(created.id) }),
|
||||
});
|
||||
assert.equal(second.status, 404);
|
||||
});
|
||||
|
||||
test("error responses do not leak stack traces", async () => {
|
||||
const missing = await resultByIdRoute.GET(req("GET", "/api/discovery/results/424242"), {
|
||||
params: Promise.resolve({ id: "424242" }),
|
||||
});
|
||||
const body = await missing.json();
|
||||
assert.ok(!String(body.error?.message ?? "").includes("at /"));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user