import { createHash } from "node:crypto"; import { readFile, writeFile, mkdir } from "node:fs/promises"; import { resolve } from "node:path"; import { root, compose, run, requireThat, safeFailure, } from "../scripts/runtime"; import { verifyBackendHandover } from "../scripts/preflight-build"; import { writeTopology } from "../scripts/topology"; import { openObserveRequest } from "../scripts/openobserve"; async function main() { requireThat( root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115", "OPENOBSERVE_GATEWAY_REMOTE_BOUNDARY_REQUIRED", ); const receipt = resolve( root, "evidence/openobserve", "query-guard-" + crypto.randomUUID() + ".json", ); await mkdir(resolve(receipt, ".."), { recursive: true }); await writeFile( receipt, JSON.stringify({ state: "RUNNING", stage: "SOURCE_LEASE" }), { flag: "wx", mode: 0o600 }, ); let stage = "SOURCE_LEASE", started = false, primary: unknown; try { const lease = await verifyBackendHandover(); requireThat( lease.sha256 === "09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609", "OPENOBSERVE_GATEWAY_SOURCE_MISMATCH", ); stage = "OWN_STAND_IDLE"; requireThat( ( await run([ "docker", "ps", "--filter", "label=com.docker.compose.project=mtuci-vp7-security", "--format", "{{.ID}}", ]) ).out.trim() === "", "OPENOBSERVE_EXISTING_OWN_STAND_RUNNING", ); stage = "GENERATE_CURRENT_GATEWAY"; await writeTopology(); const configPath = resolve(root, "config/openobserve-gateway.cfg"), configSha = createHash("sha256") .update(await readFile(configPath)) .digest("hex"); stage = "NATIVE_HAPROXY_PARSE"; await compose([ "run", "--rm", "--no-deps", "openobserve-gateway", "haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg", ]); stage = "GRAFANA_GATEWAY_NATIVE_PARSE"; await compose([ "run", "--rm", "--no-deps", "grafana-gateway", "haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg", ]); stage = "NATIVE_STORAGE_START"; started = true; await compose([ "up", "-d", "--no-build", "openobserve-gateway", "openobserve", ]); const password = await readFile( resolve(root, ".local-preflight-key"), "utf8", ); requireThat( /^[a-f0-9]{64}$/.test(password), "INVALID_PREFLIGHT_SESSION_KEY", ); stage = "QUERY_READY"; let ready = false; const deadline = Date.now() + 60_000; while (Date.now() < deadline) { try { if ( ( await openObserveRequest("/api/default/streams", { password, account: "query", role: "grafana", }) ).status === 200 ) { ready = true; break; } } catch {} await Bun.sleep(500); } requireThat(ready, "OPENOBSERVE_QUERY_GUARD_START_TIMEOUT"); const now = Date.now() * 1000, body = (size: number, start = now - 300000000, end = now) => ({ query: { sql: 'SELECT trace_id FROM "messenger" LIMIT 1', start_time: start, end_time: end, size, }, }), values = ( size: string, begin = String(now - 300000000), end = String(now), ) => "/api/default/messenger/_values?" + new URLSearchParams({ fields: "service_name", start_time: begin, end_time: end, size, type: "traces", }), range = (seconds: number) => "/api/default/prometheus/api/v1/query_range?" + new URLSearchParams({ query: "vector(1)", start: String(now / 1e6 - seconds), end: String(now / 1e6), step: "60", }); const cases: { name: string; path: string; method?: string; body?: unknown; expected: number; }[] = [ { name: "native bounded search", path: "/api/default/_search?type=traces", body: body(100), expected: 200, }, { name: "native PromQL GET", path: "/api/default/prometheus/api/v1/query?query=vector%281%29", expected: 200, }, { name: "plugin organizations", path: "/api/organizations?page_num=0&page_size=1000", expected: 200, }, { name: "plugin streams", path: "/api/default/streams?type=traces&fetchSchema=false", expected: 200, }, { name: "plugin schema", path: "/api/default/streams/messenger/schema?type=traces", expected: 200, }, { name: "plugin bounded values", path: values("50"), expected: 200 }, { name: "values over1000", path: values("1001"), expected: 400 }, { name: "values over1hour", path: values("50", String(now - 3600000001)), expected: 400, }, { name: "range60seconds", path: range(60), expected: 200 }, { name: "range3600point5seconds", path: range(3600.5), expected: 400 }, { name: "range2hours", path: range(7200), expected: 400 }, { name: "duplicate size", path: values("1") + "&size=1001", expected: 400, }, { name: "encoded duplicate size", path: values("1") + "&%73ize=1001", expected: 400, }, { name: "duplicate start_time", path: values("1") + "&start_time=1", expected: 400, }, { name: "encoded duplicate end_time", path: values("1") + "&%65nd_time=1", expected: 400, }, { name: "zero search size", path: "/api/default/_search?type=traces", body: body(0), expected: 400, }, { name: "over1000 search size", path: "/api/default/_search?type=traces", body: body(1001), expected: 400, }, { name: "inverted search window", path: "/api/default/_search?type=traces", body: body(10, now, now - 1), expected: 400, }, { name: "over1hour search window", path: "/api/default/_search?type=traces", body: body(10, now - 3600000001), expected: 400, }, { name: "oversized search body", path: "/api/default/_search?type=traces", body: { ...body(10), padding: "x".repeat(70000) }, expected: 413, }, { name: "query ingest forbidden", path: "/api/default/guard_probe/_json", body: [{ event: "bounded_gateway_negative" }], expected: 403, }, { name: "query admin forbidden", path: "/api/default/users", expected: 403, }, { name: "stream settings forbidden", path: "/api/default/streams/messenger/settings", method: "PUT", body: {}, expected: 403, }, ]; const results = []; for (let index = 0; index < cases.length; index++) { const test = cases[index]; stage = "NATIVE_QUERY_CASE_" + index; const response = await openObserveRequest(test.path, { password, account: "query", role: "grafana", method: test.method, body: test.body, }); results.push({ name: test.name, expected: test.expected, actual: response.status, }); requireThat( response.status === test.expected, "OPENOBSERVE_QUERY_CASE_" + index + "_HTTP_" + response.status, ); } stage = "SOURCE_POSTGUARD"; requireThat( createHash("sha256") .update(await readFile(configPath)) .digest("hex") === configSha, "OPENOBSERVE_GATEWAY_CONFIG_DRIFT", ); await lease.verify(); await writeFile( receipt, JSON.stringify( { state: "PASS_NATIVE_QUERY_GUARD_CASES", stage, source_handover_sha256: lease.sha256, gateway_config_sha256: configSha, native: "HAProxy3.2.26 + OpenObserve1.1.2 + own query SA and mTLS", results, query_size_is_only_request_guard: true, hard_sql_result_cap_claimed: false, native_grafana: false, native_bao: false, }, null, 2, ) + "\n", ); console.log( "PASS_NATIVE_OPENOBSERVE_QUERY_GUARDS_AND_PLUGIN_METADATA_PATHS", ); } catch (error) { primary = error; await Promise.allSettled([ writeFile( receipt, JSON.stringify({ state: "FAILED", stage, code: error instanceof Error && /^[A-Z][A-Za-z0-9_:-]{0,240}$/.test(error.message) ? error.message : "PRIVATE_DETAILS_ONLY", }) + "\n", ), ]); throw error; } finally { if (started) { const stop = await Promise.allSettled([ compose(["stop", "openobserve", "openobserve-gateway"], { allowFailure: true, }), ]); const stopped = stop[0].status === "fulfilled" && stop[0].value.code === 0; await Promise.allSettled([ Promise.resolve().then(async () => { const saved = JSON.parse(await readFile(receipt, "utf8")); saved.stop_exit = stop[0].status === "fulfilled" ? stop[0].value.code : null; if (!stopped && !primary) saved.state = "FAILED_TEARDOWN"; await writeFile(receipt, JSON.stringify(saved, null, 2) + "\n"); }), ]); if (!stopped && !primary) throw new Error("OPENOBSERVE_QUERY_GUARD_STOP_FAILED"); console.log( stopped ? "OWN_QUERY_GUARD_STORAGE_STOPPED" : "OWN_QUERY_GUARD_STOP_REQUIRES_INSPECTION", ); } } } if (import.meta.main) { try { await main(); } catch (error) { safeFailure(error); } }