Files
OmniRoute/tests/unit/authz/management-policy.test.ts
anhtahaylove fde6241d41 test: close the database before removing temp DATA_DIR (#13290) (#13292)
* test: close the database before removing temp DATA_DIR (#13290)

Tests that set their own DATA_DIR and removed it in test.after() failed on
Windows with EPERM: nothing closed the SQLite connection, so the directory
still had an open handle and the -shm/-wal sidecars kept it locked. maxRetries
could not help because every retry hit the same open handle.

Adds tests/_setup/tempDataDir.ts with cleanupTempDataDir()/createTempDataDir(),
which close the DB singleton (lazily imported, so tests that never touch the
database do not pull in the DB layer) and then remove the directory
best-effort. Applies it to the five suites confirmed failing.

The helper's own test proves the ordering matters: skipping the close makes it
fail with 'cleanup must remove the directory'.

* test: close the database before removing temp DATA_DIR (15 more suites)

Converts the suites that measurably emitted EPERM during a full run to the
shared cleanupTempDataDir helper from #13292.

Measured on the same 15 files:
  base   -> 22 fail, 40 EPERM lines
  branch ->  7 fail, 10 EPERM lines

The 7 remaining failures are pre-existing and unrelated to teardown:
rtk-learn-discover-routes and executor-map-golden already fail on a clean
base (6 and 3 failures respectively).

* test: close the database before removing temp DATA_DIR (final 9 suites)

Completes the #13290 sweep. Two teardown shapes needed the helper:

- after()/t.after() hooks that removed DATA_DIR directly
- beforeEach() hooks that wiped DATA_DIR between tests while the previous
  test's connection was still open. These failed *before* the test body ran,
  so every test in the file reported the same EPERM path.

Three of them already called core.resetDbInstance() right before rmSync and
still leaked, which is the product-side connection leak tracked in #13303.

Measured per file, EPERM lines now 0 across all nine. Remaining failures are
pre-existing on a clean base (firefly 4->1, driverFactory 1, responses-* 1
each) and unrelated to teardown.

* test: add the missing cleanupTempDataDir import to two responses suites

The previous commit swapped rmSync for cleanupTempDataDir in these two files but
did not add the import, so both suites died with
ReferenceError: cleanupTempDataDir is not defined before running any test.

responses-parse-once-4041:            0 pass / 1 fail -> 4 pass / 0 fail
responses-route-early-keepalive-wiring: 0 pass / 1 fail -> 3 pass / 0 fail

Both now report 0 EPERM.

* test: close SQLite handles in three silently-leaking suites

These three suites requested DATA_DIR cleanup but the delete failed on
Windows because a SQLite connection was still open. They pass today, so
the leak is invisible: they carry state between tests and would surface
later as an unrelated-looking assertion, as #13303 already did in the
Firefly suite (a 500 instead of a 401).

agentbridge-mitm-router-key-6403 and agent-bridge-bypass-flow removed
their own temp dir in test.after() without closing the DB first; both now
use the shared cleanupTempDataDir helper, which closes the singleton
before removing the directory.

issue-agent-route-execution is a different case: it has no teardown at
all, so the connection stayed open until process exit and the
isolateDataDir cleanup hook then hit EPERM. It now closes the DB in
test.after().

Verified with a probe on fs.rmSync: all three reported a failed delete
before, and zero across three consecutive runs after, while the same
probe still reports four leaks in the Firefly suite.

* test: remove temp DATA_DIR in five suites that never cleaned up

These five suites create their own mkdtemp DATA_DIR, open the SQLite DB and
never remove the directory, so every run leaves a storage.sqlite behind in the
OS temp dir. Each dir is private to its suite, so this leaked disk space rather
than corrupting results - but the churn is pointless.

Each now closes the DB and removes its directory through the shared
cleanupTempDataDir helper.

Verified with an exit-time probe that lists storage.sqlite* still present in
DATA_DIR: it fired for these suites before the change and is silent after,
with the same test counts (22/14/5/3/3 passing).
2026-09-17 02:31:53 -03:00

548 lines
21 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";
import { SignJWT } from "jose";
import { cleanupTempDataDir } from "../../_setup/tempDataDir.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omr-mgmt-policy-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = "test-secret";
// API-key validation falls through to a Redis-backed cache otherwise — disable
// it for the local test loop so isValidApiKey() does not stall on ETIMEDOUT.
process.env.OMNIROUTE_DISABLE_REDIS_AUTH_CACHE = "1";
const core = await import("../../../src/lib/db/core.ts");
const apiKeysDb = await import("../../../src/lib/db/apiKeys.ts");
const settingsDb = await import("../../../src/lib/db/settings.ts");
const modelSync = await import("../../../src/shared/services/modelSyncScheduler.ts");
const internalServiceAuth = await import("../../../src/lib/api/internalServiceAuth.ts");
const ORIGINAL_JWT = process.env.JWT_SECRET;
const ORIGINAL_INITIAL = process.env.INITIAL_PASSWORD;
function reset() {
core.resetDbInstance();
apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
delete process.env.JWT_SECRET;
delete process.env.INITIAL_PASSWORD;
}
test.beforeEach(() => {
reset();
});
test.after(async () => {
await cleanupTempDataDir(TEST_DATA_DIR);
if (ORIGINAL_JWT === undefined) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = ORIGINAL_JWT;
if (ORIGINAL_INITIAL === undefined) delete process.env.INITIAL_PASSWORD;
else process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL;
});
async function loadPolicy() {
const mod = await import(`../../../src/server/authz/policies/management.ts?ts=${Date.now()}`);
return mod.managementPolicy;
}
async function dashboardCookieHeader(expiresIn = "1h"): Promise<string> {
// Mirrors tests/unit/authz/pipeline.test.ts: mint a real HS256 auth_token
// JWT against process.env.JWT_SECRET so isDashboardSessionAuthenticated()
// accepts it. The header path is sufficient — the policy reads the cookie
// from `request.headers.get("cookie")` when there's no `request.cookies`
// accessor on the plain ctx() object.
assert.ok(
process.env.JWT_SECRET,
"JWT_SECRET must be set before minting dashboard cookie (otherwise TextEncoder would encode the string 'undefined' and silently mint a wrong-secret JWT)"
);
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const token = await new SignJWT({ authenticated: true })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime(expiresIn)
.sign(secret);
return `auth_token=${token}`;
}
function ctx(
headers: Headers,
method = "GET",
path = "/api/keys",
requestExtras: Record<string, unknown> = {}
) {
return {
request: {
method,
headers,
url: `http://localhost${path}`,
nextUrl: { pathname: path },
...requestExtras,
},
classification: {
routeClass: "MANAGEMENT" as const,
reason: path.startsWith("/dashboard")
? ("dashboard_prefix" as const)
: ("management_api" as const),
normalizedPath: path,
},
requestId: "req_test",
};
}
function remoteCtx(headers: Headers, method = "GET", path = "/api/keys") {
return {
request: {
method,
headers,
url: `https://dashboard.example${path}`,
nextUrl: { hostname: "dashboard.example", pathname: path },
},
classification: {
routeClass: "MANAGEMENT" as const,
reason: path.startsWith("/dashboard")
? ("dashboard_prefix" as const)
: ("management_api" as const),
normalizedPath: path,
},
requestId: "req_remote_test",
};
}
test("managementPolicy: allows when auth not required (no password set)", async () => {
await settingsDb.updateSettings({ requireLogin: true, password: null });
const policy = await loadPolicy();
// Fresh-bootstrap anonymous allow is loopback-only, and loopback is decided
// from the real peer (socket.remoteAddress / stamped peer), never from the
// `http://localhost` URL the ctx() helper carries (GHSA-7pq4-8pvv-rx7r).
const out = await policy.evaluate(
ctx(new Headers(), "GET", "/api/keys", { socket: { remoteAddress: "127.0.0.1" } })
);
assert.equal(out.allow, true);
if (out.allow) {
assert.equal(out.subject.kind, "anonymous");
assert.equal(out.subject.label, "auth-disabled");
}
});
test("managementPolicy: rejects remote fresh bootstrap without a password", async () => {
await settingsDb.updateSettings({ requireLogin: true, password: null });
const policy = await loadPolicy();
const out = await policy.evaluate(remoteCtx(new Headers()));
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 401);
assert.equal(out.code, "AUTH_001");
}
});
// ─── GHSA-7pq4-8pvv-rx7r — bootstrap first-password write is loopback-only ────
//
// `POST /api/settings/require-login` in the bootstrap window used to be an
// unconditional anonymous allow (apiAuth.isAuthRequired returned false before
// the loopback check), and the loopback check itself read the client-controlled
// Host header. A remote caller could flip requireLogin=false, then read
// JWT_SECRET through the Obsidian WebDAV file service and forge a durable admin
// session. The policy must decide from the token-stamped real peer.
const BOOTSTRAP_WRITE_PATH = "/api/settings/require-login";
const POLICY_STAMP_TOKEN = "mgmt-policy-test-peer-stamp-token";
function stampedHeaders(peerIp: string, extra: Record<string, string> = {}): Headers {
process.env.OMNIROUTE_PEER_STAMP_TOKEN = POLICY_STAMP_TOKEN;
return new Headers({
...extra,
"x-omniroute-peer-ip": `${POLICY_STAMP_TOKEN}|${peerIp}`,
"x-omniroute-via-proxy": `${POLICY_STAMP_TOKEN}|0`,
});
}
test("managementPolicy: rejects an anonymous remote POST /api/settings/require-login in the bootstrap window (GHSA-7pq4-8pvv-rx7r)", async () => {
await settingsDb.updateSettings({ requireLogin: true, password: null });
const policy = await loadPolicy();
try {
// Plain remote peer, no stamp at all → fail closed.
const unstamped = await policy.evaluate(remoteCtx(new Headers(), "POST", BOOTSTRAP_WRITE_PATH));
assert.equal(unstamped.allow, false);
if (!unstamped.allow) {
assert.equal(unstamped.status, 401);
assert.equal(unstamped.code, "AUTH_001");
}
// Host-spoof: the URL / Host header say localhost, the stamped real peer is
// a public address, and the client even forged the pipeline's locality
// verdict header. None of that is loopback.
const spoofed = await policy.evaluate(
ctx(
stampedHeaders("203.0.113.9", {
host: "localhost:20128",
"x-omniroute-peer-locality": "loopback",
}),
"POST",
BOOTSTRAP_WRITE_PATH
)
);
assert.equal(spoofed.allow, false);
if (!spoofed.allow) {
assert.equal(spoofed.status, 401);
assert.equal(spoofed.code, "AUTH_001");
}
} finally {
delete process.env.OMNIROUTE_PEER_STAMP_TOKEN;
}
});
test("managementPolicy: keeps the bootstrap first-password write open for the stamped loopback peer (GHSA-7pq4-8pvv-rx7r)", async () => {
await settingsDb.updateSettings({ requireLogin: true, password: null, setupComplete: true });
const policy = await loadPolicy();
try {
const local = await policy.evaluate(
ctx(stampedHeaders("127.0.0.1"), "POST", BOOTSTRAP_WRITE_PATH)
);
assert.equal(local.allow, true);
if (local.allow) {
assert.equal(local.subject.kind, "anonymous");
assert.equal(local.subject.label, "auth-disabled");
}
// A loopback socket that is really a reverse-proxy hop (via-proxy marker
// set by the custom server) is NOT the local operator.
process.env.OMNIROUTE_PEER_STAMP_TOKEN = POLICY_STAMP_TOKEN;
const viaProxy = await policy.evaluate(
ctx(
new Headers({
"x-omniroute-peer-ip": `${POLICY_STAMP_TOKEN}|127.0.0.1`,
"x-omniroute-via-proxy": `${POLICY_STAMP_TOKEN}|1`,
}),
"POST",
BOOTSTRAP_WRITE_PATH
)
);
assert.equal(viaProxy.allow, false);
} finally {
delete process.env.OMNIROUTE_PEER_STAMP_TOKEN;
}
});
test("managementPolicy: rejects 401 when auth required and no credentials", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
const out = await policy.evaluate(ctx(new Headers()));
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 401);
assert.equal(out.code, "AUTH_001");
}
});
test("managementPolicy: allows a valid internal service token only from loopback", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
process.env.OMNIROUTE_INTERNAL_SERVICE_TOKEN = "internal-service-token-0123456789";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
const headers = new Headers({
[internalServiceAuth.INTERNAL_SERVICE_AUTH_HEADER]: "internal-service-token-0123456789",
});
const loopback = await policy.evaluate(
ctx(headers, "GET", "/api/combos", { socket: { remoteAddress: "127.0.0.1" } })
);
assert.equal(loopback.allow, true);
const remote = await policy.evaluate(remoteCtx(headers, "GET", "/api/combos"));
assert.equal(remote.allow, false);
delete process.env.OMNIROUTE_INTERNAL_SERVICE_TOKEN;
});
test("managementPolicy: rejects client API keys for dashboard access", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const created = await apiKeysDb.createApiKey("dashboard-denied", "machine-dashboard-denied");
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ authorization: `Bearer ${created.key}` }), "GET", "/dashboard")
);
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 403);
assert.equal(out.code, "AUTH_001");
}
});
test("managementPolicy: allows API keys with manage scope", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const created = await apiKeysDb.createApiKey("mgmt-key", "machine-mgmt-allow", ["manage"]);
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ authorization: `Bearer ${created.key}` }), "POST", "/api/keys")
);
assert.equal(out.allow, true);
if (out.allow) {
assert.equal(out.subject.kind, "management_key");
assert.equal(out.subject.label, "api-key-manage-scope");
assert.equal(out.subject.id, created.id);
}
});
test("managementPolicy: rejects valid API keys that lack manage scope", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const created = await apiKeysDb.createApiKey("no-scope-key", "machine-no-scope", []);
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ authorization: `Bearer ${created.key}` }), "POST", "/api/keys")
);
assert.equal(out.allow, false);
if (!out.allow) {
// A valid bearer is present but its scope is insufficient → 403.
assert.equal(out.status, 403);
assert.equal(out.code, "AUTH_001");
}
});
test("managementPolicy: rejects invalid API keys with 403 when bearer is present", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ authorization: "Bearer not-a-real-key" }), "POST", "/api/keys")
);
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 403);
assert.equal(out.code, "AUTH_001");
}
});
// ─── LOCAL_ONLY manage-scope bypass for /api/mcp/* ───────────────────────────
//
// `/api/mcp/*` is in LOCAL_ONLY_API_PREFIXES (because it can spawn child
// processes for unauthenticated callers) AND in
// LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES (so a manage-scoped API key
// presented from non-loopback may reach it). `/api/cli-tools/runtime/*` is
// LOCAL_ONLY but NOT bypassable — the carve-out is path-scoped.
//
// `ctx()` uses `new Headers()` without an explicit `host`, so
// `isLoopbackHost(null)` returns false → the policy treats it as non-loopback,
// which is the exact case this block exercises.
test("LOCAL_ONLY manage-scope bypass: no Bearer + non-loopback → 403 (regression guard)", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
const out = await policy.evaluate(ctx(new Headers(), "GET", "/api/mcp/stream"));
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 403);
assert.equal(out.code, "LOCAL_ONLY");
}
});
test("LOCAL_ONLY manage-scope bypass: non-manage key + non-loopback → 403", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const created = await apiKeysDb.createApiKey("chat-only", "machine-chat-only", ["chat"]);
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ authorization: `Bearer ${created.key}` }), "GET", "/api/mcp/stream")
);
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 403);
assert.equal(out.code, "LOCAL_ONLY");
}
});
test("LOCAL_ONLY manage-scope bypass: manage-scope key + non-loopback → allow", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const created = await apiKeysDb.createApiKey("mcp-bypass-key", "machine-mcp-bypass", ["manage"]);
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ authorization: `Bearer ${created.key}` }), "GET", "/api/mcp/stream")
);
assert.equal(out.allow, true);
if (out.allow) {
assert.equal(out.subject.kind, "management_key");
assert.equal(out.subject.id, created.id);
assert.ok(
(out.subject.label ?? "").includes("local-only-bypass"),
`expected label to include 'local-only-bypass', got ${out.subject.label}`
);
}
});
test("LOCAL_ONLY manage-scope bypass: carve-out does not extend to /api/cli-tools/runtime/*", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const created = await apiKeysDb.createApiKey("cli-runtime-denied", "machine-cli-runtime-denied", [
"manage",
]);
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(
new Headers({ authorization: `Bearer ${created.key}` }),
"GET",
"/api/cli-tools/runtime/foo"
)
);
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 403);
assert.equal(out.code, "LOCAL_ONLY");
}
});
test("LOCAL_ONLY manage-scope bypass: loopback + no Bearer → allow (local CLI flow preserved)", async () => {
// Match the fresh-bootstrap pattern used by the "allows when auth not
// required" test above: no password configured + loopback request →
// `isAuthRequired` returns false → anonymous-allow fires once the LOCAL_ONLY
// gate is satisfied. Locality comes from the real peer (socket.remoteAddress)
// under the peer-stamp model (2026-05-31) — the spoofable `host` header alone
// is deliberately NOT enough.
await settingsDb.updateSettings({ requireLogin: true, password: null });
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ host: "localhost:20128" }), "GET", "/api/mcp/stream", {
socket: { remoteAddress: "127.0.0.1" },
})
);
assert.equal(out.allow, true);
});
// ─── LOCAL_ONLY dashboard-session bypass ─────────────────────────────────────
//
// Regression cover for commit ca284a91 ("refine LOCAL_ONLY bypass — dashboard
// cookie + admin label + error log"). The dashboard-session bypass mirrors the
// manage-scope bypass: an authenticated `auth_token` cookie reaching a
// bypassable LOCAL_ONLY path (e.g. /api/mcp/status) from a public hostname is
// allowed, but the cli-tools-runtime carve-out is NOT extended to it.
test("LOCAL_ONLY dashboard-session bypass: authenticated dashboard cookie + non-loopback → allow", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const cookie = await dashboardCookieHeader();
const policy = await loadPolicy();
const out = await policy.evaluate(ctx(new Headers({ cookie }), "GET", "/api/mcp/stream"));
assert.equal(out.allow, true);
if (out.allow) {
assert.equal(out.subject.kind, "dashboard_session");
assert.equal(out.subject.id, "dashboard");
assert.equal(out.subject.label, "dashboard-session-local-only-bypass");
}
});
test("LOCAL_ONLY dashboard-session bypass: authenticated dashboard cookie + /api/cli-tools/runtime/ → 403 LOCAL_ONLY", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const cookie = await dashboardCookieHeader();
const policy = await loadPolicy();
const out = await policy.evaluate(
ctx(new Headers({ cookie }), "GET", "/api/cli-tools/runtime/foo")
);
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.status, 403);
assert.equal(out.code, "LOCAL_ONLY");
}
});
test("managementPolicy: allows internal model sync only on the dedicated provider routes", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-mgmt-policy";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
const internalHeaders = new Headers(modelSync.buildModelSyncInternalHeaders());
const allowed = await policy.evaluate(
ctx(internalHeaders, "POST", "/api/providers/conn-123/sync-models")
);
assert.equal(allowed.allow, true);
if (allowed.allow) {
assert.equal(allowed.subject.kind, "management_key");
assert.equal(allowed.subject.id, "model-sync");
}
const denied = await policy.evaluate(ctx(internalHeaders, "POST", "/api/keys"));
assert.equal(denied.allow, false);
});
const INGEST_PATH = "/api/tools/traffic-inspector/internal/ingest";
test("managementPolicy: allows loopback inspector ingest without a dashboard session (D4)", async () => {
// Auth is required (password set), and there is NO dashboard cookie / API key.
process.env.JWT_SECRET = "test-jwt-secret-for-ingest";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
// Loopback peer (socket.remoteAddress) + ingest path → exempt from management
// auth; the route handler validates the shared-secret ingest token.
const out = await policy.evaluate(
ctx(new Headers(), "POST", INGEST_PATH, { socket: { remoteAddress: "127.0.0.1" } })
);
assert.equal(out.allow, true);
if (out.allow) {
assert.equal(out.subject.id, "inspector-ingest");
assert.equal(out.subject.label, "inspector-ingest-token");
}
});
test("managementPolicy: rejects remote inspector ingest as LOCAL_ONLY (D4)", async () => {
process.env.JWT_SECRET = "test-jwt-secret-for-ingest";
process.env.INITIAL_PASSWORD = "initial-pass";
await settingsDb.updateSettings({ requireLogin: true });
const policy = await loadPolicy();
// Non-loopback caller hits the LOCAL_ONLY gate before the ingest carve-out —
// the loopback exemption must never widen the endpoint to off-box peers.
const out = await policy.evaluate(remoteCtx(new Headers(), "POST", INGEST_PATH));
assert.equal(out.allow, false);
if (!out.allow) {
assert.equal(out.code, "LOCAL_ONLY");
}
});