forked from mtusi2026/mtusi2026lab7
Prepare verified laboratory 7 implementation and evidence
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
import { readFile, readdir, stat, writeFile } from "node:fs/promises";
|
||||
import { resolve, relative } from "node:path";
|
||||
import { root, local, run, compose, requireThat } from "../scripts/runtime";
|
||||
import { decrypt } from "../scripts/operator-crypto";
|
||||
import { containerID } from "../scripts/runtime-inspect";
|
||||
import { readCanonicalGitProof } from "../scripts/git-tracking-source";
|
||||
import { type GitTrackingSource } from "../scripts/git-tracking-proof";
|
||||
export async function auditArtifacts(
|
||||
password: string,
|
||||
gitSource: GitTrackingSource,
|
||||
) {
|
||||
const secrets = decrypt<Record<string, string>>(
|
||||
await readFile(resolve(local, "operator/services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
const values = Object.values(secrets).filter(
|
||||
(v) => typeof v === "string" && v.length >= 20,
|
||||
);
|
||||
const files: string[] = [];
|
||||
async function walk(path: string) {
|
||||
for (const entry of await readdir(path, { withFileTypes: true })) {
|
||||
if (
|
||||
[".git", "node_modules", ".venv"].includes(entry.name) ||
|
||||
entry.name.startsWith(".local") ||
|
||||
entry.name === ".env" ||
|
||||
entry.name.endsWith(".zip")
|
||||
)
|
||||
continue;
|
||||
const target = resolve(path, entry.name);
|
||||
if (entry.isDirectory()) await walk(target);
|
||||
else if (entry.isFile()) files.push(target);
|
||||
}
|
||||
}
|
||||
await walk(root);
|
||||
let violations = 0;
|
||||
for (const file of files) {
|
||||
const info = await stat(file);
|
||||
requireThat(
|
||||
info.size <= 20 * 1024 * 1024,
|
||||
"UNEXPECTED_LARGE_SOURCE_ARTIFACT",
|
||||
);
|
||||
const content = await readFile(file);
|
||||
for (const value of values)
|
||||
if (content.includes(Buffer.from(value))) violations++;
|
||||
}
|
||||
let gitProvenance: Record<string, unknown>;
|
||||
if (gitSource.kind === "canonical-proof")
|
||||
gitProvenance = {
|
||||
kind: gitSource.kind,
|
||||
...(await readCanonicalGitProof(gitSource)),
|
||||
};
|
||||
else {
|
||||
const forbidden = await run([
|
||||
"git",
|
||||
"ls-files",
|
||||
".env",
|
||||
".local/**",
|
||||
"*.key",
|
||||
"*.pem",
|
||||
]);
|
||||
requireThat(!forbidden.out.trim(), "PRIVATE_MATERIAL_TRACKED");
|
||||
gitProvenance = { kind: "native-git", tracked_private_files: 0 };
|
||||
}
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
const id = await containerID(service),
|
||||
info = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
requireThat(
|
||||
info.Config.User !== "0" &&
|
||||
info.Config.User !== "" &&
|
||||
info.HostConfig.ReadonlyRootfs === true,
|
||||
"APP_PRIVILEGE_OR_FILESYSTEM",
|
||||
);
|
||||
requireThat(
|
||||
info.HostConfig.CapDrop.includes("ALL") &&
|
||||
info.HostConfig.SecurityOpt.includes("no-new-privileges:true") &&
|
||||
info.HostConfig.Memory > 0 &&
|
||||
info.HostConfig.PidsLimit > 0,
|
||||
"APP_LIMITS_OR_CAPABILITIES",
|
||||
);
|
||||
requireThat(
|
||||
!info.Mounts.some((m: any) =>
|
||||
/docker.sock|operator|\/ca$/.test(m.Source),
|
||||
),
|
||||
"OPERATOR_MATERIAL_MOUNTED_IN_APP",
|
||||
);
|
||||
const logs = await compose(["logs", "--no-color", service]);
|
||||
for (const value of values)
|
||||
if ((logs.out + logs.err).includes(value)) violations++;
|
||||
}
|
||||
requireThat(violations === 0, "SECRET_LEAK_DETECTED");
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/artifacts-and-hardening.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
source_files_checked: files.length,
|
||||
generated_secret_values_checked: values.length,
|
||||
secret_matches: violations,
|
||||
tracked_private_files: 0,
|
||||
git_tracking_provenance: gitProvenance,
|
||||
app_nonroot_readonly_capdrop_limits: true,
|
||||
operator_mounts_in_app: 0,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_SECRET_ARTIFACTS_LOGS_AND_EFFECTIVE_APP_HARDENING");
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, requireThat } from "../scripts/runtime";
|
||||
import { bao } from "../scripts/bao-client";
|
||||
import { parseKV } from "../scripts/kv-secrets";
|
||||
export async function auditBao() {
|
||||
const results = [];
|
||||
for (const role of ["api", "worker"]) {
|
||||
const login = await bao("/auth/cert/login", { role, body: { name: role } });
|
||||
const auth = login.data.auth;
|
||||
requireThat(
|
||||
typeof auth.client_token === "string" &&
|
||||
auth.lease_duration > 0 &&
|
||||
auth.lease_duration <= 300 &&
|
||||
auth.renewable === true,
|
||||
"BAO_TOKEN_LIFETIME_INVALID",
|
||||
);
|
||||
requireThat(
|
||||
auth.policies.length === 1 && auth.policies[0] === role,
|
||||
"BAO_POLICY_NOT_SCOPED",
|
||||
);
|
||||
const token = auth.client_token;
|
||||
const own = await bao("/kv/data/" + role, { role, token });
|
||||
parseKV(own, role as "api" | "worker");
|
||||
const other = await bao("/kv/data/" + (role === "api" ? "worker" : "api"), {
|
||||
role,
|
||||
token,
|
||||
expected: [403],
|
||||
});
|
||||
const admin = await bao("/sys/policies/acl/forbidden", {
|
||||
role,
|
||||
token,
|
||||
body: { policy: 'path "*" {capabilities=["read"]}' },
|
||||
expected: [403],
|
||||
});
|
||||
const renew = await bao("/auth/token/renew-self", {
|
||||
role,
|
||||
token,
|
||||
body: { increment: 60 },
|
||||
});
|
||||
requireThat(
|
||||
renew.data.auth.lease_duration > 0 &&
|
||||
renew.data.auth.lease_duration <= 300,
|
||||
"BAO_RENEWAL_INVALID",
|
||||
);
|
||||
await bao("/auth/token/revoke-self", { role, token, body: {} });
|
||||
await bao("/kv/data/" + role, { role, token, expected: [403] });
|
||||
results.push({
|
||||
role,
|
||||
policy: role,
|
||||
lease_seconds: auth.lease_duration,
|
||||
own_path: own.status,
|
||||
foreign_path: other.status,
|
||||
policy_write: admin.status,
|
||||
renewed: true,
|
||||
revoked_new_request_denied: true,
|
||||
});
|
||||
}
|
||||
const forbidden = await bao("/auth/cert/login", {
|
||||
role: "forbidden",
|
||||
body: { name: "api" },
|
||||
expected: [400, 403],
|
||||
});
|
||||
requireThat(forbidden.status !== 200, "BAO_FORBIDDEN_IDENTITY_ACCEPTED");
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/openbao-policy.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
non_dev: true,
|
||||
persistent_storage: "pebbledb",
|
||||
service_auth: "native cert auto-auth",
|
||||
results,
|
||||
same_ca_forbidden_identity: forbidden.status,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_BAO_OWN_PATH_ALLOW_FOREIGN_ADMIN_DENY_RENEW_REVOKE");
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { createBrowserLifecycle } from "../scripts/browser-lifecycle";
|
||||
|
||||
function fixture(
|
||||
failure: "newPage" | "listener" | "none",
|
||||
closeFailure = false,
|
||||
primary: unknown = new Error("PRIMARY"),
|
||||
) {
|
||||
const secondary = new Error("CLOSE"),
|
||||
reports: unknown[] = [];
|
||||
let closes = 0;
|
||||
const context = {
|
||||
newPage: async () => {
|
||||
if (failure === "newPage") throw primary;
|
||||
return {
|
||||
on: () => {
|
||||
if (failure === "listener") throw primary;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const run = createBrowserLifecycle({
|
||||
acquire: async () => context,
|
||||
run: async (acquired) => {
|
||||
const page = await acquired.newPage();
|
||||
page.on();
|
||||
return "complete";
|
||||
},
|
||||
close: async (acquired) => {
|
||||
expect(acquired).toBe(context);
|
||||
closes++;
|
||||
if (closeFailure) throw secondary;
|
||||
},
|
||||
reportCleanupFailure: async (error) => {
|
||||
reports.push(error);
|
||||
},
|
||||
});
|
||||
return { run, primary, secondary, reports, closes: () => closes };
|
||||
}
|
||||
test("newPage rejection closes the already acquired context exactly once", async () => {
|
||||
const f = fixture("newPage");
|
||||
await expect(f.run()).rejects.toBe(f.primary);
|
||||
expect(f.closes()).toBe(1);
|
||||
});
|
||||
test("listener setup failure closes the already acquired context exactly once", async () => {
|
||||
const f = fixture("listener");
|
||||
await expect(f.run()).rejects.toBe(f.primary);
|
||||
expect(f.closes()).toBe(1);
|
||||
});
|
||||
test("normal browser work returns its result and closes exactly once", async () => {
|
||||
const f = fixture("none");
|
||||
expect(await f.run()).toBe("complete");
|
||||
expect(f.closes()).toBe(1);
|
||||
expect(f.reports).toEqual([]);
|
||||
});
|
||||
test("cleanup failure is separately reported without replacing the primary error", async () => {
|
||||
const f = fixture("listener", true);
|
||||
await expect(f.run()).rejects.toBe(f.primary);
|
||||
expect(f.closes()).toBe(1);
|
||||
expect(f.reports).toEqual([f.secondary]);
|
||||
});
|
||||
test("cleanup failure after successful work remains a failure", async () => {
|
||||
const f = fixture("none", true);
|
||||
await expect(f.run()).rejects.toBe(f.secondary);
|
||||
expect(f.closes()).toBe(1);
|
||||
expect(f.reports).toEqual([f.secondary]);
|
||||
});
|
||||
test("missing ports reject before any browser can be acquired", () => {
|
||||
expect(() => createBrowserLifecycle({} as any)).toThrow(
|
||||
"BROWSER_LIFECYCLE_PORTS_REQUIRED",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
assertSameSnapshot,
|
||||
createEvidencePreserver,
|
||||
pinHandover,
|
||||
assertAcceptedGeneration,
|
||||
} from "../scripts/checkpoint-guards";
|
||||
const hash = (value: Uint8Array) =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
test("checkpoint second snapshot rejects changed bytes, additions and removals", () => {
|
||||
const first = { a: "a".repeat(64) },
|
||||
mutations: Record<string, string>[] = [
|
||||
{ a: "b".repeat(64) },
|
||||
{ ...first, b: "b".repeat(64) },
|
||||
{},
|
||||
];
|
||||
for (const second of mutations)
|
||||
expect(() => assertSameSnapshot(first, second)).toThrow(
|
||||
"SOURCE_SNAPSHOT_CHANGED",
|
||||
);
|
||||
expect(() => assertSameSnapshot(first, { ...first })).not.toThrow();
|
||||
});
|
||||
test("historical evidence never replaces existing different bytes and permits exact identical bytes", async () => {
|
||||
let existing = Buffer.from("old"),
|
||||
writes = 0;
|
||||
const preserve = createEvidencePreserver({
|
||||
writeExclusive: async () => {
|
||||
writes++;
|
||||
throw Object.assign(new Error("exists"), { code: "EEXIST" });
|
||||
},
|
||||
read: async () => existing,
|
||||
});
|
||||
await expect(preserve("fixture", Buffer.from("new"))).rejects.toThrow(
|
||||
"HISTORICAL_EVIDENCE_CONFLICT",
|
||||
);
|
||||
expect(existing.toString()).toBe("old");
|
||||
await preserve("fixture", Buffer.from("old"));
|
||||
expect(writes).toBe(2);
|
||||
});
|
||||
test("handover lease rejects a different valid source generation after initial verification", async () => {
|
||||
let source = Buffer.from("A");
|
||||
const receipt = () =>
|
||||
Buffer.from(
|
||||
JSON.stringify({
|
||||
checkedAt: "2026-11-15T17:47:34Z",
|
||||
runtimeTelemetry: false,
|
||||
runtimeSecurity: false,
|
||||
files: { "main.go": hash(source) },
|
||||
preservedFreshness: {},
|
||||
}),
|
||||
);
|
||||
let current = receipt();
|
||||
const lease = await pinHandover({
|
||||
readReceipt: async () => current,
|
||||
readSource: async () => source,
|
||||
});
|
||||
expect(lease.count).toBe(1);
|
||||
source = Buffer.from("B");
|
||||
current = receipt();
|
||||
await expect(lease.verify()).rejects.toThrow("HANDOVER_GENERATION_CHANGED");
|
||||
});
|
||||
test("handover lease rejects source mutation even when receipt is unchanged", async () => {
|
||||
let source = Buffer.from("A");
|
||||
const current = Buffer.from(
|
||||
JSON.stringify({
|
||||
checkedAt: "2026-11-15T17:47:34Z",
|
||||
runtimeTelemetry: false,
|
||||
runtimeSecurity: false,
|
||||
files: { "main.go": hash(source) },
|
||||
preservedFreshness: {},
|
||||
}),
|
||||
);
|
||||
const lease = await pinHandover({
|
||||
readReceipt: async () => current,
|
||||
readSource: async () => source,
|
||||
});
|
||||
source = Buffer.from("B");
|
||||
await expect(lease.verify()).rejects.toThrow("HANDOVER_SOURCE_CHANGED");
|
||||
});
|
||||
test("historical finalization requires its accepted source and build generation binding", () => {
|
||||
const source = Buffer.from(
|
||||
JSON.stringify({
|
||||
checkedAt: "A",
|
||||
files: { a: "a" },
|
||||
preservedFreshness: {},
|
||||
}),
|
||||
),
|
||||
build = {
|
||||
backend_checked_at: "A",
|
||||
source_handover_sha256: hash(source),
|
||||
source_files_verified: 1,
|
||||
binaries: { app: "a", worker: "w" },
|
||||
};
|
||||
const accepted = {
|
||||
backend_checked_at: "A",
|
||||
source_handover_sha256: hash(source),
|
||||
source_files_verified: 1,
|
||||
binaries: { app: "a", worker: "w" },
|
||||
};
|
||||
expect(() => assertAcceptedGeneration(accepted, source, build)).not.toThrow();
|
||||
expect(() =>
|
||||
assertAcceptedGeneration(
|
||||
{ ...accepted, backend_checked_at: "B" },
|
||||
source,
|
||||
build,
|
||||
),
|
||||
).toThrow("ACCEPTED_GENERATION_MISMATCH");
|
||||
expect(() => assertAcceptedGeneration(undefined, source, build)).toThrow(
|
||||
"ACCEPTED_GENERATION_MISMATCH",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { createCommandRunner } from "../scripts/command-runner";
|
||||
test("secondary diagnostic failures cannot replace command exit and both receipt writers are attempted", async () => {
|
||||
for (const failed of ["unique", "last", "both"]) {
|
||||
const calls: string[] = [];
|
||||
const runner = createCommandRunner({
|
||||
execute: async () => ({
|
||||
out: "fixture-output",
|
||||
err: "fixture-error",
|
||||
code: 17,
|
||||
}),
|
||||
unique: async () => {
|
||||
calls.push("unique");
|
||||
if (failed !== "last") throw new Error("FIXTURE_EVIDENCE_IO_FAILED");
|
||||
},
|
||||
last: async () => {
|
||||
calls.push("last");
|
||||
if (failed !== "unique") throw new Error("FIXTURE_EVIDENCE_IO_FAILED");
|
||||
},
|
||||
});
|
||||
await expect(runner(["fixture-command"])).rejects.toThrow(
|
||||
"COMMAND_FAILED_fixture_command_17",
|
||||
);
|
||||
expect(calls.sort()).toEqual(["last", "unique"]);
|
||||
}
|
||||
});
|
||||
test("successful and explicitly allowed command outcomes are returned without diagnostic writes", async () => {
|
||||
for (const code of [0, 17]) {
|
||||
let writes = 0;
|
||||
const result = { out: "fixture-output", err: "fixture-error", code };
|
||||
const runner = createCommandRunner({
|
||||
execute: async () => result,
|
||||
unique: async () => {
|
||||
writes++;
|
||||
},
|
||||
last: async () => {
|
||||
writes++;
|
||||
},
|
||||
});
|
||||
expect(await runner(["fixture-command"], { allowFailure: true })).toEqual(
|
||||
result,
|
||||
);
|
||||
expect(writes).toBe(0);
|
||||
}
|
||||
});
|
||||
test("runner requires explicit fake ports and preserves primary execution error", async () => {
|
||||
expect(() => createCommandRunner({} as never)).toThrow(
|
||||
"INVALID_COMMAND_RUNNER_PORTS",
|
||||
);
|
||||
const primary = new Error("FIXTURE_EXECUTION_FAILED");
|
||||
const runner = createCommandRunner({
|
||||
execute: async () => {
|
||||
throw primary;
|
||||
},
|
||||
unique: async () => {
|
||||
throw new Error("UNEXPECTED_WRITE");
|
||||
},
|
||||
last: async () => {
|
||||
throw new Error("UNEXPECTED_WRITE");
|
||||
},
|
||||
});
|
||||
await expect(runner(["fixture-command"])).rejects.toBe(primary);
|
||||
});
|
||||
@@ -0,0 +1,524 @@
|
||||
import { readFile, copyFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
run,
|
||||
compose,
|
||||
privateWrite,
|
||||
requireThat,
|
||||
} from "../scripts/runtime";
|
||||
import { unlock, unseal } from "../scripts/openbao-operator";
|
||||
import { bao } from "../scripts/bao-client";
|
||||
import { parseKV } from "../scripts/kv-secrets";
|
||||
import { issue } from "../scripts/pki";
|
||||
import { reloadGateway } from "../scripts/reload-gateway";
|
||||
import { containerID, containerIP } from "../scripts/runtime-inspect";
|
||||
import { tlsProbe, expectDenied } from "./transport";
|
||||
import { waitReady } from "./wait";
|
||||
import { auditArtifacts } from "./artifacts";
|
||||
import { workerCompromise } from "../scripts/rotation";
|
||||
import { HTTP } from "./http";
|
||||
import { publicLBEndpoint } from "../scripts/public-endpoint";
|
||||
import { createSealedShutdown } from "../scripts/sealed-shutdown";
|
||||
import { type GitTrackingSource } from "../scripts/git-tracking-proof";
|
||||
import {
|
||||
createHealthConvergence,
|
||||
freshSecretsAfterSeal,
|
||||
} from "../scripts/health-convergence";
|
||||
const health =
|
||||
"GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
function opensslDate(timestamp: number) {
|
||||
return (
|
||||
new Date(timestamp).toISOString().replace(/[-:T]/g, "").slice(0, 14) + "Z"
|
||||
);
|
||||
}
|
||||
export async function certificateLifetime(
|
||||
password: string,
|
||||
scope: "full" | "cached" = "full",
|
||||
) {
|
||||
const path = resolve(local, "pki/lb/server.pem"),
|
||||
original = await readFile(path),
|
||||
ca = resolve(local, "operator/ca"),
|
||||
outcomes = [];
|
||||
const lbID = await containerID("lb"),
|
||||
endpoint = publicLBEndpoint(
|
||||
JSON.parse((await run(["docker", "inspect", lbID])).out)[0],
|
||||
);
|
||||
const positive = await tlsProbe(
|
||||
endpoint.host,
|
||||
endpoint.port,
|
||||
endpoint.servername,
|
||||
null,
|
||||
health,
|
||||
);
|
||||
requireThat(
|
||||
/HTTP\/1\.[01] 200/.test(positive.data),
|
||||
"LIFETIME_PUBLIC_TLS_POSITIVE_FAILED",
|
||||
);
|
||||
try {
|
||||
for (const mode of ["expired", "future"]) {
|
||||
const destination = resolve(local, "operator", "lifetime-" + mode),
|
||||
now = Date.now();
|
||||
await issue(ca, destination, "lb", password, {
|
||||
start: opensslDate(now + (mode === "expired" ? -2 : 1) * 86400_000),
|
||||
end: opensslDate(now + (mode === "expired" ? -1 : 2) * 86400_000),
|
||||
});
|
||||
await privateWrite(
|
||||
path,
|
||||
await readFile(resolve(destination, "server.pem")),
|
||||
);
|
||||
await reloadGateway("lb");
|
||||
await Bun.sleep(2500);
|
||||
const code = await expectDenied(
|
||||
() =>
|
||||
tlsProbe(
|
||||
endpoint.host,
|
||||
endpoint.port,
|
||||
endpoint.servername,
|
||||
null,
|
||||
health,
|
||||
),
|
||||
"trust",
|
||||
);
|
||||
requireThat(
|
||||
code ===
|
||||
(mode === "expired" ? "CERT_HAS_EXPIRED" : "CERT_NOT_YET_VALID"),
|
||||
"CERTIFICATE_LIFETIME_WRONG_FAILURE",
|
||||
);
|
||||
outcomes.push({ mode, code });
|
||||
}
|
||||
} finally {
|
||||
await privateWrite(path, original);
|
||||
await reloadGateway("lb");
|
||||
await waitReady();
|
||||
}
|
||||
await writeFile(
|
||||
resolve(
|
||||
root,
|
||||
scope === "full"
|
||||
? "evidence/security/certificate-lifetime.json"
|
||||
: "evidence/preflight/certificate-lifetime.json",
|
||||
),
|
||||
JSON.stringify(
|
||||
{
|
||||
scope,
|
||||
actual_listener:
|
||||
"verified published loopback LB TLS binding; native HAProxy master-worker reload",
|
||||
outcomes,
|
||||
restored_verified_https: true,
|
||||
image_rebuild: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
}
|
||||
export async function sealedLifecycle(password: string, operationId: string) {
|
||||
requireThat(/^[a-f0-9-]{36}$/.test(operationId), "SEALED_OPERATION_INVALID");
|
||||
const operator = await unlock(password);
|
||||
const observe = createSealedShutdown(
|
||||
{
|
||||
inspect: async (service, expectedId) => {
|
||||
const id = expectedId ?? (await containerID(service));
|
||||
const state = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
requireThat(
|
||||
state.Config.Labels["com.docker.compose.project"] ===
|
||||
"mtuci-vp7-security" &&
|
||||
state.Config.Labels["com.docker.compose.service"] === service,
|
||||
"SEALED_FOREIGN_CONTAINER",
|
||||
);
|
||||
return {
|
||||
id: state.Id,
|
||||
running: state.State.Running,
|
||||
restarts: state.RestartCount,
|
||||
};
|
||||
},
|
||||
readFreshness: (service) =>
|
||||
readFile(resolve(local, "rendered", service, "freshness"), "utf8"),
|
||||
readEvents: async (id, since) => {
|
||||
const logs = await run([
|
||||
"docker",
|
||||
"logs",
|
||||
"--timestamps",
|
||||
"--tail",
|
||||
"200",
|
||||
"--since",
|
||||
new Date(since).toISOString(),
|
||||
id,
|
||||
]);
|
||||
const events = [];
|
||||
for (const line of (logs.out + "\n" + logs.err).split("\n")) {
|
||||
const split = line.indexOf(" ");
|
||||
if (split < 0) continue;
|
||||
try {
|
||||
const row = JSON.parse(line.slice(split + 1));
|
||||
if (row.event === "secret_freshness_failed")
|
||||
events.push({
|
||||
event: row.event,
|
||||
milliseconds: Date.parse(line.slice(0, split)),
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
return events;
|
||||
},
|
||||
retainBaseline: async (value) => {
|
||||
await writeFile(
|
||||
resolve(
|
||||
root,
|
||||
"evidence/security/sealed-baseline-" + operationId + ".json",
|
||||
),
|
||||
JSON.stringify({ operation_id: operationId, ...value }, null, 2) +
|
||||
"\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
},
|
||||
seal: async () => {
|
||||
await bao("/sys/seal", { token: operator.root_token, body: {} });
|
||||
},
|
||||
now: Date.now,
|
||||
sleep: (milliseconds) => Bun.sleep(milliseconds),
|
||||
},
|
||||
{
|
||||
maxAgeMilliseconds: 120000,
|
||||
deadlineMilliseconds: 190000,
|
||||
pollMilliseconds: 2000,
|
||||
},
|
||||
);
|
||||
let proof: Awaited<ReturnType<typeof observe>> | undefined;
|
||||
let primary: unknown,
|
||||
failed = false,
|
||||
recoveryFailure: unknown,
|
||||
rejectionAt = 0,
|
||||
recoveryStarted = 0;
|
||||
try {
|
||||
proof = await observe();
|
||||
rejectionAt = Date.now();
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/sealed-cause-" + operationId + ".json"),
|
||||
JSON.stringify(
|
||||
{ operation_id: operationId, ...proof, rejection_at: rejectionAt },
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
const publicResult = await run([
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--cacert",
|
||||
resolve(local, "pki/lb/ca.crt"),
|
||||
"--max-time",
|
||||
"5",
|
||||
"--output",
|
||||
"/dev/null",
|
||||
"--write-out",
|
||||
"%{http_code}",
|
||||
"https://localhost:18443/health/ready",
|
||||
]);
|
||||
requireThat(publicResult.out === "503", "SEALED_BAO_STALE_API_STILL_READY");
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/sealed-public-" + operationId + ".json"),
|
||||
JSON.stringify({
|
||||
operation_id: operationId,
|
||||
http_status: 503,
|
||||
sealed_at: proof.sealedAt,
|
||||
observed_at: Date.now(),
|
||||
}) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
} catch (error) {
|
||||
primary = error;
|
||||
failed = true;
|
||||
} finally {
|
||||
recoveryStarted = Date.now();
|
||||
try {
|
||||
await unseal(password);
|
||||
const baoId = await containerID("openbao");
|
||||
const health = await createHealthConvergence(
|
||||
{
|
||||
read: async () => {
|
||||
const info = JSON.parse(
|
||||
(await run(["docker", "inspect", baoId])).out,
|
||||
)[0];
|
||||
requireThat(
|
||||
info.Id.startsWith(baoId) &&
|
||||
info.State.Running &&
|
||||
info.Config.Labels["com.docker.compose.project"] ===
|
||||
"mtuci-vp7-security" &&
|
||||
info.Config.Labels["com.docker.compose.service"] === "openbao",
|
||||
"RECOVERY_BAO_OWNER_OR_STATE_CHANGED",
|
||||
);
|
||||
return info.State.Health?.Status ?? "unknown";
|
||||
},
|
||||
now: Date.now,
|
||||
sleep: (ms) => Bun.sleep(ms),
|
||||
},
|
||||
10000,
|
||||
250,
|
||||
)();
|
||||
await writeFile(
|
||||
resolve(
|
||||
root,
|
||||
"evidence/security/sealed-recovery-health-" + operationId + ".json",
|
||||
),
|
||||
JSON.stringify({
|
||||
operation_id: operationId,
|
||||
container: baoId,
|
||||
...health,
|
||||
}) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
await compose(["restart", "api1-agent", "api2-agent", "worker-agent"]);
|
||||
const freshness = await createHealthConvergence(
|
||||
{
|
||||
read: async () =>
|
||||
freshSecretsAfterSeal(
|
||||
await Promise.all(
|
||||
["api1", "api2", "worker"].map((service) =>
|
||||
readFile(
|
||||
resolve(local, "rendered", service, "freshness"),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
),
|
||||
proof?.sealedAt ?? recoveryStarted,
|
||||
Date.now(),
|
||||
120000,
|
||||
)
|
||||
? "healthy"
|
||||
: "unhealthy",
|
||||
now: Date.now,
|
||||
sleep: (ms) => Bun.sleep(ms),
|
||||
},
|
||||
120000,
|
||||
500,
|
||||
)().catch((error) => {
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.message === "BAO_HEALTH_NOT_CONVERGED"
|
||||
)
|
||||
throw new Error("SEALED_AGENT_FRESHNESS_NOT_CONVERGED", {
|
||||
cause: error,
|
||||
});
|
||||
throw error;
|
||||
});
|
||||
await writeFile(
|
||||
resolve(
|
||||
root,
|
||||
"evidence/security/sealed-recovery-render-" + operationId + ".json",
|
||||
),
|
||||
JSON.stringify({
|
||||
operation_id: operationId,
|
||||
...freshness,
|
||||
controlled_agent_restart: true,
|
||||
all_three_post_seal: true,
|
||||
}) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"api1-agent",
|
||||
"api2-agent",
|
||||
"worker-agent",
|
||||
"api1",
|
||||
"api2",
|
||||
"worker",
|
||||
]);
|
||||
await waitReady(["api1", "api2"], 120_000);
|
||||
} catch (error) {
|
||||
recoveryFailure = error;
|
||||
await Promise.allSettled([
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/sealed-recovery-error.json"),
|
||||
JSON.stringify({
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if (failed) throw primary;
|
||||
if (recoveryFailure !== undefined) throw recoveryFailure;
|
||||
requireThat(proof, "SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
||||
const recoveredFreshness: Record<string, number> = {};
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
const timestamp = Date.parse(
|
||||
(
|
||||
await readFile(
|
||||
resolve(local, "rendered", service, "freshness"),
|
||||
"utf8",
|
||||
)
|
||||
).trim(),
|
||||
),
|
||||
age = Date.now() - timestamp;
|
||||
requireThat(
|
||||
Number.isFinite(age) &&
|
||||
age >= 0 &&
|
||||
age <= 120000 &&
|
||||
timestamp > proof.sealedAt,
|
||||
"SEALED_RECOVERY_NOT_FRESH",
|
||||
);
|
||||
recoveredFreshness[service] = timestamp;
|
||||
}
|
||||
const http = new HTTP(),
|
||||
a = await http.user("recovery"),
|
||||
b = await http.user("peer");
|
||||
const chat = (
|
||||
await http.call("POST", "/api/v1/chats", 201, {
|
||||
actor: a.token,
|
||||
body: { title: "After unseal", member_ids: [a.id, b.id] },
|
||||
})
|
||||
).json;
|
||||
const fixture = new Uint8Array(
|
||||
await readFile(resolve(root, "tests/fixtures/sample.png")),
|
||||
);
|
||||
const att = (
|
||||
await http.call(
|
||||
"POST",
|
||||
`/api/v1/chats/${chat.id}/attachments?filename=recovery.png`,
|
||||
202,
|
||||
{
|
||||
actor: a.token,
|
||||
raw: fixture,
|
||||
headers: { "Content-Type": "image/png" },
|
||||
},
|
||||
)
|
||||
).json;
|
||||
await http.ready(b.token, att.id);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/sealed-lifecycle.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
operation_id: operationId,
|
||||
baseline: proof.baseline,
|
||||
baseline_freshness_milliseconds: proof.freshness,
|
||||
observed_causal_shutdown: proof.observed,
|
||||
recovered_freshness_milliseconds: recoveredFreshness,
|
||||
sealed_old_credentials_bounded: true,
|
||||
stale_processes_restarted_or_stopped: true,
|
||||
public_ready_while_stale: 503,
|
||||
seconds_until_checked_rejection: (rejectionAt - proof.started) / 1000,
|
||||
recovery_seconds_including_new_upload:
|
||||
(Date.now() - recoveryStarted) / 1000,
|
||||
unseal_recovery: true,
|
||||
real_attachment_processed_after_recovery: true,
|
||||
limit:
|
||||
"observed local filesystem/scheduling; no universal hung-host wall-clock bound",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
}
|
||||
async function telemetryScope() {
|
||||
const service = "openobserve-gateway",
|
||||
ip = await containerIP(service);
|
||||
const authorization = await readFile(
|
||||
resolve(local, "config/openobserve_query_auth"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
authorization.length <= 4096 &&
|
||||
/^Basic [A-Za-z0-9+/]+={0,2}$/.test(authorization),
|
||||
"INVALID_OPENOBSERVE_AUTH_HEADER_FILE",
|
||||
);
|
||||
const positive = async () => {
|
||||
const response = await tlsProbe(
|
||||
ip,
|
||||
5082,
|
||||
service,
|
||||
"grafana",
|
||||
`GET /api/default/streams HTTP/1.1\r\nHost: localhost\r\nAuthorization: ${authorization}\r\nConnection: close\r\n\r\n`,
|
||||
);
|
||||
requireThat(
|
||||
response.authorized && /HTTP\/1\.[01] 200/.test(response.data),
|
||||
"GRAFANA_NATIVE_QUERY_POSITIVE_FAILED",
|
||||
);
|
||||
};
|
||||
await positive();
|
||||
for (const [service, port, path] of [
|
||||
["openobserve-gateway", 5082, "/api/default/v1/logs"],
|
||||
["openobserve-gateway", 5082, "/api/default/users"],
|
||||
["openobserve-gateway", 5082, "/api/foreign/_search"],
|
||||
] as const) {
|
||||
const ip = await containerIP(service);
|
||||
const denied = await tlsProbe(
|
||||
ip,
|
||||
port,
|
||||
service,
|
||||
"grafana",
|
||||
`POST ${path} HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`,
|
||||
);
|
||||
requireThat(
|
||||
/HTTP\/1\.[01] 403/.test(denied.data),
|
||||
"GRAFANA_INGEST_NOT_DENIED",
|
||||
);
|
||||
}
|
||||
await positive();
|
||||
console.log("PASS_GRAFANA_QUERY_IDENTITY_CANNOT_INGEST");
|
||||
}
|
||||
export async function extendedAcceptance(
|
||||
password: string,
|
||||
operationId: string,
|
||||
gitSource: GitTrackingSource,
|
||||
) {
|
||||
await certificateLifetime(password);
|
||||
await telemetryScope();
|
||||
await workerCompromise(password);
|
||||
await completeSecurityLifecycle(password, operationId, gitSource);
|
||||
}
|
||||
export async function completeSecurityLifecycle(
|
||||
password: string,
|
||||
operationId: string,
|
||||
gitSource: GitTrackingSource,
|
||||
) {
|
||||
const expiring = await bao("/auth/cert/login", {
|
||||
role: "api",
|
||||
body: { name: "api" },
|
||||
}),
|
||||
ttl = expiring.data.auth.lease_duration,
|
||||
token = expiring.data.auth.client_token,
|
||||
expiryAt = Date.now() + ttl * 1000 + 1500;
|
||||
requireThat(ttl > 0 && ttl <= 60, "EXPIRY_TEST_TOKEN_TTL_UNBOUNDED");
|
||||
parseKV(await bao("/kv/data/api", { role: "api", token }), "api");
|
||||
await auditArtifacts(password, gitSource);
|
||||
while (Date.now() < expiryAt)
|
||||
await Bun.sleep(Math.min(1000, expiryAt - Date.now()));
|
||||
await bao("/kv/data/api", { role: "api", token, expected: [403] });
|
||||
const fresh = await bao("/auth/cert/login", {
|
||||
role: "api",
|
||||
body: { name: "api" },
|
||||
});
|
||||
parseKV(
|
||||
await bao("/kv/data/api", {
|
||||
role: "api",
|
||||
token: fresh.data.auth.client_token,
|
||||
}),
|
||||
"api",
|
||||
);
|
||||
await bao("/auth/token/revoke-self", {
|
||||
role: "api",
|
||||
token: fresh.data.auth.client_token,
|
||||
body: {},
|
||||
});
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/token-expiry.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
token_ttl_seconds: ttl,
|
||||
initial_own_read: 200,
|
||||
expired_new_request: 403,
|
||||
new_auth_same_role_read: 200,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
await sealedLifecycle(password, operationId);
|
||||
console.log("PASS_EXTENDED_LIFECYCLE_AND_WORKER_RESEARCH");
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import {
|
||||
createFailoverReader,
|
||||
failoverReceiptPath,
|
||||
type FailoverProof,
|
||||
type ReplicaBaseline,
|
||||
} from "../scripts/failover-proof";
|
||||
const operation = "11111111-1111-4111-8111-111111111111",
|
||||
attempt = "22222222-2222-4222-8222-222222222222";
|
||||
const baseline: ReplicaBaseline = {
|
||||
api1: {
|
||||
container: "a".repeat(64),
|
||||
alias: "33333333-3333-4333-8333-333333333333",
|
||||
},
|
||||
api2: {
|
||||
container: "b".repeat(64),
|
||||
alias: "44444444-4444-4444-8444-444444444444",
|
||||
},
|
||||
};
|
||||
function valid(): FailoverProof {
|
||||
return {
|
||||
operation_id: operation,
|
||||
attempt_id: attempt,
|
||||
service: "api1",
|
||||
target_alias: baseline.api1.alias,
|
||||
container: baseline.api1.container,
|
||||
before_running: true,
|
||||
running: false,
|
||||
volumes_removed: false,
|
||||
};
|
||||
}
|
||||
test("read current receipt contents and bind its stopped replica to the current attempt baseline", async () => {
|
||||
const calls: string[] = [];
|
||||
const r = await createFailoverReader({
|
||||
read: async (path) => {
|
||||
calls.push(path);
|
||||
return valid();
|
||||
},
|
||||
})(operation, attempt, baseline);
|
||||
expect(r.proof.service).toBe("api1");
|
||||
expect(calls).toEqual([failoverReceiptPath(operation, attempt)]);
|
||||
});
|
||||
test.each([
|
||||
{
|
||||
name: "old operation",
|
||||
patch: { operation_id: attempt },
|
||||
code: "FAILOVER_WRONG_OPERATION",
|
||||
},
|
||||
{
|
||||
name: "foreign attempt",
|
||||
patch: { attempt_id: operation },
|
||||
code: "FAILOVER_WRONG_OPERATION",
|
||||
},
|
||||
{
|
||||
name: "wrong alias",
|
||||
patch: { target_alias: baseline.api2.alias },
|
||||
code: "FAILOVER_TARGET_MISMATCH",
|
||||
},
|
||||
{
|
||||
name: "wrong container",
|
||||
patch: { container: baseline.api2.container },
|
||||
code: "FAILOVER_TARGET_MISMATCH",
|
||||
},
|
||||
{
|
||||
name: "still running",
|
||||
patch: { running: true },
|
||||
code: "FAILOVER_STOP_NOT_PROVED",
|
||||
},
|
||||
{
|
||||
name: "not initially running",
|
||||
patch: { before_running: false },
|
||||
code: "FAILOVER_STOP_NOT_PROVED",
|
||||
},
|
||||
{
|
||||
name: "foreign service",
|
||||
patch: { service: "worker" },
|
||||
code: "FAILOVER_SERVICE_INVALID",
|
||||
},
|
||||
])("reject $name receipt even when a file exists", async ({ patch, code }) => {
|
||||
await expect(
|
||||
createFailoverReader({ read: async () => ({ ...valid(), ...patch }) })(
|
||||
operation,
|
||||
attempt,
|
||||
baseline,
|
||||
),
|
||||
).rejects.toThrow(code);
|
||||
});
|
||||
test("missing receipt preserves reader error instead of accepting older stable files", async () => {
|
||||
const error = new Error("FIXTURE_ENOENT");
|
||||
let actual: unknown;
|
||||
try {
|
||||
await createFailoverReader({
|
||||
read: async () => {
|
||||
throw error;
|
||||
},
|
||||
})(operation, attempt, baseline);
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
});
|
||||
test("required read port has no live filesystem fallback", () => {
|
||||
expect(() => createFailoverReader({} as never)).toThrow(
|
||||
"FAILOVER_READ_PORT_REQUIRED",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, run, requireThat } from "../scripts/runtime";
|
||||
import { containerID } from "../scripts/runtime-inspect";
|
||||
import { waitReady } from "./wait";
|
||||
// Caller stops its explicit preflight heartbeat before this function. No live provider is stopped here.
|
||||
export async function freshnessExpiry() {
|
||||
await waitReady();
|
||||
const started = Date.now(),
|
||||
since = new Date(started).toISOString(),
|
||||
baseline: any = {},
|
||||
observed: any = {};
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
const id = await containerID(service),
|
||||
state = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
requireThat(state.State.Running, "FRESHNESS_BASELINE_NOT_RUNNING");
|
||||
baseline[service] = { id, restarts: state.RestartCount };
|
||||
}
|
||||
while (Date.now() - started < 145_000) {
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
if (observed[service]) continue;
|
||||
const base = baseline[service],
|
||||
state = JSON.parse((await run(["docker", "inspect", base.id])).out)[0],
|
||||
logs = await run(["docker", "logs", "--since", since, base.id]);
|
||||
const cause = (logs.out + "\n" + logs.err).split("\n").some((line) => {
|
||||
try {
|
||||
return JSON.parse(line).event === "secret_freshness_failed";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (cause && (!state.State.Running || state.RestartCount > base.restarts))
|
||||
observed[service] = {
|
||||
event: "secret_freshness_failed",
|
||||
seconds: (Date.now() - started) / 1000,
|
||||
};
|
||||
}
|
||||
if (Object.keys(observed).length === 3) break;
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
requireThat(
|
||||
Object.keys(observed).length === 3,
|
||||
"FRESHNESS_EXPIRY_DID_NOT_STOP_ALL_PROCESSES",
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/preflight/freshness-expiry.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
provider: "explicit operator heartbeat stopped; not OpenBao seal",
|
||||
max_age_seconds: 120,
|
||||
poll_seconds: 5,
|
||||
observed,
|
||||
limit:
|
||||
"measured local filesystem and scheduling only; no hung-filesystem wall-clock guarantee",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_ACTUAL_FRESHNESS_EXPIRY_WITH_FIXED_CAUSE_EVENT");
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import {
|
||||
createAcceptCommand,
|
||||
parseGitProofCLI,
|
||||
} from "../scripts/git-proof-cli";
|
||||
const path =
|
||||
"evidence/openbao/canonical-git-proof-11111111-1111-4111-8111-111111111111.json",
|
||||
sha = "a".repeat(64),
|
||||
args = ["--checked-cache", "--git-proof", path, "--git-proof-sha", sha];
|
||||
function fixture() {
|
||||
const calls: string[] = [];
|
||||
return {
|
||||
calls,
|
||||
ports: {
|
||||
verifyProof: async (p: unknown) => {
|
||||
calls.push("proof");
|
||||
},
|
||||
password: async () => {
|
||||
calls.push("password");
|
||||
return "fixture password";
|
||||
},
|
||||
accept: async (_password: string, proof: unknown) => {
|
||||
calls.push("accept");
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
test("real Git checkout default remains native Git without proof flags", async () => {
|
||||
const f = fixture();
|
||||
expect(parseGitProofCLI(["--checked-cache"])).toEqual({ kind: "native-git" });
|
||||
await createAcceptCommand(f.ports)([]);
|
||||
expect(f.calls).toEqual(["password", "accept"]);
|
||||
});
|
||||
test("ZIP canonical proof is selected and verified before password or acceptance", async () => {
|
||||
const f = fixture();
|
||||
expect(parseGitProofCLI(args)).toEqual({
|
||||
kind: "canonical-proof",
|
||||
path,
|
||||
sha256: sha,
|
||||
});
|
||||
await createAcceptCommand(f.ports)(args);
|
||||
expect(f.calls).toEqual(["proof", "password", "accept"]);
|
||||
});
|
||||
test.each(
|
||||
[
|
||||
["--git-proof"],
|
||||
["--git-proof", path],
|
||||
["--git-proof-sha", sha],
|
||||
["--git-proof", path, "--git-proof-sha", "invalid"],
|
||||
["--git-proof", path, "--git-proof-sha", sha, "--git-proof", path],
|
||||
].map((args) => ({ args })),
|
||||
)(
|
||||
"malformed proof flags reject before credentials: $args",
|
||||
async ({ args: items }) => {
|
||||
const f = fixture();
|
||||
await expect(createAcceptCommand(f.ports)(items)).rejects.toThrow(
|
||||
"GIT_PROOF_CLI_INVALID",
|
||||
);
|
||||
expect(f.calls).toEqual([]);
|
||||
},
|
||||
);
|
||||
test("missing or changed proof preserves reader error and never reads password", async () => {
|
||||
const f = fixture(),
|
||||
error = Error("GIT_PROOF_SHA_MISMATCH");
|
||||
f.ports.verifyProof = async () => {
|
||||
throw error;
|
||||
};
|
||||
let actual;
|
||||
try {
|
||||
await createAcceptCommand(f.ports)(args);
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
expect(f.calls).toEqual([]);
|
||||
});
|
||||
test("workflow ports have no filesystem, prompt or stand defaults", () =>
|
||||
expect(() => createAcceptCommand({} as never)).toThrow(
|
||||
"ACCEPT_COMMAND_PORTS_REQUIRED",
|
||||
));
|
||||
@@ -0,0 +1,117 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import {
|
||||
createGitProofProducer,
|
||||
createGitProofReader,
|
||||
proofHash,
|
||||
type SourceHashes,
|
||||
} from "../scripts/git-tracking-proof";
|
||||
const files: SourceHashes = { "scripts/example.ts": "a".repeat(64) };
|
||||
async function produced() {
|
||||
return createGitProofProducer({
|
||||
query: async () => ({ code: 0, stdout: "" }),
|
||||
head: async () => "b".repeat(40),
|
||||
snapshot: async () => ({ ...files }),
|
||||
})("/fixture/canonical");
|
||||
}
|
||||
const bytes = (p: unknown) => Buffer.from(JSON.stringify(p));
|
||||
test("actual producer output is accepted only for matching pinned bytes and current source", async () => {
|
||||
const p = bytes(await produced());
|
||||
const r = await createGitProofReader({
|
||||
read: async () => p,
|
||||
snapshot: async () => ({ ...files }),
|
||||
})(proofHash(p));
|
||||
expect(r.tracked_private_files).toBe(0);
|
||||
expect(r.proof_sha256).toBe(proofHash(p));
|
||||
});
|
||||
test("changed proof bytes are rejected before source inspection", async () => {
|
||||
const p = bytes(await produced());
|
||||
let calls = 0;
|
||||
await expect(
|
||||
createGitProofReader({
|
||||
read: async () => Buffer.concat([p, Buffer.from(" ")]),
|
||||
snapshot: async () => {
|
||||
calls++;
|
||||
return files;
|
||||
},
|
||||
})(proofHash(p)),
|
||||
).rejects.toThrow("GIT_PROOF_SHA_MISMATCH");
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
test("missing proof preserves the primary read failure", async () => {
|
||||
const error = new Error("FIXTURE_MISSING_PROOF");
|
||||
let actual: unknown;
|
||||
try {
|
||||
await createGitProofReader({
|
||||
read: async () => {
|
||||
throw error;
|
||||
},
|
||||
snapshot: async () => files,
|
||||
})("c".repeat(64));
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
});
|
||||
const sourceChanges: { name: string; current: SourceHashes }[] = [
|
||||
{
|
||||
name: "changed source bytes",
|
||||
current: { "scripts/example.ts": "c".repeat(64) },
|
||||
},
|
||||
{
|
||||
name: "added source entry",
|
||||
current: { ...files, "scripts/new.ts": "d".repeat(64) },
|
||||
},
|
||||
];
|
||||
test.each(sourceChanges)(
|
||||
"$name invalidates canonical Git evidence",
|
||||
async ({ current }) => {
|
||||
const p = bytes(await produced());
|
||||
await expect(
|
||||
createGitProofReader({
|
||||
read: async () => p,
|
||||
snapshot: async () => current,
|
||||
})(proofHash(p)),
|
||||
).rejects.toThrow("GIT_PROOF_SOURCE_MISMATCH");
|
||||
},
|
||||
);
|
||||
test("nonempty private tracking query result never becomes a zero-count proof", async () => {
|
||||
const p = await produced();
|
||||
p.result.stdout_base64 = Buffer.from(".env\0").toString("base64");
|
||||
const b = bytes(p);
|
||||
await expect(
|
||||
createGitProofReader({ read: async () => b, snapshot: async () => files })(
|
||||
proofHash(b),
|
||||
),
|
||||
).rejects.toThrow("GIT_PROOF_INVALID");
|
||||
});
|
||||
test("a weakened query cannot prove the original private-file patterns", async () => {
|
||||
const p = await produced();
|
||||
p.query.pop();
|
||||
const b = bytes(p);
|
||||
await expect(
|
||||
createGitProofReader({ read: async () => b, snapshot: async () => files })(
|
||||
proofHash(b),
|
||||
),
|
||||
).rejects.toThrow("GIT_PROOF_INVALID");
|
||||
});
|
||||
test("producer rejects a changing HEAD during capture", async () => {
|
||||
let reads = 0;
|
||||
await expect(
|
||||
createGitProofProducer({
|
||||
query: async () => ({ code: 0, stdout: "" }),
|
||||
head: async () => (++reads === 1 ? "b".repeat(40) : "c".repeat(40)),
|
||||
snapshot: async () => files,
|
||||
})("/fixture/canonical"),
|
||||
).rejects.toThrow("GIT_CAPTURE_CHANGED");
|
||||
});
|
||||
test("producer rejects a changing source snapshot", async () => {
|
||||
let reads = 0;
|
||||
await expect(
|
||||
createGitProofProducer({
|
||||
query: async () => ({ code: 0, stdout: "" }),
|
||||
head: async () => "b".repeat(40),
|
||||
snapshot: async () =>
|
||||
++reads === 1 ? files : { "scripts/example.ts": "c".repeat(64) },
|
||||
})("/fixture/canonical"),
|
||||
).rejects.toThrow("GIT_CAPTURE_CHANGED");
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { chromium } from "playwright-core";
|
||||
import { mkdtemp } from "node:fs/promises";
|
||||
import { requireThat, root, local } from "../scripts/runtime";
|
||||
import { resolve } from "node:path";
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"BROWSER_LAUNCH_REMOTE_REQUIRED",
|
||||
);
|
||||
const profile = await mkdtemp(resolve(local, "u-"));
|
||||
requireThat(
|
||||
Buffer.byteLength(profile + "/SingletonSocket") < 90,
|
||||
"BROWSER_PROFILE_PATH_TOO_LONG",
|
||||
);
|
||||
const context = await chromium.launchPersistentContext(profile, {
|
||||
executablePath: "/usr/bin/chromium",
|
||||
headless: true,
|
||||
args: ["--no-sandbox", "--disable-gpu"],
|
||||
env: { ...process.env, TMPDIR: root },
|
||||
});
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.goto("about:blank");
|
||||
requireThat(page.url() === "about:blank", "BROWSER_BLANK_PAGE_FAILED");
|
||||
console.log("PASS_NATIVE_SHORT_PROFILE_BROWSER_LAUNCH");
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { readGrafanaDatasources } from "../scripts/grafana-datasources";
|
||||
const uids = ["prometheus", "openobserve"];
|
||||
function fixture(mutator?: (x: any) => void) {
|
||||
const calls: string[] = [],
|
||||
details = Object.fromEntries(
|
||||
uids.map((uid) => [
|
||||
uid,
|
||||
{
|
||||
uid,
|
||||
basicAuth: true,
|
||||
basicAuthUser: "vp7-query@example.invalid",
|
||||
secureJsonFields: { basicAuthPassword: true },
|
||||
},
|
||||
]),
|
||||
);
|
||||
const request = async (path: string) => {
|
||||
calls.push(path);
|
||||
if (path === "/api/datasources")
|
||||
return {
|
||||
status: 200,
|
||||
body: uids.map((uid) => ({ uid, basicAuth: true })),
|
||||
};
|
||||
const uid = path.split("/")[4]!;
|
||||
const response = path.endsWith("/health")
|
||||
? { status: 200, body: { status: "OK" } }
|
||||
: { status: 200, body: { ...details[uid] } };
|
||||
mutator?.(response);
|
||||
return response;
|
||||
};
|
||||
return { request, calls };
|
||||
}
|
||||
test("native listDTO may omit auth fields; authenticate the exact UID detail and health readers", async () => {
|
||||
const f = fixture();
|
||||
expect(await readGrafanaDatasources(f.request)).toEqual(uids);
|
||||
expect(f.calls).toEqual([
|
||||
"/api/datasources",
|
||||
"/api/datasources/uid/prometheus",
|
||||
"/api/datasources/uid/prometheus/health",
|
||||
"/api/datasources/uid/openobserve",
|
||||
"/api/datasources/uid/openobserve/health",
|
||||
]);
|
||||
});
|
||||
test("configured root account is rejected before datasource health can masquerade as scoped auth", async () => {
|
||||
const f = fixture((x) => {
|
||||
if (x.body.basicAuthUser)
|
||||
x.body.basicAuthUser = "vp7-owner@example.invalid";
|
||||
});
|
||||
await expect(readGrafanaDatasources(f.request)).rejects.toThrow(
|
||||
"GRAFANA_DATASOURCE_PRINCIPAL_MISMATCH",
|
||||
);
|
||||
});
|
||||
test("HTTP200 health with error body is not a healthy datasource", async () => {
|
||||
const f = fixture((x) => {
|
||||
if (x.body.status) x.body.status = "ERROR";
|
||||
});
|
||||
await expect(readGrafanaDatasources(f.request)).rejects.toThrow(
|
||||
"GRAFANA_DATASOURCE_HEALTH_FAILED",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
compose,
|
||||
run,
|
||||
requireThat,
|
||||
safeFailure,
|
||||
} from "../scripts/runtime";
|
||||
import { verifyBackendHandover } from "../scripts/preflight-build";
|
||||
import { openObserveRequest } from "../scripts/openobserve";
|
||||
import { containerID } from "../scripts/runtime-inspect";
|
||||
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"GAUGE_PROOF_REMOTE_REQUIRED",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/grafana/gauges-" + 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",
|
||||
"GAUGE_SOURCE_MISMATCH",
|
||||
);
|
||||
const parentPath =
|
||||
"evidence/grafana/incidents-e80b4c4d-df97-4cc9-b6d4-7ba651e0542b.json";
|
||||
const parentBytes = await readFile(resolve(root, parentPath));
|
||||
requireThat(
|
||||
createHash("sha256").update(parentBytes).digest("hex") ===
|
||||
"94a075b55cdc38b4b67b3c6a3758f200b3c0e660e51b4953010add6716e44c6c",
|
||||
"GAUGE_PARENT_MISMATCH",
|
||||
);
|
||||
const parent = JSON.parse(parentBytes.toString()),
|
||||
point = parent.live_panels.query_time_milliseconds;
|
||||
requireThat(
|
||||
Number.isSafeInteger(point) && point === 1794801461224,
|
||||
"GAUGE_POINT_MISMATCH",
|
||||
);
|
||||
stage = "OWN_STAND_IDLE";
|
||||
requireThat(
|
||||
(
|
||||
await run([
|
||||
"docker",
|
||||
"ps",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=mtuci-vp7-security",
|
||||
"--format",
|
||||
"{{.ID}}",
|
||||
])
|
||||
).out.trim() === "",
|
||||
"GAUGE_STAND_NOT_IDLE",
|
||||
);
|
||||
const workerID = await containerID("worker");
|
||||
const inspected = JSON.parse(
|
||||
(await run(["docker", "inspect", workerID])).out,
|
||||
);
|
||||
requireThat(inspected.length === 1, "GAUGE_WORKER_COUNT_INVALID");
|
||||
const worker = inspected[0];
|
||||
requireThat(
|
||||
worker.Config.Labels["com.docker.compose.project"] ===
|
||||
"mtuci-vp7-security" &&
|
||||
worker.Config.Labels["com.docker.compose.service"] === "worker" &&
|
||||
!worker.State.Running,
|
||||
"GAUGE_WORKER_OWNERSHIP_INVALID",
|
||||
);
|
||||
requireThat(
|
||||
Date.parse(worker.State.StartedAt) < point &&
|
||||
point < Date.parse(worker.State.FinishedAt),
|
||||
"GAUGE_WORKER_TIMELINE_MISMATCH",
|
||||
);
|
||||
stage = "STORAGE_ONLY_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), "GAUGE_KEY_INVALID");
|
||||
stage = "STORAGE_AUTHENTICATED_READY";
|
||||
let ready = false;
|
||||
for (const deadline = Date.now() + 60000; 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, "GAUGE_STORAGE_TIMEOUT");
|
||||
const query = async (kind: string, expression: string) => {
|
||||
stage = kind;
|
||||
const response = await openObserveRequest(
|
||||
"/api/default/prometheus/api/v1/query?" +
|
||||
new URLSearchParams({
|
||||
query: expression,
|
||||
time: String(point / 1000),
|
||||
}),
|
||||
{
|
||||
password,
|
||||
account: "query",
|
||||
role: "grafana",
|
||||
kind: "metric_database_observer",
|
||||
},
|
||||
);
|
||||
requireThat(response.status === 200, `GAUGE_HTTP_${response.status}`);
|
||||
const body = response.data as any;
|
||||
requireThat(
|
||||
body.status === "success" && Array.isArray(body.data?.result),
|
||||
"GAUGE_NATIVE_RESULT_INVALID",
|
||||
);
|
||||
return {
|
||||
expression,
|
||||
type: body.data.resultType,
|
||||
series: body.data.result,
|
||||
};
|
||||
};
|
||||
const results = [];
|
||||
for (const metric of ["worker_capacity", "database_observer_up"]) {
|
||||
const aggregate = metric === "worker_capacity" ? "sum" : "min";
|
||||
const raw = await query("RAW_" + metric.toUpperCase(), metric + "[120s]");
|
||||
requireThat(raw.type === "matrix", "GAUGE_RAW_MATRIX_REQUIRED");
|
||||
const series = raw.series.map((item: any) => {
|
||||
requireThat(
|
||||
item.metric && Array.isArray(item.values) && item.values.length > 0,
|
||||
"GAUGE_RAW_SERIES_INVALID",
|
||||
);
|
||||
const last = item.values[item.values.length - 1];
|
||||
const lastTimestamp = Number(last[0]),
|
||||
age = point / 1000 - lastTimestamp;
|
||||
requireThat(
|
||||
Number.isFinite(age) &&
|
||||
age >= 0 &&
|
||||
age <= 120 &&
|
||||
Number.isFinite(Number(last[1])),
|
||||
"GAUGE_RAW_AGE_INVALID",
|
||||
);
|
||||
return {
|
||||
labels: item.metric,
|
||||
samples: item.values,
|
||||
last_timestamp_seconds: lastTimestamp,
|
||||
age_seconds: age,
|
||||
};
|
||||
});
|
||||
const old = await query(
|
||||
"OLD_" + metric.toUpperCase(),
|
||||
`${aggregate}(${metric})`,
|
||||
);
|
||||
const filtered = await query(
|
||||
"FILTERED_" + metric.toUpperCase(),
|
||||
`${aggregate}((${metric} and (timestamp(${metric}) > time()-10)))`,
|
||||
);
|
||||
const absent = await query(
|
||||
"ABSENT_" + metric.toUpperCase(),
|
||||
`${aggregate}((${metric}{service_name="__vp7_absent__"} and (timestamp(${metric}{service_name="__vp7_absent__"}) > time()-10)))`,
|
||||
);
|
||||
results.push({ metric, raw_series: series, old, filtered, absent });
|
||||
}
|
||||
stage = "NATIVE_GAUGE_ORACLE";
|
||||
const values = (result: any) =>
|
||||
result.series.map((r: any) => Number(r.value[1]));
|
||||
requireThat(
|
||||
JSON.stringify(values(results[0].old)) === "[2]" &&
|
||||
JSON.stringify(values(results[1].old)) === "[0]",
|
||||
"GAUGE_OLD_RED_NOT_REPRODUCED",
|
||||
);
|
||||
requireThat(
|
||||
results.every(
|
||||
(r) =>
|
||||
JSON.stringify(values(r.filtered)) === "[1]" &&
|
||||
r.absent.series.length === 0,
|
||||
),
|
||||
"GAUGE_FILTER_NOT_CORRECT",
|
||||
);
|
||||
await lease.verify();
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_NATIVE_FIXED_POINT_GAUGE_PROOF",
|
||||
stage,
|
||||
parent: parentPath,
|
||||
parent_sha256: createHash("sha256").update(parentBytes).digest("hex"),
|
||||
source_sha256: lease.sha256,
|
||||
query_time_milliseconds: point,
|
||||
worker: {
|
||||
id: worker.Id,
|
||||
started_at: worker.State.StartedAt,
|
||||
finished_at: worker.State.FinishedAt,
|
||||
running: worker.State.Running,
|
||||
compose_number:
|
||||
worker.Config.Labels["com.docker.compose.container-number"],
|
||||
},
|
||||
sdk_export_interval_seconds: 2,
|
||||
sdk_export_timeout_seconds: 1,
|
||||
freshness_seconds: 10,
|
||||
results,
|
||||
producer_started: false,
|
||||
native_bao: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_NATIVE_FIXED_POINT_GAUGE_PROOF");
|
||||
} catch (error) {
|
||||
primary = error;
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(() =>
|
||||
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 stopped = await Promise.allSettled([
|
||||
compose(["stop", "openobserve", "openobserve-gateway"], {
|
||||
allowFailure: true,
|
||||
}),
|
||||
]);
|
||||
const code =
|
||||
stopped[0].status === "fulfilled" ? stopped[0].value.code : null;
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(async () => {
|
||||
const saved = JSON.parse(await readFile(receipt, "utf8"));
|
||||
saved.stop_exit = code;
|
||||
await writeFile(receipt, JSON.stringify(saved, null, 2) + "\n");
|
||||
}),
|
||||
]);
|
||||
if (code !== 0 && !primary) throw new Error("GAUGE_STOP_FAILED");
|
||||
}
|
||||
console.log("GAUGE_RECEIPT " + receipt);
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { publicGrafanaEndpoint, metricFrameValues } from "../scripts/grafana";
|
||||
import {
|
||||
assertOriginalGrafanaRules,
|
||||
isOwnHistoryWrite,
|
||||
} from "../scripts/grafana";
|
||||
const endpoint = () => ({
|
||||
Config: {
|
||||
Labels: {
|
||||
"com.docker.compose.project": "mtuci-vp7-security",
|
||||
"com.docker.compose.service": "grafana-gateway",
|
||||
},
|
||||
},
|
||||
State: { Running: true },
|
||||
NetworkSettings: {
|
||||
Networks: { private: {}, edge: {} },
|
||||
Ports: { "3443/tcp": [{ HostIp: "127.0.0.1", HostPort: "18447" }] },
|
||||
},
|
||||
});
|
||||
test("Grafana endpoint uses the verified published loopback binding despite two networks", () => {
|
||||
expect(publicGrafanaEndpoint(endpoint())).toEqual({
|
||||
host: "127.0.0.1",
|
||||
port: 18447,
|
||||
});
|
||||
});
|
||||
test("Grafana endpoint rejects foreign, stopped, wildcard, missing and ambiguous bindings", () => {
|
||||
for (const change of [
|
||||
(x: any) => (x.Config.Labels["com.docker.compose.project"] = "foreign"),
|
||||
(x: any) => (x.Config.Labels["com.docker.compose.service"] = "lb"),
|
||||
(x: any) => (x.State.Running = false),
|
||||
(x: any) => (x.NetworkSettings.Ports = null),
|
||||
(x: any) =>
|
||||
x.NetworkSettings.Ports["3443/tcp"].push({
|
||||
HostIp: "127.0.0.1",
|
||||
HostPort: "18447",
|
||||
}),
|
||||
(x: any) => (x.NetworkSettings.Ports["3443/tcp"][0].HostIp = "0.0.0.0"),
|
||||
(x: any) => (x.NetworkSettings.Ports["3443/tcp"][0].HostPort = "65536"),
|
||||
]) {
|
||||
const x = endpoint();
|
||||
change(x);
|
||||
expect(() => publicGrafanaEndpoint(x)).toThrow();
|
||||
}
|
||||
});
|
||||
const frames = (value: any) => ({
|
||||
results: {
|
||||
A: {
|
||||
status: 200,
|
||||
frames: [
|
||||
{
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "Time", type: "time" },
|
||||
{ name: "Value", type: "number" },
|
||||
],
|
||||
},
|
||||
data: { values: [[123], [value]] },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
test("real numeric zero is a valid metric sample", () => {
|
||||
expect(metricFrameValues(frames(0))).toEqual([0]);
|
||||
});
|
||||
test("HTTP200 with datasource error, empty, null, nonfinite or ragged values cannot pass", () => {
|
||||
for (const sample of [
|
||||
frames(null),
|
||||
frames(NaN),
|
||||
frames(Infinity),
|
||||
frames("0"),
|
||||
{ results: { A: { status: 200, error: "query failed", frames: [] } } },
|
||||
{ results: { A: { status: 200, frames: [] } } },
|
||||
{ results: { A: { status: 500, frames: frames(1).results.A.frames } } },
|
||||
{
|
||||
results: {
|
||||
A: {
|
||||
status: 200,
|
||||
frames: [
|
||||
{
|
||||
schema: { fields: [{ type: "number" }] },
|
||||
data: { values: [[]] },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
])
|
||||
expect(() => metricFrameValues(sample)).toThrow();
|
||||
});
|
||||
|
||||
test("native history first creation binds exact collection and user key", () => {
|
||||
const collection =
|
||||
"/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage";
|
||||
const name = "grafana-page-history:fg4fpuerxx79cb";
|
||||
expect(
|
||||
isOwnHistoryWrite("POST", collection + "/", { metadata: { name } }, name),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isOwnHistoryWrite(
|
||||
"POST",
|
||||
collection + "/foreign",
|
||||
{ metadata: { name } },
|
||||
name,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
test("existing native history uses versioned PATCH at the same owned key", () => {
|
||||
const collection =
|
||||
"/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage",
|
||||
name = "grafana-page-history:fg4fpuerxx79cb";
|
||||
const body = {
|
||||
metadata: { resourceVersion: "123" },
|
||||
spec: { data: { history: "fixture" } },
|
||||
};
|
||||
expect(isOwnHistoryWrite("PATCH", collection + "/" + name, body, name)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
isOwnHistoryWrite(
|
||||
"PATCH",
|
||||
collection + "/grafana-page-history:other",
|
||||
body,
|
||||
name,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
test("native Grafana evaluator key reordering does not change a rule", () => {
|
||||
const original: any = {
|
||||
uid: "vp7-server-errors",
|
||||
title: "Error ratio",
|
||||
data: [
|
||||
{ model: { expr: "actual_metric" } },
|
||||
{},
|
||||
{
|
||||
model: { conditions: [{ evaluator: { type: "gt", params: [0.05] } }] },
|
||||
},
|
||||
],
|
||||
};
|
||||
const actual = structuredClone(original);
|
||||
actual.data[2].model.conditions[0].evaluator = { params: [0.05], type: "gt" };
|
||||
expect(() => assertOriginalGrafanaRules([actual], [original])).not.toThrow();
|
||||
actual.data[2].model.conditions[0].evaluator.params = [0.5];
|
||||
expect(() => assertOriginalGrafanaRules([actual], [original])).toThrow(
|
||||
"GRAFANA_INCIDENT_RULE_CHANGED",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import { createServer } from "node:net";
|
||||
import { gzipSync } from "node:zlib";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { root, local, run, requireThat, safeFailure } from "../scripts/runtime";
|
||||
import { containerID } from "../scripts/runtime-inspect";
|
||||
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"RESPONSE_FIXTURE_REMOTE_REQUIRED",
|
||||
);
|
||||
const claim = crypto.randomUUID(),
|
||||
dir = resolve(local, "response-framing-" + claim);
|
||||
await mkdir(dir, { mode: 0o700 });
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/grafana/response-framing-" + claim + ".json",
|
||||
);
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify({ state: "RUNNING", stage: "SOURCE_GUARD" }),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
const sourcePath = resolve(root, "config/openobserve-gateway.cfg"),
|
||||
source = await readFile(sourcePath, "utf8");
|
||||
const info = JSON.parse(
|
||||
(await run(["docker", "inspect", await containerID("openobserve-gateway")]))
|
||||
.out,
|
||||
)[0];
|
||||
requireThat(
|
||||
info.Config.Labels["com.docker.compose.project"] === "mtuci-vp7-security" &&
|
||||
info.Config.Labels["com.docker.compose.service"] ===
|
||||
"openobserve-gateway",
|
||||
"RESPONSE_FIXTURE_IMAGE_OWNER_INVALID",
|
||||
);
|
||||
const cfg = source
|
||||
.replace("bind :5080 ssl", "bind 127.0.0.1:29577 ssl")
|
||||
.replace("bind :5082 ssl", "bind 127.0.0.1:29578 ssl")
|
||||
.replaceAll(
|
||||
"server local 127.0.0.1:15080",
|
||||
"server synthetic 127.0.0.1:29579",
|
||||
);
|
||||
requireThat(
|
||||
cfg !== source &&
|
||||
!cfg.includes("server local") &&
|
||||
cfg.includes("bind 127.0.0.1:29578 ssl"),
|
||||
"RESPONSE_FIXTURE_UPSTREAM_NOT_ISOLATED",
|
||||
);
|
||||
const cfgPath = resolve(dir, "fixture.cfg");
|
||||
await writeFile(cfgPath, cfg, { flag: "wx", mode: 0o600 });
|
||||
const sized = (n: number) => Buffer.from('{"v":"' + "x".repeat(n - 8) + '"}'),
|
||||
small = Buffer.from('{"ok":true}'),
|
||||
cap = 8388608;
|
||||
requireThat(
|
||||
sized(cap).length === cap,
|
||||
"RESPONSE_FIXTURE_BYTE_ORACLE_INVALID",
|
||||
);
|
||||
const cases = [
|
||||
{
|
||||
name: "small",
|
||||
body: small,
|
||||
headers: ["Content-Length: " + small.length],
|
||||
status: 200,
|
||||
},
|
||||
{
|
||||
name: "exact_cap",
|
||||
body: sized(cap),
|
||||
headers: ["Content-Length: " + cap],
|
||||
status: 200,
|
||||
},
|
||||
{
|
||||
name: "cap_plus_one",
|
||||
body: sized(cap + 1),
|
||||
headers: ["Content-Length: " + (cap + 1)],
|
||||
status: 502,
|
||||
},
|
||||
{
|
||||
name: "gzip",
|
||||
body: gzipSync(small),
|
||||
headers: [
|
||||
"Content-Length: " + gzipSync(small).length,
|
||||
"Content-Encoding: gzip",
|
||||
],
|
||||
status: 502,
|
||||
},
|
||||
{
|
||||
name: "identity_encoding",
|
||||
body: small,
|
||||
headers: [
|
||||
"Content-Length: " + small.length,
|
||||
"Content-Encoding: identity",
|
||||
],
|
||||
status: 502,
|
||||
},
|
||||
{
|
||||
name: "chunked",
|
||||
body: Buffer.from(
|
||||
small.length.toString(16) + "\r\n" + small + "\r\n0\r\n\r\n",
|
||||
),
|
||||
headers: ["Transfer-Encoding: chunked"],
|
||||
status: 502,
|
||||
},
|
||||
{ name: "eof", body: small, headers: [], status: 502 },
|
||||
{
|
||||
name: "duplicate_equal_normalized",
|
||||
body: small,
|
||||
headers: [
|
||||
"Content-Length: " + small.length,
|
||||
"Content-Length: " + small.length,
|
||||
],
|
||||
status: 200,
|
||||
},
|
||||
{
|
||||
name: "leading_zero_normalized",
|
||||
body: small,
|
||||
headers: ["Content-Length: 000" + small.length],
|
||||
status: 200,
|
||||
},
|
||||
];
|
||||
const upstream: { name: string; identity_encoding: boolean }[] = [];
|
||||
const server = createServer((socket) => {
|
||||
let input = "";
|
||||
socket.on("error", () => {});
|
||||
socket.on("data", (data) => {
|
||||
input += data.toString();
|
||||
if (!input.includes("\r\n\r\n")) return;
|
||||
socket.removeAllListeners("data");
|
||||
const name = /fixture=([a-z_]+)/.exec(input)?.[1],
|
||||
c = cases.find((c) => c.name === name) ?? cases[0];
|
||||
upstream.push({
|
||||
name: c.name,
|
||||
identity_encoding: /\r\naccept-encoding:\s*identity\r\n/i.test(input),
|
||||
});
|
||||
socket.end(
|
||||
Buffer.concat([
|
||||
Buffer.from(
|
||||
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/json\r\n" +
|
||||
c.headers.join("\r\n") +
|
||||
"\r\n\r\n",
|
||||
),
|
||||
c.body,
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
await new Promise<void>((ok, fail) => {
|
||||
server.once("error", fail);
|
||||
server.listen(29579, "127.0.0.1", ok);
|
||||
});
|
||||
let id = "",
|
||||
primary: unknown,
|
||||
stop: number | null = null;
|
||||
const results = [];
|
||||
try {
|
||||
const common = [
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--network",
|
||||
"host",
|
||||
"--read-only",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--user",
|
||||
`${process.getuid!()}:${process.getgid!()}`,
|
||||
"--label",
|
||||
"mtuci.vp7.response-claim=" + claim,
|
||||
"--volume",
|
||||
cfgPath + ":/fixture.cfg:ro",
|
||||
"--volume",
|
||||
resolve(local, "pki/openobserve-gateway") + ":/pki:ro",
|
||||
"--entrypoint",
|
||||
"haproxy",
|
||||
];
|
||||
await run([...common, info.Image, "-c", "-f", "/fixture.cfg"]);
|
||||
id = (
|
||||
await run([
|
||||
...common.slice(0, 2),
|
||||
"--detach",
|
||||
...common.slice(2),
|
||||
info.Image,
|
||||
"-W",
|
||||
"-db",
|
||||
"-f",
|
||||
"/fixture.cfg",
|
||||
])
|
||||
).out.trim();
|
||||
requireThat(/^[a-f0-9]{64}$/.test(id), "RESPONSE_FIXTURE_ID_MISSING");
|
||||
const request = async (name: string) => {
|
||||
const path = resolve(dir, name + "-" + crypto.randomUUID() + ".body");
|
||||
await writeFile(path, "", { flag: "wx", mode: 0o600 });
|
||||
const result = await run(
|
||||
[
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--max-time",
|
||||
"10",
|
||||
"--cacert",
|
||||
resolve(local, "pki/grafana/ca.crt"),
|
||||
"--cert",
|
||||
resolve(local, "pki/grafana/cert.pem"),
|
||||
"--key",
|
||||
resolve(local, "pki/grafana/key.pem"),
|
||||
"--resolve",
|
||||
"openobserve-gateway:29578:127.0.0.1",
|
||||
"--header",
|
||||
"Accept-Encoding: gzip",
|
||||
"--output",
|
||||
path,
|
||||
"--write-out",
|
||||
"%{http_code}",
|
||||
"https://openobserve-gateway:29578/api/default/streams?fixture=" +
|
||||
name,
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
return {
|
||||
code: result.code,
|
||||
status: Number(result.out),
|
||||
body: await readFile(path),
|
||||
};
|
||||
};
|
||||
let ready = false;
|
||||
for (let attempt = 0; attempt < 30; attempt++) {
|
||||
const r = await request("small");
|
||||
if (r.status === 200) {
|
||||
ready = true;
|
||||
break;
|
||||
}
|
||||
await Bun.sleep(100);
|
||||
}
|
||||
requireThat(ready, "RESPONSE_FIXTURE_NOT_READY");
|
||||
for (const c of cases) {
|
||||
const response = await request(c.name),
|
||||
marker =
|
||||
response.body.toString() === '{"error":"query_response_boundary"}';
|
||||
const pass =
|
||||
response.code === 0 &&
|
||||
response.status === c.status &&
|
||||
response.body.length <= cap &&
|
||||
(c.status !== 200 || response.body.equals(c.body)) &&
|
||||
upstream
|
||||
.filter((r) => r.name === c.name)
|
||||
.every((r) => r.identity_encoding);
|
||||
results.push({
|
||||
name: c.name,
|
||||
status: response.status,
|
||||
bytes: response.body.length,
|
||||
marker,
|
||||
pass,
|
||||
});
|
||||
}
|
||||
requireThat(
|
||||
(await readFile(sourcePath, "utf8")) === source,
|
||||
"RESPONSE_FIXTURE_SOURCE_CHANGED",
|
||||
);
|
||||
requireThat(
|
||||
results.every((r) => r.pass),
|
||||
"RESPONSE_FRAMING_NATIVE_FAILED",
|
||||
);
|
||||
} catch (error) {
|
||||
primary = error;
|
||||
} finally {
|
||||
try {
|
||||
if (id) {
|
||||
const current = JSON.parse(
|
||||
(await run(["docker", "inspect", id])).out,
|
||||
)[0];
|
||||
requireThat(
|
||||
current.Id === id &&
|
||||
current.Image === info.Image &&
|
||||
current.Config.Labels["mtuci.vp7.response-claim"] === claim,
|
||||
"RESPONSE_FIXTURE_STOP_OWNER_MISMATCH",
|
||||
);
|
||||
stop = (
|
||||
await run(["docker", "stop", "--time", "3", id], {
|
||||
allowFailure: true,
|
||||
})
|
||||
).code;
|
||||
}
|
||||
} catch (error) {
|
||||
primary ??= error;
|
||||
}
|
||||
server.close();
|
||||
try {
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state:
|
||||
!primary && stop === 0
|
||||
? "PASS_NATIVE_MTLS_RESPONSE_FRAMING_8MIB"
|
||||
: "FAILED",
|
||||
config_sha256: createHash("sha256").update(source).digest("hex"),
|
||||
image: info.Image,
|
||||
results,
|
||||
upstream,
|
||||
stop_exit: stop,
|
||||
producer_started: false,
|
||||
native_bao: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
} catch (error) {
|
||||
primary ??= error;
|
||||
}
|
||||
}
|
||||
console.log("RESPONSE_FRAMING_RECEIPT " + receipt);
|
||||
if (primary) throw primary;
|
||||
requireThat(stop === 0, "RESPONSE_FIXTURE_STOP_FAILED");
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { createSecureServer, type ServerHttp2Stream } from "node:http2";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local } from "../scripts/runtime";
|
||||
import { createCA, issue } from "../scripts/pki";
|
||||
import { grpcProbe } from "./grpc-probe";
|
||||
test("native HTTP2 gRPC probe requires a valid Export response and checks request framing", async () => {
|
||||
const scratch = await mkdtemp(resolve(local, "grpc-test-")),
|
||||
role = "grpc-probe-" + crypto.randomUUID(),
|
||||
rolePath = resolve(local, "pki", role),
|
||||
password = "probe-fixture-operator-passphrase";
|
||||
let server: ReturnType<typeof createSecureServer> | undefined;
|
||||
try {
|
||||
await createCA(resolve(scratch, "ca"), password);
|
||||
await issue(
|
||||
resolve(scratch, "ca"),
|
||||
resolve(scratch, "server"),
|
||||
"tempo-gateway",
|
||||
password,
|
||||
);
|
||||
await issue(resolve(scratch, "ca"), rolePath, "collector", password);
|
||||
const [ca, key, cert] = await Promise.all(
|
||||
["ca/ca.crt", "server/key.pem", "server/cert.pem"].map((path) =>
|
||||
readFile(resolve(scratch, path)),
|
||||
),
|
||||
);
|
||||
let bodyOK = false,
|
||||
reject = false;
|
||||
server = createSecureServer({
|
||||
ca,
|
||||
key,
|
||||
cert,
|
||||
requestCert: true,
|
||||
rejectUnauthorized: true,
|
||||
});
|
||||
server.on("stream", (stream, headers) => {
|
||||
const chunks: Buffer[] = [];
|
||||
stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
|
||||
stream.on("end", () => {
|
||||
bodyOK =
|
||||
Buffer.concat(chunks).equals(Buffer.alloc(5)) &&
|
||||
headers[":path"] ===
|
||||
"/opentelemetry.proto.collector.trace.v1.TraceService/Export";
|
||||
(stream as ServerHttp2Stream).respond({
|
||||
":status": 200,
|
||||
"content-type": "application/grpc",
|
||||
"grpc-status": reject ? "7" : "0",
|
||||
});
|
||||
stream.end(Buffer.alloc(5));
|
||||
});
|
||||
});
|
||||
await new Promise<void>((done) => server!.listen(0, "127.0.0.1", done));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string")
|
||||
throw new Error("FIXTURE_NO_TCP_PORT");
|
||||
await grpcProbe("127.0.0.1", address.port, "tempo-gateway", role);
|
||||
expect(bodyOK).toBe(true);
|
||||
reject = true;
|
||||
await expect(
|
||||
grpcProbe("127.0.0.1", address.port, "tempo-gateway", role),
|
||||
).rejects.toThrow("TEMPO_GRPC_EXPORT_NOT_ACCEPTED");
|
||||
} finally {
|
||||
if (server) await new Promise<void>((done) => server!.close(() => done()));
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
await rm(rolePath, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -0,0 +1,84 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { connect } from "node:http2";
|
||||
import { connect as tlsConnect } from "node:tls";
|
||||
import { local, requireThat } from "../scripts/runtime";
|
||||
// Native HTTP/2 performs framing/HPACK/TLS. The protobuf Empty Export request is five zero bytes:
|
||||
// the gRPC identity-compression flag and zero message length, no handwritten protobuf encoder.
|
||||
export async function grpcProbe(
|
||||
ip: string,
|
||||
port: number,
|
||||
hostname: string,
|
||||
role: string,
|
||||
) {
|
||||
const [ca, cert, key] = await Promise.all(
|
||||
["ca.crt", "cert.pem", "key.pem"].map((name) =>
|
||||
readFile(resolve(local, "pki", role, name)),
|
||||
),
|
||||
);
|
||||
return new Promise<void>((done, fail) => {
|
||||
let finished = false;
|
||||
const session = connect(`https://${hostname}:${port}`, {
|
||||
createConnection: () =>
|
||||
tlsConnect({
|
||||
host: ip,
|
||||
port,
|
||||
servername: hostname,
|
||||
ca,
|
||||
cert,
|
||||
key,
|
||||
rejectUnauthorized: true,
|
||||
minVersion: "TLSv1.2",
|
||||
ALPNProtocols: ["h2"],
|
||||
}),
|
||||
});
|
||||
const timer = setTimeout(
|
||||
() => finish(new Error("GRPC_PROBE_TIMEOUT")),
|
||||
4000,
|
||||
);
|
||||
function finish(error?: Error) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
session.destroy();
|
||||
if (error) fail(error);
|
||||
else done();
|
||||
}
|
||||
session.on("error", finish);
|
||||
const request = session.request({
|
||||
":method": "POST",
|
||||
":path": "/opentelemetry.proto.collector.trace.v1.TraceService/Export",
|
||||
"content-type": "application/grpc",
|
||||
te: "trailers",
|
||||
});
|
||||
let status: string | undefined,
|
||||
bytes = 0,
|
||||
httpStatus = 0;
|
||||
request.on("response", (headers) => {
|
||||
httpStatus = Number(headers[":status"]);
|
||||
if (headers["grpc-status"] !== undefined)
|
||||
status = String(headers["grpc-status"]);
|
||||
});
|
||||
request.on("trailers", (headers) => {
|
||||
if (headers["grpc-status"] !== undefined)
|
||||
status = String(headers["grpc-status"]);
|
||||
});
|
||||
request.on("data", (chunk) => {
|
||||
bytes += chunk.length;
|
||||
if (bytes > 1048576) finish(new Error("GRPC_RESPONSE_TOO_LARGE"));
|
||||
});
|
||||
request.on("error", finish);
|
||||
request.on("end", () => {
|
||||
try {
|
||||
requireThat(
|
||||
httpStatus === 200 && status === "0",
|
||||
"TEMPO_GRPC_EXPORT_NOT_ACCEPTED",
|
||||
);
|
||||
finish();
|
||||
} catch (error) {
|
||||
finish(error as Error);
|
||||
}
|
||||
});
|
||||
request.end(Buffer.alloc(5));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import {
|
||||
createHealthConvergence,
|
||||
freshSecretsAfterSeal,
|
||||
} from "../scripts/health-convergence";
|
||||
test("all three native Agent renders must be fresh after seal, including worker", () => {
|
||||
const now = Date.parse("2026-11-16T12:00:00Z"),
|
||||
fresh = new Date(now - 1000).toISOString();
|
||||
expect(
|
||||
freshSecretsAfterSeal([fresh, fresh, fresh], now - 10000, now, 120000),
|
||||
).toBe(true);
|
||||
expect(
|
||||
freshSecretsAfterSeal(
|
||||
[fresh, fresh, new Date(now - 11000).toISOString()],
|
||||
now - 10000,
|
||||
now,
|
||||
120000,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
test.each([
|
||||
"invalid",
|
||||
new Date(1794830400000 + 1).toISOString(),
|
||||
"x".repeat(129),
|
||||
])("malformed, future or oversized render fails closed: %s", (value) => {
|
||||
const now = 1794830400000,
|
||||
fresh = new Date(now - 1000).toISOString();
|
||||
expect(
|
||||
freshSecretsAfterSeal([fresh, fresh, value], now - 10000, now, 120000),
|
||||
).toBe(false);
|
||||
});
|
||||
test("bounded recovery waits for the actual worker render, not only API readiness", async () => {
|
||||
let now = Date.parse("2026-11-16T12:00:00Z");
|
||||
const sealedAt = now - 10000;
|
||||
let reads = 0;
|
||||
const result = await createHealthConvergence(
|
||||
{
|
||||
now: () => now,
|
||||
sleep: async (ms) => {
|
||||
now += ms;
|
||||
},
|
||||
read: async () => {
|
||||
reads++;
|
||||
const fresh = new Date(now - 1000).toISOString(),
|
||||
worker = new Date(
|
||||
reads === 1 ? sealedAt - 1000 : now - 1000,
|
||||
).toISOString();
|
||||
return freshSecretsAfterSeal(
|
||||
[fresh, fresh, worker],
|
||||
sealedAt,
|
||||
now,
|
||||
120000,
|
||||
)
|
||||
? "healthy"
|
||||
: "unhealthy";
|
||||
},
|
||||
},
|
||||
5000,
|
||||
1000,
|
||||
)();
|
||||
expect(result.reads).toBe(2);
|
||||
});
|
||||
function fixture(states: string[]) {
|
||||
let now = 1000,
|
||||
reads = 0;
|
||||
const slept: number[] = [];
|
||||
return {
|
||||
slept,
|
||||
ports: {
|
||||
read: async () => states[Math.min(reads++, states.length - 1)],
|
||||
now: () => now,
|
||||
sleep: async (ms: number) => {
|
||||
slept.push(ms);
|
||||
now += ms;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
test("wait for the next healthy tick after unseal instead of trusting stale unhealthy", async () => {
|
||||
const f = fixture(["unhealthy", "starting", "healthy"]);
|
||||
expect(await createHealthConvergence(f.ports, 5000, 1000)()).toEqual({
|
||||
elapsedMilliseconds: 2000,
|
||||
reads: 3,
|
||||
});
|
||||
expect(f.slept).toEqual([1000, 1000]);
|
||||
});
|
||||
test("healthy container returns immediately without delaying recovery", async () => {
|
||||
const f = fixture(["healthy"]);
|
||||
expect(await createHealthConvergence(f.ports, 5000, 1000)()).toEqual({
|
||||
elapsedMilliseconds: 0,
|
||||
reads: 1,
|
||||
});
|
||||
expect(f.slept).toEqual([]);
|
||||
});
|
||||
test("never healthy fails at the bounded deadline", async () => {
|
||||
const f = fixture(["unhealthy"]);
|
||||
await expect(createHealthConvergence(f.ports, 2000, 1000)()).rejects.toThrow(
|
||||
"BAO_HEALTH_NOT_CONVERGED",
|
||||
);
|
||||
expect(f.slept).toEqual([1000, 1000]);
|
||||
});
|
||||
test("native read failure preserves its original identity", async () => {
|
||||
const f = fixture(["healthy"]),
|
||||
error = Error("FIXTURE_READ");
|
||||
f.ports.read = async () => {
|
||||
throw error;
|
||||
};
|
||||
let actual;
|
||||
try {
|
||||
await createHealthConvergence(f.ports, 5000, 1000)();
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
});
|
||||
test("unknown state fails closed", async () => {
|
||||
const f = fixture(["unknown"]);
|
||||
await expect(createHealthConvergence(f.ports, 5000, 1000)()).rejects.toThrow(
|
||||
"BAO_HEALTH_INVALID",
|
||||
);
|
||||
});
|
||||
test("backward clock is rejected", async () => {
|
||||
const f = fixture(["unhealthy"]);
|
||||
let ticks = 0;
|
||||
f.ports.now = () => (ticks++ === 0 ? 1000 : 999);
|
||||
await expect(createHealthConvergence(f.ports, 5000, 1000)()).rejects.toThrow(
|
||||
"HEALTH_CLOCK_INVALID",
|
||||
);
|
||||
});
|
||||
test("explicit ports are required", () =>
|
||||
expect(() => createHealthConvergence({} as never, 5000, 1000)).toThrow(
|
||||
"HEALTH_PORTS_REQUIRED",
|
||||
));
|
||||
@@ -0,0 +1,55 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { syntheticUserIdentity, assertHTTPStatus } from "./http";
|
||||
const nonce = "01234567-89ab-4cde-8fab-0123456789ab";
|
||||
test("human fixture labels never become invalid API usernames", () => {
|
||||
for (const label of ["grafana-alert", "Grafana QA", "Сервис"]) {
|
||||
const identity = syntheticUserIdentity(label, nonce);
|
||||
expect(identity.username).toMatch(/^[a-z0-9_]{3,32}$/);
|
||||
expect(identity.display_name).toBe(label);
|
||||
}
|
||||
});
|
||||
test("unexpected native HTTP result retains its exact outcome before stable failure", async () => {
|
||||
const saved: any[] = [];
|
||||
await expect(
|
||||
assertHTTPStatus(
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/v1/users",
|
||||
expected: 201,
|
||||
status: 400,
|
||||
content_type: "application/json",
|
||||
body_base64: Buffer.from('{"error":"invalid username"}').toString(
|
||||
"base64",
|
||||
),
|
||||
},
|
||||
async (value) => {
|
||||
saved.push(value);
|
||||
},
|
||||
),
|
||||
).rejects.toThrow("HTTP_POST_201_GOT_400");
|
||||
expect(saved.length).toBe(1);
|
||||
expect(saved[0].status).toBe(400);
|
||||
expect(Buffer.from(saved[0].body_base64, "base64").toString()).toBe(
|
||||
'{"error":"invalid username"}',
|
||||
);
|
||||
});
|
||||
test("diagnostic write failure cannot replace HTTP400", async () => {
|
||||
let writes = 0;
|
||||
await expect(
|
||||
assertHTTPStatus(
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/v1/users",
|
||||
expected: 201,
|
||||
status: 400,
|
||||
content_type: "text/plain",
|
||||
body_base64: "",
|
||||
},
|
||||
async () => {
|
||||
writes++;
|
||||
throw Error("EVIDENCE_IO_FAILED");
|
||||
},
|
||||
),
|
||||
).rejects.toThrow("HTTP_POST_201_GOT_400");
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { readFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local, requireThat } from "../scripts/runtime";
|
||||
export function syntheticUserIdentity(label: string, nonce: string) {
|
||||
return {
|
||||
username: "s7_" + nonce.replaceAll("-", "").slice(0, 24),
|
||||
display_name: label,
|
||||
};
|
||||
}
|
||||
type HTTPOutcome = {
|
||||
method: string;
|
||||
path: string;
|
||||
expected: number;
|
||||
status: number;
|
||||
content_type: string;
|
||||
body_base64: string;
|
||||
};
|
||||
export async function assertHTTPStatus(
|
||||
outcome: HTTPOutcome,
|
||||
retain: (value: HTTPOutcome) => Promise<void>,
|
||||
) {
|
||||
if (outcome.status !== outcome.expected)
|
||||
await Promise.allSettled([Promise.resolve().then(() => retain(outcome))]);
|
||||
requireThat(
|
||||
outcome.status === outcome.expected,
|
||||
"HTTP_" +
|
||||
outcome.method +
|
||||
"_" +
|
||||
outcome.expected +
|
||||
"_GOT_" +
|
||||
outcome.status,
|
||||
);
|
||||
}
|
||||
export class HTTP {
|
||||
readonly base = "https://localhost:18443";
|
||||
async call(
|
||||
method: string,
|
||||
path: string,
|
||||
expected: number,
|
||||
options: {
|
||||
actor?: string;
|
||||
body?: unknown;
|
||||
raw?: Uint8Array;
|
||||
headers?: Record<string, string>;
|
||||
} = {},
|
||||
) {
|
||||
const headers: Record<string, string> = { ...options.headers };
|
||||
if (options.actor) headers.Authorization = "Bearer " + options.actor;
|
||||
let body: string | Uint8Array<ArrayBuffer> | undefined = options.raw
|
||||
? new Uint8Array(options.raw)
|
||||
: undefined;
|
||||
if (options.body !== undefined) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
body = JSON.stringify(options.body);
|
||||
}
|
||||
const response = await fetch(this.base + path, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
redirect: "error",
|
||||
tls: {
|
||||
ca: await readFile(resolve(local, "pki/lb/ca.crt"), "utf8"),
|
||||
rejectUnauthorized: true,
|
||||
},
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
await assertHTTPStatus(
|
||||
{
|
||||
method,
|
||||
path,
|
||||
expected,
|
||||
status: response.status,
|
||||
content_type: response.headers.get("content-type") ?? "",
|
||||
body_base64: Buffer.from(bytes).toString("base64"),
|
||||
},
|
||||
async (outcome) => {
|
||||
const directory = resolve(local, "diagnostics");
|
||||
await mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
await writeFile(
|
||||
resolve(directory, "http-failure-" + crypto.randomUUID() + ".json"),
|
||||
JSON.stringify(outcome),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
},
|
||||
);
|
||||
requireThat(
|
||||
bytes.length <= 16 * 1024 * 1024,
|
||||
"HTTP_TEST_RESPONSE_TOO_LARGE",
|
||||
);
|
||||
let json: any;
|
||||
try {
|
||||
json = bytes.length ? JSON.parse(new TextDecoder().decode(bytes)) : null;
|
||||
} catch {}
|
||||
return { status: response.status, headers: response.headers, bytes, json };
|
||||
}
|
||||
async user(label: string) {
|
||||
const password = "Synthetic-" + crypto.randomUUID(),
|
||||
identity = syntheticUserIdentity(label, crypto.randomUUID()),
|
||||
username = identity.username;
|
||||
const registered = await this.call("POST", "/api/v1/users", 201, {
|
||||
body: { ...identity, password },
|
||||
});
|
||||
const session = await this.call("POST", "/api/v1/auth/sessions", 201, {
|
||||
headers: {
|
||||
Authorization:
|
||||
"Basic " + Buffer.from(username + ":" + password).toString("base64"),
|
||||
},
|
||||
});
|
||||
requireThat(
|
||||
session.json.user.id === registered.json.id,
|
||||
"HTTP_SESSION_ACTOR_MISMATCH",
|
||||
);
|
||||
return {
|
||||
id: registered.json.id,
|
||||
token: session.json.token,
|
||||
password,
|
||||
username,
|
||||
};
|
||||
}
|
||||
async ready(actor: string, id: string, budget = 60_000) {
|
||||
const deadline = Date.now() + budget;
|
||||
while (Date.now() < deadline) {
|
||||
const result = await this.call("GET", "/api/v1/attachments/" + id, 200, {
|
||||
actor,
|
||||
});
|
||||
requireThat(result.json.status !== "failed", "ATTACHMENT_FAILED");
|
||||
if (result.json.status === "ready") return result.json;
|
||||
await Bun.sleep(250);
|
||||
}
|
||||
throw new Error("ATTACHMENT_READY_TIMEOUT");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { parseKV, type Role } from "../scripts/kv-secrets";
|
||||
function fixture(role: Role) {
|
||||
return {
|
||||
status: 200,
|
||||
data: {
|
||||
request_id: "synthetic-request",
|
||||
data: {
|
||||
data: {
|
||||
database_url: `postgresql://${role}@127.0.0.1:15432/messenger?sslmode=disable`,
|
||||
cache_url: `redis://${role}:synthetic-password@127.0.0.1:16379/0`,
|
||||
s3_json: JSON.stringify({
|
||||
Endpoint: "127.0.0.1:19000",
|
||||
Access: "vp7" + role,
|
||||
Secret: "synthetic-s3-secret",
|
||||
Bucket: "messenger-attachments",
|
||||
}),
|
||||
...(role === "worker"
|
||||
? {
|
||||
publisher_url:
|
||||
"redis://publisher:synthetic-password@127.0.0.1:16379/0",
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
metadata: { version: 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
test.each(["api", "worker"] as const)(
|
||||
"reads the native KVv2 envelope for %s",
|
||||
(role) => {
|
||||
const result = parseKV(fixture(role), role);
|
||||
expect(result.version).toBe(1);
|
||||
expect(new URL(result.secrets.database_url).username).toBe(role);
|
||||
},
|
||||
);
|
||||
test("rejects missing KVv2 nesting and required fields", () => {
|
||||
expect(() => parseKV({ status: 200, data: { data: {} } }, "api")).toThrow();
|
||||
const f = fixture("api");
|
||||
delete (f.data.data.data as any).s3_json;
|
||||
expect(() => parseKV(f, "api")).toThrow();
|
||||
});
|
||||
test("rejects credentials for another role", () => {
|
||||
expect(() => parseKV(fixture("worker"), "api")).toThrow("BAO_ROLE_MISMATCH");
|
||||
});
|
||||
test("rejects invalid metadata and denied responses", () => {
|
||||
const f = fixture("api");
|
||||
f.data.data.metadata.version = -1;
|
||||
expect(() => parseKV(f, "api")).toThrow();
|
||||
const denied = fixture("api");
|
||||
denied.status = 403;
|
||||
expect(() => parseKV(denied, "api")).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, requireThat } from "../scripts/runtime";
|
||||
import { containerIP } from "../scripts/runtime-inspect";
|
||||
import { tlsProbe, expectDenied } from "./transport";
|
||||
const http = (path: string) =>
|
||||
`GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n`;
|
||||
export async function auditMatrix(
|
||||
scope: "full" | "cached" | "openobserve" = "full",
|
||||
) {
|
||||
const authorization = async (name: string) => {
|
||||
const value = await readFile(resolve(local, "config", name), "utf8");
|
||||
requireThat(
|
||||
value.length <= 4096 && /^Basic [A-Za-z0-9+/]+={0,2}$/.test(value),
|
||||
"INVALID_OPENOBSERVE_AUTH_HEADER_FILE",
|
||||
);
|
||||
return value;
|
||||
};
|
||||
const ingest =
|
||||
scope !== "cached" ? await authorization("openobserve_ingest_auth") : "";
|
||||
const query =
|
||||
scope !== "cached" ? await authorization("openobserve_query_auth") : "";
|
||||
const cases: {
|
||||
service: string;
|
||||
port: number;
|
||||
role: string;
|
||||
wrong: string;
|
||||
data: string;
|
||||
expected: RegExp;
|
||||
}[] = [
|
||||
{
|
||||
service: "api1-gateway",
|
||||
port: 8443,
|
||||
role: "lb",
|
||||
wrong: "worker",
|
||||
data: http("/health/ready"),
|
||||
expected: /HTTP\/1\.[01] 200/,
|
||||
},
|
||||
{
|
||||
service: "api2-gateway",
|
||||
port: 8443,
|
||||
role: "lb",
|
||||
wrong: "worker",
|
||||
data: http("/health/ready"),
|
||||
expected: /HTTP\/1\.[01] 200/,
|
||||
},
|
||||
{
|
||||
service: "broker-gateway",
|
||||
port: 6379,
|
||||
role: "api",
|
||||
wrong: "lb",
|
||||
data: "*1\r\n$4\r\nPING\r\n",
|
||||
expected: /NOAUTH/,
|
||||
},
|
||||
{
|
||||
service: "collector-gateway",
|
||||
port: 4318,
|
||||
role: "api",
|
||||
wrong: "lb",
|
||||
data: http("/v1/traces"),
|
||||
expected: /HTTP\/1\.[01] (405|404)/,
|
||||
},
|
||||
{
|
||||
service: "collector-gateway",
|
||||
port: 4318,
|
||||
role: "worker",
|
||||
wrong: "forbidden",
|
||||
data: http("/v1/traces"),
|
||||
expected: /HTTP\/1\.[01] (405|404)/,
|
||||
},
|
||||
{
|
||||
service: "s3-gateway",
|
||||
port: 9000,
|
||||
role: "worker",
|
||||
wrong: "lb",
|
||||
data: http("/messenger-attachments"),
|
||||
expected: /HTTP\/1\.[01] 403/,
|
||||
},
|
||||
{
|
||||
service: "openobserve-gateway",
|
||||
port: 5082,
|
||||
role: "grafana",
|
||||
wrong: "worker",
|
||||
data: `GET /api/default/streams HTTP/1.1\r\nHost: localhost\r\nAuthorization: ${query}\r\nConnection: close\r\n\r\n`,
|
||||
expected: /HTTP\/1\.[01] 200/,
|
||||
},
|
||||
{
|
||||
service: "openobserve-gateway",
|
||||
port: 5080,
|
||||
role: "collector",
|
||||
wrong: "grafana",
|
||||
data: `POST /api/default/v1/traces HTTP/1.1\r\nHost: localhost\r\nAuthorization: ${ingest}\r\nContent-Type: application/x-protobuf\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`,
|
||||
expected: /HTTP\/1\.[01] 200/,
|
||||
},
|
||||
];
|
||||
const results = [];
|
||||
for (const c of cases.filter(
|
||||
(c) =>
|
||||
scope === "full" ||
|
||||
(scope === "openobserve"
|
||||
? c.service === "openobserve-gateway"
|
||||
: [
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"broker-gateway",
|
||||
"s3-gateway",
|
||||
].includes(c.service)),
|
||||
)) {
|
||||
const ip = await containerIP(c.service);
|
||||
const positive = async () => {
|
||||
const result = await tlsProbe(ip, c.port, c.service, c.role, c.data);
|
||||
requireThat(
|
||||
result.authorized && c.expected.test(result.data),
|
||||
"MATRIX_POSITIVE_" + c.service.toUpperCase(),
|
||||
);
|
||||
};
|
||||
await positive();
|
||||
const missing = await expectDenied(
|
||||
() => tlsProbe(ip, c.port, c.service, null, c.data),
|
||||
"client",
|
||||
);
|
||||
const foreign = await expectDenied(
|
||||
() => tlsProbe(ip, c.port, c.service, "foreign-lb", c.data),
|
||||
"client",
|
||||
);
|
||||
const identity = await expectDenied(
|
||||
() => tlsProbe(ip, c.port, c.service, c.wrong, c.data),
|
||||
"role",
|
||||
);
|
||||
const wrongName = await expectDenied(
|
||||
() => tlsProbe(ip, c.port, "invalid.example", c.role, c.data),
|
||||
"trust",
|
||||
);
|
||||
const wrongCA = await expectDenied(
|
||||
() => tlsProbe(ip, c.port, c.service, c.role, c.data, "foreign-lb"),
|
||||
"trust",
|
||||
);
|
||||
await positive();
|
||||
results.push({
|
||||
service: c.service,
|
||||
port: c.port,
|
||||
permitted_role: c.role,
|
||||
missing_client: missing,
|
||||
foreign_client: foreign,
|
||||
wrong_role: identity,
|
||||
wrong_hostname: wrongName,
|
||||
foreign_trust: wrongCA,
|
||||
});
|
||||
}
|
||||
await writeFile(
|
||||
resolve(
|
||||
root,
|
||||
scope === "openobserve"
|
||||
? "evidence/openobserve/tls-matrix-" + crypto.randomUUID() + ".json"
|
||||
: scope === "full"
|
||||
? "evidence/security/tls-matrix.json"
|
||||
: "evidence/preflight/tls-matrix.json",
|
||||
),
|
||||
JSON.stringify(
|
||||
{
|
||||
scope,
|
||||
results,
|
||||
positive_controls: "before and after every negative set",
|
||||
timeouts_counted_as_denial: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
scope === "openobserve" ? { flag: "wx" } : {},
|
||||
);
|
||||
console.log(
|
||||
scope === "openobserve"
|
||||
? "PASS_OPENOBSERVE_INGEST_QUERY_MTLS_IDENTITIES_AND_SERVER_TRUST"
|
||||
: scope === "full"
|
||||
? "PASS_ALL_MATRIX_CLIENT_IDENTITIES_AND_SERVER_TRUST"
|
||||
: "PASS_CACHED_CORE_MATRIX_ONLY",
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
createAccountWorkflow,
|
||||
type Account,
|
||||
type Principal,
|
||||
} from "../scripts/openobserve-accounts";
|
||||
const accounts = () => ({
|
||||
ingest: {
|
||||
user: "vp7-ingest@example.invalid",
|
||||
token: "SyntheticIngestToken-123",
|
||||
},
|
||||
query: {
|
||||
user: "vp7-query@example.invalid",
|
||||
token: "SyntheticQueryToken-123",
|
||||
},
|
||||
});
|
||||
function ports(positive = 200, deny = 403) {
|
||||
const events: string[] = [];
|
||||
return {
|
||||
events,
|
||||
positive: async (name: Principal) => {
|
||||
events.push("positive:" + name);
|
||||
return positive;
|
||||
},
|
||||
deny: async (name: Principal) => {
|
||||
events.push("deny:" + name);
|
||||
return deny;
|
||||
},
|
||||
publish: async (_accounts: Record<Principal, Account>) => {
|
||||
events.push("publish");
|
||||
},
|
||||
};
|
||||
}
|
||||
test("saved native200 and403 accounts publish only after both account controls", async () => {
|
||||
const p = ports();
|
||||
await createAccountWorkflow(p)(accounts());
|
||||
expect(p.events).toEqual([
|
||||
"positive:ingest",
|
||||
"deny:ingest",
|
||||
"positive:query",
|
||||
"deny:query",
|
||||
"publish",
|
||||
]);
|
||||
});
|
||||
for (const status of [401, 503, 201])
|
||||
test(`positive HTTP${status} cannot publish derived credentials`, async () => {
|
||||
const p = ports(status);
|
||||
await expect(createAccountWorkflow(p)(accounts())).rejects.toThrow(
|
||||
`OPENOBSERVE_CREDENTIAL_INGEST_POSITIVE_HTTP_${status}`,
|
||||
);
|
||||
expect(p.events).not.toContain("publish");
|
||||
});
|
||||
for (const status of [200, 503])
|
||||
test(`unexpected deny HTTP${status} cannot publish derived credentials`, async () => {
|
||||
const p = ports(200, status);
|
||||
await expect(createAccountWorkflow(p)(accounts())).rejects.toThrow(
|
||||
`OPENOBSERVE_CREDENTIAL_INGEST_DENY_HTTP_${status}`,
|
||||
);
|
||||
expect(p.events).not.toContain("publish");
|
||||
});
|
||||
for (const patch of [
|
||||
{ user: "vp7-owner@example.invalid" },
|
||||
{ user: "foreign@example.invalid" },
|
||||
{ token: "" },
|
||||
{ token: "bad\nvalue" },
|
||||
])
|
||||
test(`invalid saved query shape ${Object.keys(patch)[0]} cannot publish or probe`, async () => {
|
||||
const p = ports(),
|
||||
saved = accounts();
|
||||
saved.query = { ...saved.query, ...patch };
|
||||
await expect(createAccountWorkflow(p)(saved)).rejects.toThrow(
|
||||
"OPENOBSERVE_ACCOUNT_INVALID_RESPONSE",
|
||||
);
|
||||
expect(p.events).toEqual([]);
|
||||
});
|
||||
test("extra owner slot never reaches credential publication", async () => {
|
||||
const p = ports();
|
||||
await expect(
|
||||
createAccountWorkflow(p)({
|
||||
...accounts(),
|
||||
owner: { user: "vp7-owner@example.invalid", token: "owner-slot" },
|
||||
} as any),
|
||||
).rejects.toThrow("OPENOBSERVE_ACCOUNT_SLOTS_INVALID");
|
||||
expect(p.events).toEqual([]);
|
||||
});
|
||||
test("workflow requires explicit native and publishing ports", () => {
|
||||
expect(() =>
|
||||
createAccountWorkflow({ publish: ports().publish } as any),
|
||||
).toThrow("OPENOBSERVE_ACCOUNT_WORKFLOW_PORTS_REQUIRED");
|
||||
});
|
||||
test("invalid query token after a healthy ingest control still cannot publish any derived file", async () => {
|
||||
const p = ports();
|
||||
p.positive = async (name: Principal) => {
|
||||
p.events.push("positive:" + name);
|
||||
return name === "query" ? 401 : 200;
|
||||
};
|
||||
await expect(createAccountWorkflow(p)(accounts())).rejects.toThrow(
|
||||
"OPENOBSERVE_CREDENTIAL_QUERY_POSITIVE_HTTP_401",
|
||||
);
|
||||
expect(p.events).not.toContain("publish");
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { createAccountProvisioner } from "../scripts/openobserve-accounts";
|
||||
const native = {
|
||||
code: 200,
|
||||
user: "vp7-query@example.invalid",
|
||||
token: "SyntheticToken-123456",
|
||||
};
|
||||
test("native service-account success saves exact credential before returning without a human-user API", async () => {
|
||||
const events: string[] = [];
|
||||
const provision = createAccountProvisioner({
|
||||
create: async (path, body) => {
|
||||
events.push(path);
|
||||
expect(body.email).toBe(native.user);
|
||||
return { status: 200, data: native };
|
||||
},
|
||||
save: async (principal, account) => {
|
||||
events.push("saved:" + principal);
|
||||
expect(account).toEqual({ user: native.user, token: native.token });
|
||||
},
|
||||
});
|
||||
expect(await provision("query")).toEqual({
|
||||
user: native.user,
|
||||
token: native.token,
|
||||
});
|
||||
expect(events).toEqual(["/api/default/service_accounts", "saved:query"]);
|
||||
});
|
||||
for (const status of [401, 403, 500])
|
||||
test(`native HTTP${status} never publishes an account`, async () => {
|
||||
let saves = 0;
|
||||
const provision = createAccountProvisioner({
|
||||
create: async () => ({ status, data: native }),
|
||||
save: async () => {
|
||||
saves++;
|
||||
},
|
||||
});
|
||||
await expect(provision("query")).rejects.toThrow(
|
||||
"OPENOBSERVE_ACCOUNT_CREATE_REJECTED",
|
||||
);
|
||||
expect(saves).toBe(0);
|
||||
});
|
||||
for (const patch of [
|
||||
{ code: 403 },
|
||||
{ token: "" },
|
||||
{ token: "x".repeat(4097) },
|
||||
{ user: "foreign@example.invalid" },
|
||||
{ token: null },
|
||||
])
|
||||
test(`invalid native result fails closed ${Object.keys(patch)[0]} ${String(Object.values(patch)[0]).length}`, async () => {
|
||||
let saves = 0;
|
||||
const provision = createAccountProvisioner({
|
||||
create: async () => ({ status: 200, data: { ...native, ...patch } }),
|
||||
save: async () => {
|
||||
saves++;
|
||||
},
|
||||
});
|
||||
await expect(provision("query")).rejects.toThrow(
|
||||
"OPENOBSERVE_ACCOUNT_INVALID_RESPONSE",
|
||||
);
|
||||
expect(saves).toBe(0);
|
||||
});
|
||||
test("account persistence failure stays primary and prevents a success result", async () => {
|
||||
const failure = new Error("FIXTURE_STORAGE_FAILED");
|
||||
const provision = createAccountProvisioner({
|
||||
create: async () => ({ status: 200, data: native }),
|
||||
save: async () => {
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
try {
|
||||
await provision("query");
|
||||
throw new Error("UNEXPECTED_SUCCESS");
|
||||
} catch (error) {
|
||||
expect(error).toBe(failure);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root } from "../scripts/runtime";
|
||||
|
||||
test("Collector uses native file auth and distinct stream-name handling for logs/traces versus metrics", async () => {
|
||||
const config = Bun.YAML.parse(
|
||||
await readFile(resolve(root, "infra/otel/collector.yaml"), "utf8"),
|
||||
) as any;
|
||||
const logs = config.exporters[config.service.pipelines.logs.exporters[0]];
|
||||
const traces = config.exporters[config.service.pipelines.traces.exporters[0]];
|
||||
const metrics =
|
||||
config.exporters[config.service.pipelines.metrics.exporters[0]];
|
||||
expect(logs.headers).toBeDefined();
|
||||
expect(logs.headers["stream-name"]).toBe("messenger");
|
||||
expect(traces.headers["stream-name"]).toBe("messenger");
|
||||
expect(metrics.headers["stream-name"]).toBeUndefined();
|
||||
for (const exporter of [logs, traces, metrics]) {
|
||||
expect(exporter.headers.Authorization).toBe(
|
||||
"${file:/run/secrets/openobserve_ingest_auth}",
|
||||
);
|
||||
expect(exporter.endpoint).toBe("http://127.0.0.1:15080/api/default");
|
||||
expect(exporter.timeout).toBe("2s");
|
||||
expect(exporter.sending_queue.sizer).toBe("bytes");
|
||||
expect(exporter.sending_queue.queue_size).toBe(8388608);
|
||||
}
|
||||
});
|
||||
|
||||
test("Grafana queries measured native metric names without legacy namespace or invented suffixes", async () => {
|
||||
const dashboard = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "infra/grafana/dashboards/messenger.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const expressions = dashboard.panels.flatMap((p: any) =>
|
||||
p.targets.map((t: any) => t.expr),
|
||||
);
|
||||
expect(expressions).toContain("sum(rate(http_requests[1m]))");
|
||||
expect(expressions).toContain(
|
||||
"histogram_quantile(0.95,sum by (le)(rate(http_duration_bucket[1m])))",
|
||||
);
|
||||
expect(
|
||||
expressions.some((expr: string) =>
|
||||
/messenger_|_total|_duration_seconds_bucket/.test(expr),
|
||||
),
|
||||
).toBe(false);
|
||||
for (const name of [
|
||||
"HTTP p50 seconds",
|
||||
"HTTP p99 seconds",
|
||||
"HTTP server error ratio",
|
||||
"Worker busy",
|
||||
"Worker capacity",
|
||||
])
|
||||
expect(dashboard.panels.some((panel: any) => panel.title === name)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("Grafana native plugin provisioning uses measured fields and native Basic auth consumers", async () => {
|
||||
const config = Bun.YAML.parse(
|
||||
await readFile(
|
||||
resolve(root, "infra/grafana/provisioning/datasources/default.yaml"),
|
||||
"utf8",
|
||||
),
|
||||
) as any;
|
||||
const plugin = config.datasources.find((d: any) => d.type === "openobserve");
|
||||
expect(
|
||||
config.datasources.find((d: any) => d.type === "prometheus").jsonData
|
||||
?.httpMethod,
|
||||
).toBe("GET");
|
||||
expect(plugin).toBeDefined();
|
||||
expect(plugin.jsonData.default_log_stream).toBe("messenger");
|
||||
expect(plugin.jsonData.default_trace_stream).toBe("messenger");
|
||||
expect(plugin.jsonData.span_name_field).toBe("operation_name");
|
||||
expect(plugin.jsonData.status_field).toBe("span_status");
|
||||
expect(plugin.basicAuth).toBe(true);
|
||||
expect(plugin.basicAuthUser).toBe("$OO_QUERY_USER");
|
||||
expect(plugin.secureJsonData.basicAuthPassword).toBe("$OO_QUERY_PASSWORD");
|
||||
expect(plugin.jsonData.apiKey).toBeUndefined();
|
||||
});
|
||||
|
||||
test("Grafana mounts native alert rules using the measured datasource and metric names", async () => {
|
||||
const path = resolve(
|
||||
root,
|
||||
"infra/grafana/provisioning/alerting/messenger.yaml",
|
||||
);
|
||||
expect(await Bun.file(path).exists()).toBe(true);
|
||||
const config = Bun.YAML.parse(await readFile(path, "utf8")) as any;
|
||||
expect(config.groups[0].rules.length).toBe(2);
|
||||
for (const rule of config.groups[0].rules) {
|
||||
expect(rule.condition).toBe("C");
|
||||
expect(rule.data[0].datasourceUid).toBe("prometheus");
|
||||
expect(rule.data[0].model.expr).not.toContain("messenger_");
|
||||
expect(rule.isPaused).toBe(false);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
import { readFile, writeFile, mkdir, stat } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
compose,
|
||||
run,
|
||||
requireThat,
|
||||
safeFailure,
|
||||
} from "../scripts/runtime";
|
||||
import { verifyBackendHandover } from "../scripts/preflight-build";
|
||||
import {
|
||||
openObserveRequest,
|
||||
provisionOpenObserve,
|
||||
} from "../scripts/openobserve";
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"OPENOBSERVE_MATH_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/openobserve",
|
||||
"error-ratio-" + 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_MATH_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",
|
||||
);
|
||||
const dashboardBytes = await readFile(
|
||||
resolve(root, "infra/grafana/dashboards/messenger.json"),
|
||||
),
|
||||
ruleBytes = await readFile(
|
||||
resolve(root, "infra/grafana/provisioning/alerting/messenger.yaml"),
|
||||
);
|
||||
const dashboard = JSON.parse(dashboardBytes.toString()),
|
||||
rule = Bun.YAML.parse(ruleBytes.toString()) as any;
|
||||
const expression = dashboard.panels.find(
|
||||
(p: any) => p.title === "HTTP server error ratio",
|
||||
).targets[0].expr;
|
||||
requireThat(
|
||||
expression ===
|
||||
rule.groups[0].rules.find((r: any) => r.uid === "vp7-server-errors")
|
||||
.data[0].model.expr,
|
||||
"ERROR_RATIO_DASHBOARD_RULE_DRIFT",
|
||||
);
|
||||
const errors = 'sum(rate(http_requests{status_class="5xx"}[1m]))',
|
||||
total = "sum(rate(http_requests[1m]))";
|
||||
requireThat(
|
||||
expression.includes(errors) && expression.includes(total),
|
||||
"ERROR_RATIO_FIXTURE_SOURCE_MISMATCH",
|
||||
);
|
||||
const point =
|
||||
(
|
||||
await stat(
|
||||
resolve(
|
||||
root,
|
||||
"evidence/openobserve/pipeline-fc1a31a6-7c89-4e10-98d4-fb127a6e352a.json",
|
||||
),
|
||||
)
|
||||
).mtimeMs - 5000;
|
||||
const accountPaths = ["ingest", "query"].map((name) =>
|
||||
resolve(root, ".local/operator/openobserve-" + name + ".enc"),
|
||||
);
|
||||
const accountHashes = await Promise.all(
|
||||
accountPaths.map(async (path) =>
|
||||
createHash("sha256")
|
||||
.update(await readFile(path))
|
||||
.digest("hex"),
|
||||
),
|
||||
);
|
||||
stage = "STORAGE_ONLY_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 = "STORAGE_QUERY_READY";
|
||||
let ready = false;
|
||||
const deadline = Date.now() + 60000;
|
||||
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_MATH_STORAGE_TIMEOUT");
|
||||
stage = "VERIFY_EXISTING_SAVED_ACCOUNTS";
|
||||
const credentialControls = await provisionOpenObserve(password);
|
||||
for (let index = 0; index < accountPaths.length; index++)
|
||||
requireThat(
|
||||
createHash("sha256")
|
||||
.update(await readFile(accountPaths[index]))
|
||||
.digest("hex") === accountHashes[index],
|
||||
"OPENOBSERVE_EXISTING_ACCOUNT_CHANGED",
|
||||
);
|
||||
const query = async (kind: string, expr: string) => {
|
||||
stage = kind;
|
||||
const result = await openObserveRequest(
|
||||
"/api/default/prometheus/api/v1/query?" +
|
||||
new URLSearchParams({ query: expr, time: String(point / 1000) }),
|
||||
{
|
||||
password,
|
||||
account: "query",
|
||||
role: "grafana",
|
||||
kind: "metric_http_requests",
|
||||
},
|
||||
);
|
||||
requireThat(
|
||||
result.status === 200,
|
||||
`OPENOBSERVE_MATH_HTTP_${result.status}`,
|
||||
);
|
||||
const data = result.data as any;
|
||||
requireThat(
|
||||
data.status === "success" && Array.isArray(data.data?.result),
|
||||
"OPENOBSERVE_MATH_RESULT_INVALID",
|
||||
);
|
||||
return data.data.result.map((r: any) => Number(r.value?.[1])) as number[];
|
||||
};
|
||||
const successful = await query(
|
||||
"PRECONDITION_PRESENT_2XX",
|
||||
'sum(http_requests{status_class="2xx"})',
|
||||
);
|
||||
requireThat(
|
||||
successful.length > 0 &&
|
||||
successful.every((v) => Number.isFinite(v) && v > 0),
|
||||
"ERROR_RATIO_2XX_PRECONDITION_MISSING",
|
||||
);
|
||||
const missing = await query("PRECONDITION_ABSENT_5XX", errors);
|
||||
requireThat(missing.length === 0, "ERROR_RATIO_5XX_PRECONDITION_PRESENT");
|
||||
const healthy = await query("MATH_HEALTHY_EMPTY_ERRORS", expression),
|
||||
positive = await query(
|
||||
"MATH_PRESENT_ERROR_POSITIVE",
|
||||
expression.replace(errors, "vector(2)").replace(total, "vector(10)"),
|
||||
),
|
||||
none = await query(
|
||||
"MATH_ALL_SERIES_ABSENT",
|
||||
expression
|
||||
.replace(
|
||||
errors,
|
||||
'sum(rate(http_requests{status_class="__vp7_missing_errors__"}[1m]))',
|
||||
)
|
||||
.replace(
|
||||
total,
|
||||
'sum(rate(http_requests{status_class="__vp7_missing_all__"}[1m]))',
|
||||
),
|
||||
);
|
||||
const results = [
|
||||
{
|
||||
case: "present2xx_absent5xx",
|
||||
values: healthy,
|
||||
pass: healthy.length === 1 && healthy[0] === 0,
|
||||
},
|
||||
{
|
||||
case: "present_errors2_total10",
|
||||
values: positive,
|
||||
pass: positive.length === 1 && Math.abs(positive[0] - 0.2) < 1e-12,
|
||||
},
|
||||
{ case: "all_series_absent", values: none, pass: none.length === 0 },
|
||||
];
|
||||
stage = "MATH_POSTGUARD";
|
||||
await lease.verify();
|
||||
const passed = results.every((r) => r.pass);
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: passed
|
||||
? "PASS_NATIVE_ERROR_RATIO_MATH"
|
||||
: "FAILED_NATIVE_ERROR_RATIO_MATH",
|
||||
stage,
|
||||
source_handover_sha256: lease.sha256,
|
||||
dashboard_sha256: createHash("sha256")
|
||||
.update(dashboardBytes)
|
||||
.digest("hex"),
|
||||
rule_sha256: createHash("sha256").update(ruleBytes).digest("hex"),
|
||||
query_time_milliseconds: point,
|
||||
successful_2xx: successful,
|
||||
missing_5xx: missing,
|
||||
expression,
|
||||
results,
|
||||
producer_started: false,
|
||||
accounts_created: false,
|
||||
encrypted_accounts_unchanged: true,
|
||||
saved_credential_controls: credentialControls,
|
||||
native_grafana: false,
|
||||
native_bao: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log(JSON.stringify({ native_math_results: results }));
|
||||
requireThat(passed, "OPENOBSERVE_NATIVE_ERROR_RATIO_MATH_FAILED");
|
||||
} catch (error) {
|
||||
primary = error;
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(async () => {
|
||||
const current = JSON.parse(await readFile(receipt, "utf8"));
|
||||
if (current.state === "RUNNING")
|
||||
await 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;
|
||||
await writeFile(receipt, JSON.stringify(saved, null, 2) + "\n");
|
||||
}),
|
||||
]);
|
||||
if (!stopped && !primary) throw new Error("OPENOBSERVE_MATH_STOP_FAILED");
|
||||
console.log(
|
||||
stopped
|
||||
? "OWN_MATH_STORAGE_STOPPED"
|
||||
: "OWN_MATH_STOP_REQUIRES_INSPECTION",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { createSignalAssertions } from "./openobserve-signals";
|
||||
const parent = 1794785761292.7983,
|
||||
traceId = "a".repeat(32);
|
||||
function fixture() {
|
||||
const calls: { kind: string; path: string; body: any }[] = [];
|
||||
const at = BigInt(Math.trunc(parent) - 60000) * 1000000n;
|
||||
const row = (
|
||||
span: string,
|
||||
previous: string,
|
||||
operation: string,
|
||||
service: string,
|
||||
) => ({
|
||||
trace_id: traceId,
|
||||
span_id: span,
|
||||
reference_parent_span_id: previous,
|
||||
operation_name: operation,
|
||||
service_name: service,
|
||||
start_ns: at.toString(),
|
||||
end_ns: (at + 10000n).toString(),
|
||||
duration: 10,
|
||||
_timestamp: Number(at / 1000n),
|
||||
});
|
||||
const request = async (kind: string, path: string, body?: unknown) => {
|
||||
calls.push({ kind, path, body });
|
||||
let data: unknown;
|
||||
if (kind === "trace_streams") data = { list: [{ name: "messenger" }] };
|
||||
else if (kind === "worker_trace") data = { hits: [{ trace_id: traceId }] };
|
||||
else if (kind === "trace_chain")
|
||||
data = {
|
||||
hits: [
|
||||
row("1", "", "POST /api/v1/attachments", "messenger-api"),
|
||||
row("2", "1", "attachment.publish", "messenger-api"),
|
||||
row("3", "2", "attachment.process", "messenger-worker"),
|
||||
],
|
||||
};
|
||||
else if (kind === "correlated_logs")
|
||||
data = {
|
||||
hits: [
|
||||
{ service_name: "messenger-api", request_id: "a".repeat(36) },
|
||||
{ service_name: "messenger-worker" },
|
||||
],
|
||||
};
|
||||
else data = { status: "success", data: { result: [{ value: [1, "1"] }] } };
|
||||
return { status: 200, data };
|
||||
};
|
||||
return { calls, request };
|
||||
}
|
||||
test("reader produces fixed historical SQL end and the same PromQL time after three hours", async () => {
|
||||
const { calls, request } = fixture();
|
||||
const assert = createSignalAssertions({
|
||||
now: () => parent + 3 * 3600000,
|
||||
request,
|
||||
});
|
||||
const end = parent - 5000;
|
||||
await assert(parent - 15 * 60000, end);
|
||||
const searches = calls.filter((call) =>
|
||||
call.path.startsWith("/api/default/_search"),
|
||||
);
|
||||
expect(searches.length).toBe(3);
|
||||
for (const call of searches)
|
||||
expect(call.body.query).toMatchObject({
|
||||
start_time: Math.trunc((parent - 15 * 60000) * 1000),
|
||||
end_time: Math.trunc(end * 1000),
|
||||
});
|
||||
const metrics = calls.filter((call) => call.kind.startsWith("metric_"));
|
||||
expect(metrics.length).toBe(5);
|
||||
for (const call of metrics)
|
||||
expect(new URL("http://fixture" + call.path).searchParams.get("time")).toBe(
|
||||
String(end / 1000),
|
||||
);
|
||||
});
|
||||
test("fresh reader default uses the explicit clock for both native request forms", async () => {
|
||||
const { calls, request } = fixture(),
|
||||
now = Math.trunc(parent) + 1000;
|
||||
await createSignalAssertions({ now: () => now, request })(now - 60000);
|
||||
expect(
|
||||
calls.find((call) => call.kind === "worker_trace")!.body.query.end_time,
|
||||
).toBe(now * 1000);
|
||||
expect(
|
||||
new URL(
|
||||
"http://fixture" +
|
||||
calls.find((call) => call.kind === "metric_http_requests")!.path,
|
||||
).searchParams.get("time"),
|
||||
).toBe(String(now / 1000));
|
||||
});
|
||||
test("reader requires explicit native request and clock ports", () => {
|
||||
expect(() =>
|
||||
createSignalAssertions({ request: fixture().request } as any),
|
||||
).toThrow("OPENOBSERVE_SIGNAL_PORTS_REQUIRED");
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { validateOpenObservePath } from "../scripts/openobserve-request-path";
|
||||
test("native URLSearchParams PromQL spaces stay valid before any credential or process port", () => {
|
||||
const path =
|
||||
"/api/default/prometheus/api/v1/query?" +
|
||||
new URLSearchParams({
|
||||
query: "histogram_quantile(0.95,sum by(le)(http_duration_bucket))",
|
||||
});
|
||||
expect(() => validateOpenObservePath(path)).not.toThrow();
|
||||
});
|
||||
for (const path of [
|
||||
"https://foreign/api/default/streams",
|
||||
"/api/foreign/streams",
|
||||
"/api/default/streams\r\nX: bad",
|
||||
"/api/default/_search#fragment",
|
||||
"/api/default/space in path",
|
||||
])
|
||||
test(`rejects invalid request URI ${JSON.stringify(path)}`, () => {
|
||||
expect(() => validateOpenObservePath(path)).toThrow(
|
||||
"INVALID_OPENOBSERVE_REQUEST_PATH",
|
||||
);
|
||||
});
|
||||
test("pinned plugin organization editor endpoint remains available", () => {
|
||||
expect(() =>
|
||||
validateOpenObservePath("/api/organizations?page_num=0&page_size=1000"),
|
||||
).not.toThrow();
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseOpenObserveResponse } from "../scripts/openobserve-response";
|
||||
for (const status of [401, 422, 500])
|
||||
test(`HTTP${status} text error preserves native HTTP outcome`, () => {
|
||||
expect(parseOpenObserveResponse(status, "Query deserialize error")).toEqual(
|
||||
{ status, data: null },
|
||||
);
|
||||
});
|
||||
test("HTTP200 JSON remains parsed", () => {
|
||||
expect(parseOpenObserveResponse(200, '{"code":200}')).toEqual({
|
||||
status: 200,
|
||||
data: { code: 200 },
|
||||
});
|
||||
});
|
||||
test("HTTP200 malformed success retains the status in its error", () => {
|
||||
expect(() => parseOpenObserveResponse(200, "invalid")).toThrow(
|
||||
"OPENOBSERVE_HTTP_200_INVALID_JSON",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { nativeSearchWindow } from "../scripts/openobserve-search-window";
|
||||
test("actual fractional filesystem mtime serializes native integer microseconds", () => {
|
||||
const mtime = 1794785761292.7983;
|
||||
const value = nativeSearchWindow(mtime - 900000, mtime);
|
||||
expect(value).toEqual({
|
||||
start_time: 1794784861292798,
|
||||
end_time: 1794785761292798,
|
||||
});
|
||||
expect(JSON.parse(JSON.stringify(value))).toEqual(value);
|
||||
});
|
||||
for (const [start, end] of [
|
||||
[NaN, 1],
|
||||
[1, Infinity],
|
||||
[-1, 100],
|
||||
[1, Number.MAX_VALUE],
|
||||
[10, 1],
|
||||
[1, 1],
|
||||
[1, 3600002],
|
||||
])
|
||||
test(`invalid search window ${String(start)} ${String(end)} fails before a native call`, () => {
|
||||
expect(() => nativeSearchWindow(start, end)).toThrow(
|
||||
"INVALID_OPENOBSERVE_SEARCH_WINDOW",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { openObserveRequest } from "../scripts/openobserve";
|
||||
import { requireThat } from "../scripts/runtime";
|
||||
import { nativeSearchWindow } from "../scripts/openobserve-search-window";
|
||||
type Kind = NonNullable<Parameters<typeof openObserveRequest>[1]["kind"]>;
|
||||
export interface SignalPorts {
|
||||
now: () => number;
|
||||
request: (
|
||||
kind: Kind,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
) => Promise<{ status: number; data: unknown }>;
|
||||
}
|
||||
export function createSignalAssertions(ports: SignalPorts) {
|
||||
if (
|
||||
!ports ||
|
||||
typeof ports.now !== "function" ||
|
||||
typeof ports.request !== "function"
|
||||
)
|
||||
throw new Error("OPENOBSERVE_SIGNAL_PORTS_REQUIRED");
|
||||
const { now, request: send } = ports;
|
||||
return async (startMilliseconds: number, queryTimeMilliseconds = now()) => {
|
||||
const request = async (kind: Kind, path: string, body?: unknown) => {
|
||||
const r = await send(kind, path, body);
|
||||
requireThat(
|
||||
r.status === 200,
|
||||
`OPENOBSERVE_${kind.toUpperCase()}_HTTP_${r.status}`,
|
||||
);
|
||||
return r.data as any;
|
||||
};
|
||||
const streams = await request(
|
||||
"trace_streams",
|
||||
"/api/default/streams?type=traces",
|
||||
);
|
||||
requireThat(
|
||||
Array.isArray(streams.list) &&
|
||||
streams.list.some((s: any) => s.name === "messenger"),
|
||||
"OPENOBSERVE_TRACE_STREAM_MISSING",
|
||||
);
|
||||
const search = (kind: Kind, type: string, sql: string) =>
|
||||
request(kind, "/api/default/_search?type=" + type, {
|
||||
query: {
|
||||
sql,
|
||||
...nativeSearchWindow(startMilliseconds, queryTimeMilliseconds),
|
||||
from: 0,
|
||||
size: 100,
|
||||
},
|
||||
});
|
||||
const worker = await search(
|
||||
"worker_trace",
|
||||
"traces",
|
||||
`SELECT trace_id FROM "messenger" WHERE operation_name='attachment.process' ORDER BY _timestamp DESC LIMIT 1`,
|
||||
);
|
||||
const traceId = worker.hits?.[0]?.trace_id;
|
||||
requireThat(
|
||||
/^[a-f0-9]{32}$/.test(traceId ?? ""),
|
||||
"OPENOBSERVE_WORKER_TRACE_MISSING",
|
||||
);
|
||||
const trace = await search(
|
||||
"trace_chain",
|
||||
"traces",
|
||||
`SELECT trace_id,span_id,reference_parent_span_id,operation_name,service_name,CAST(start_time AS VARCHAR) AS start_ns,CAST(end_time AS VARCHAR) AS end_ns,duration,_timestamp FROM "messenger" WHERE trace_id='${traceId}' ORDER BY start_time LIMIT 100`,
|
||||
);
|
||||
const rows = trace.hits ?? [];
|
||||
requireThat(
|
||||
rows.length > 0 && rows.length <= 100,
|
||||
"OPENOBSERVE_TRACE_ROWS_INVALID",
|
||||
);
|
||||
for (const operation of ["attachment.publish", "attachment.process"])
|
||||
requireThat(
|
||||
rows.some((r: any) => r.operation_name === operation),
|
||||
"OPENOBSERVE_CROSS_PROCESS_OPERATION_MISSING",
|
||||
);
|
||||
requireThat(
|
||||
rows.some(
|
||||
(r: any) =>
|
||||
r.service_name === "messenger-api" &&
|
||||
r.operation_name.startsWith("POST "),
|
||||
),
|
||||
"OPENOBSERVE_API_TRACE_MISSING",
|
||||
);
|
||||
const spans = new Set(rows.map((r: any) => r.span_id)),
|
||||
parents = rows.filter(
|
||||
(r: any) =>
|
||||
r.reference_parent_span_id && spans.has(r.reference_parent_span_id),
|
||||
);
|
||||
requireThat(parents.length >= 2, "OPENOBSERVE_PARENT_CHAIN_MISSING");
|
||||
for (const r of rows) {
|
||||
requireThat(
|
||||
/^\d{18,20}$/.test(r.start_ns) && /^\d{18,20}$/.test(r.end_ns),
|
||||
"OPENOBSERVE_NATIVE_NS_INVALID",
|
||||
);
|
||||
const ns = BigInt(r.end_ns) - BigInt(r.start_ns);
|
||||
requireThat(
|
||||
ns >= 0n && Math.abs(Number(ns) / 1000 - Number(r.duration)) <= 1.01,
|
||||
"OPENOBSERVE_DURATION_UNITS_INVALID",
|
||||
);
|
||||
requireThat(
|
||||
Math.abs(Number(BigInt(r.start_ns) / 1000n) - Number(r._timestamp)) <=
|
||||
1,
|
||||
"OPENOBSERVE_TIMESTAMP_UNITS_INVALID",
|
||||
);
|
||||
}
|
||||
requireThat(
|
||||
rows.some((r: any) => Number(r.duration) > 0),
|
||||
"OPENOBSERVE_TRACE_ZERO_DURATION",
|
||||
);
|
||||
const logs = await search(
|
||||
"correlated_logs",
|
||||
"logs",
|
||||
`SELECT trace_id,span_id,event,service_name,request_id FROM "messenger" WHERE trace_id='${traceId}' LIMIT 100`,
|
||||
);
|
||||
for (const service of ["messenger-api", "messenger-worker"])
|
||||
requireThat(
|
||||
logs.hits?.some((l: any) => l.service_name === service),
|
||||
"OPENOBSERVE_CORRELATED_LOGS_MISSING",
|
||||
);
|
||||
requireThat(
|
||||
logs.hits.some((l: any) => /^[a-f0-9-]{36}$/.test(l.request_id ?? "")),
|
||||
"OPENOBSERVE_REQUEST_ID_LOG_MISSING",
|
||||
);
|
||||
const metrics = [];
|
||||
for (const [kind, query] of [
|
||||
["metric_http_requests", "sum(http_requests)"],
|
||||
["metric_jobs_processed", "sum(jobs_processed)"],
|
||||
[
|
||||
"metric_http_p95",
|
||||
"histogram_quantile(0.95,sum by(le)(http_duration_bucket))",
|
||||
],
|
||||
["metric_queue_depth", "max(queue_depth)"],
|
||||
["metric_database_observer", "max(database_observer_up)"],
|
||||
] as const) {
|
||||
const data = await request(
|
||||
kind,
|
||||
"/api/default/prometheus/api/v1/query?" +
|
||||
new URLSearchParams({
|
||||
query,
|
||||
time: String(queryTimeMilliseconds / 1000),
|
||||
}),
|
||||
);
|
||||
requireThat(
|
||||
data.status === "success" && data.data?.result?.length > 0,
|
||||
"OPENOBSERVE_NATIVE_METRIC_MISSING",
|
||||
);
|
||||
const values = data.data.result.map((r: any) => Number(r.value?.[1]));
|
||||
requireThat(
|
||||
values.every(Number.isFinite),
|
||||
"OPENOBSERVE_NATIVE_METRIC_NONFINITE",
|
||||
);
|
||||
metrics.push({ query, values });
|
||||
}
|
||||
return {
|
||||
trace_id: traceId,
|
||||
span_count: rows.length,
|
||||
parent_relations: parents.length,
|
||||
correlated_logs: logs.hits.length,
|
||||
metrics,
|
||||
time_units: {
|
||||
start_time: "nanoseconds",
|
||||
end_time: "nanoseconds",
|
||||
duration: "microseconds",
|
||||
_timestamp: "microseconds",
|
||||
},
|
||||
parent_field: "reference_parent_span_id",
|
||||
native_grafana: false,
|
||||
native_bao: false,
|
||||
};
|
||||
};
|
||||
}
|
||||
export async function assertOpenObserveSignals(
|
||||
password: string,
|
||||
startMilliseconds: number,
|
||||
queryTimeMilliseconds?: number,
|
||||
) {
|
||||
const assert = createSignalAssertions({
|
||||
now: Date.now,
|
||||
request: (kind, path, body) =>
|
||||
openObserveRequest(path, {
|
||||
password,
|
||||
body,
|
||||
account: "query",
|
||||
role: "grafana",
|
||||
kind,
|
||||
}),
|
||||
});
|
||||
return assert(startMilliseconds, queryTimeMilliseconds);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { manifest, gatewayConfigs } from "../scripts/topology";
|
||||
test("telemetry storage is a single OpenObserve instead of Prometheus Loki Tempo and their gateways", () => {
|
||||
const services = manifest().services;
|
||||
expect(services.openobserve).toBeDefined();
|
||||
for (const name of [
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"prometheus-gateway",
|
||||
"loki-gateway",
|
||||
"tempo-gateway",
|
||||
])
|
||||
expect(services[name]).toBeUndefined();
|
||||
});
|
||||
test("OpenObserve has its own persistent data and a closed private gateway namespace", () => {
|
||||
const service = manifest().services.openobserve;
|
||||
expect(service).toBeDefined();
|
||||
expect(service.network_mode).toBe("service:openobserve-gateway");
|
||||
expect(service.ports).toBeUndefined();
|
||||
expect(
|
||||
service.volumes.some(
|
||||
(mount: any) =>
|
||||
mount.source === "./.local/data/openobserve" &&
|
||||
mount.target === "/data" &&
|
||||
!mount.read_only,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
test("storage migration retains required neighbors and existing app OTLP contract without OpenObserve secrets", () => {
|
||||
const services = manifest().services;
|
||||
for (const name of [
|
||||
"api1",
|
||||
"api2",
|
||||
"worker",
|
||||
"postgres",
|
||||
"broker",
|
||||
"s3",
|
||||
"collector",
|
||||
"grafana",
|
||||
"openbao",
|
||||
])
|
||||
expect(services[name]).toBeDefined();
|
||||
for (const name of ["api1", "api2", "worker"]) {
|
||||
expect(services[name].environment.OTEL_EXPORTER_OTLP_ENDPOINT).toBe(
|
||||
"http://127.0.0.1:14318",
|
||||
);
|
||||
expect(
|
||||
JSON.stringify({
|
||||
environment: services[name].environment,
|
||||
volumes: services[name].volumes,
|
||||
})
|
||||
.toLowerCase()
|
||||
.includes("openobserve"),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
test("Collector and Grafana storage transport targets OpenObserve through the verified gateway", () => {
|
||||
const configs = gatewayConfigs();
|
||||
for (const name of ["collector-gateway", "grafana"]) {
|
||||
expect(configs[name]).toContain("openobserve-gateway:");
|
||||
for (const old of [
|
||||
"prometheus-gateway:",
|
||||
"loki-gateway:",
|
||||
"tempo-gateway:",
|
||||
])
|
||||
expect(configs[name]).not.toContain(old);
|
||||
}
|
||||
});
|
||||
test("Grafana query gateway permits actual editor metadata and guards native request fields", () => {
|
||||
const query = gatewayConfigs()["openobserve-gateway"];
|
||||
for (const path of [
|
||||
"/api/organizations",
|
||||
"/api/default/messenger/_values",
|
||||
"/api/default/streams/",
|
||||
])
|
||||
expect(query).toContain(path);
|
||||
expect(query).toContain("req.body_len gt 65536");
|
||||
expect(query).toContain("acl duplicate_query query,url_dec");
|
||||
expect(query).toContain("var(txn.window_s) -m int 1:3599");
|
||||
});
|
||||
|
||||
test("Grafana can use an own verified immutable cache alias without changing the canonical image pin", () => {
|
||||
expect(manifest().services.grafana.image).toBe(
|
||||
"${VP7_GRAFANA_IMAGE:-grafana/grafana@sha256:1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e}",
|
||||
);
|
||||
});
|
||||
|
||||
test("Grafana uses its own file-delivered encryption key and secure HTTPS cookies", () => {
|
||||
const service = manifest().services.grafana;
|
||||
expect(service.environment.GF_SECURITY_SECRET_KEY__FILE).toBe(
|
||||
"/run/admin/secret-key",
|
||||
);
|
||||
expect(service.environment.GF_SECURITY_COOKIE_SECURE).toBe("true");
|
||||
expect(
|
||||
service.volumes.some(
|
||||
(mount: any) =>
|
||||
mount.source === "./.local/operator/grafana-secret-key" &&
|
||||
mount.target === "/run/admin/secret-key" &&
|
||||
mount.read_only,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("Grafana cannot fetch extra plugin packages outside the approved cached artifacts", () => {
|
||||
expect(
|
||||
manifest().services.grafana.environment.GF_PLUGINS_PREINSTALL_DISABLED,
|
||||
).toBe("true");
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { connect } from "node:net";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
requireThat,
|
||||
safeFailure,
|
||||
} from "../scripts/runtime";
|
||||
import { verifyBackendHandover } from "../scripts/preflight-build";
|
||||
import { containerIP } from "../scripts/runtime-inspect";
|
||||
import { openObserveRequest } from "../scripts/openobserve";
|
||||
import { tlsProbe } from "./transport";
|
||||
import { auditMatrix } from "./matrix";
|
||||
async function refused(ip: string, port: number) {
|
||||
return new Promise<void>((done, fail) => {
|
||||
const socket = connect({ host: ip, port });
|
||||
const timer = setTimeout(
|
||||
() => finish(new Error("OPENOBSERVE_RAW_PORT_TIMEOUT")),
|
||||
2000,
|
||||
);
|
||||
let settled = false;
|
||||
function finish(error?: Error) {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
error ? fail(error) : done();
|
||||
}
|
||||
socket.on("connect", () =>
|
||||
finish(new Error("OPENOBSERVE_RAW_PORT_EXPOSED")),
|
||||
);
|
||||
socket.on("error", (error: NodeJS.ErrnoException) =>
|
||||
finish(
|
||||
error.code === "ECONNREFUSED"
|
||||
? undefined
|
||||
: new Error("OPENOBSERVE_RAW_PORT_WRONG_FAILURE"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"OPENOBSERVE_TRANSPORT_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/openobserve",
|
||||
"transport-" + 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_TRANSPORT_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 = "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_TRANSPORT_START_TIMEOUT");
|
||||
stage = "BOTH_LISTENER_MTLS_NEGATIVES";
|
||||
await auditMatrix("openobserve");
|
||||
stage = "QUERY_METHOD_PATH_DENIALS";
|
||||
const ip = await containerIP("openobserve-gateway");
|
||||
const authorization = await readFile(
|
||||
resolve(local, "config/openobserve_query_auth"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^Basic [A-Za-z0-9+/]+={0,2}$/.test(authorization),
|
||||
"INVALID_OPENOBSERVE_AUTH_HEADER_FILE",
|
||||
);
|
||||
for (const path of [
|
||||
"/api/default/v1/logs",
|
||||
"/api/default/users",
|
||||
"/api/foreign/_search",
|
||||
]) {
|
||||
const result = await tlsProbe(
|
||||
ip,
|
||||
5082,
|
||||
"openobserve-gateway",
|
||||
"grafana",
|
||||
`POST ${path} HTTP/1.1\r\nHost: localhost\r\nAuthorization: ${authorization}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`,
|
||||
);
|
||||
requireThat(
|
||||
result.authorized && /HTTP\/1\.[01] 403/.test(result.data),
|
||||
"OPENOBSERVE_GRAFANA_PATH_NOT_DENIED",
|
||||
);
|
||||
}
|
||||
stage = "NATIVE_QUERY_ACCOUNT_NONADMIN";
|
||||
const rotate = await openObserveRequest(
|
||||
"/api/default/service_accounts/vp7-query@example.invalid?rotateToken=true",
|
||||
{ password, account: "query", method: "PUT", body: {} },
|
||||
);
|
||||
requireThat(
|
||||
rotate.status === 403,
|
||||
"OPENOBSERVE_QUERY_ACCOUNT_ADMIN_ROTATE_NOT_DENIED",
|
||||
);
|
||||
stage = "RAW_STORAGE_LISTENERS_CLOSED";
|
||||
await refused(ip, 15080);
|
||||
await refused(ip, 5081);
|
||||
stage = "POSITIVE_AFTER_NEGATIVES";
|
||||
requireThat(
|
||||
(
|
||||
await openObserveRequest("/api/default/streams", {
|
||||
password,
|
||||
account: "query",
|
||||
role: "grafana",
|
||||
})
|
||||
).status === 200,
|
||||
"OPENOBSERVE_QUERY_AFTER_NEGATIVE_FAILED",
|
||||
);
|
||||
stage = "SOURCE_POSTGUARD";
|
||||
await lease.verify();
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_SCOPED_OPENOBSERVE_TRANSPORT",
|
||||
stage,
|
||||
source_handover_sha256: lease.sha256,
|
||||
listeners: [5080, 5082],
|
||||
tls_matrix:
|
||||
"separate tls-matrix UUID receipt; positive before/after each negative set",
|
||||
grafana_ingest_admin_foreign_org_denied: true,
|
||||
native_query_account_admin_rotate_http: rotate.status,
|
||||
native_role_read_only: false,
|
||||
raw_ports_refused: [15080, 5081],
|
||||
timeouts_counted_as_denial: false,
|
||||
native_bao: false,
|
||||
native_grafana: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_OPENOBSERVE_NATIVE_MTLS_SCOPE_AND_CLOSED_RAW_LISTENERS");
|
||||
} 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_TRANSPORT_STOP_FAILED");
|
||||
console.log(
|
||||
stopped
|
||||
? "OWN_TRANSPORT_STORAGE_STOPPED"
|
||||
: "OWN_TRANSPORT_STOP_REQUIRES_INSPECTION",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { encrypt, decrypt } from "../scripts/operator-crypto";
|
||||
test("operator envelope authenticates ciphertext and hides plaintext", () => {
|
||||
const password = "operator-only-test-passphrase",
|
||||
secret = {
|
||||
token: "synthetic-token-never-real",
|
||||
shares: ["synthetic-share"],
|
||||
};
|
||||
const first = encrypt(secret, password),
|
||||
second = encrypt(secret, password);
|
||||
expect(first).not.toBe(second);
|
||||
expect(first.includes(secret.token)).toBe(false);
|
||||
expect(decrypt(first, password)).toEqual(secret);
|
||||
expect(() => decrypt(first, "different-operator-password")).toThrow(
|
||||
"OPERATOR_DECRYPTION_FAILED",
|
||||
);
|
||||
const envelope = JSON.parse(first);
|
||||
envelope.data = Buffer.from("tampered").toString("base64");
|
||||
expect(() => decrypt(JSON.stringify(envelope), password)).toThrow(
|
||||
"OPERATOR_DECRYPTION_FAILED",
|
||||
);
|
||||
});
|
||||
test("operator envelope requires a sufficiently long passphrase", () => {
|
||||
expect(() => encrypt({}, "short")).toThrow("OPERATOR_PASSWORD_TOO_SHORT");
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createCA, issue } from "../scripts/pki";
|
||||
import { validateLeaf } from "../scripts/security-guards";
|
||||
import { local } from "../scripts/runtime";
|
||||
test("issued leaf verifies exact SAN, issuer, validity and matching key", async () => {
|
||||
const scratch = await mkdtemp(resolve(local, "pki-case-"));
|
||||
const password = "pki-test-process-only-strong-passphrase";
|
||||
try {
|
||||
await createCA(resolve(scratch, "ca"), password);
|
||||
await issue(
|
||||
resolve(scratch, "ca"),
|
||||
resolve(scratch, "worker"),
|
||||
"worker",
|
||||
password,
|
||||
);
|
||||
await issue(
|
||||
resolve(scratch, "ca"),
|
||||
resolve(scratch, "api"),
|
||||
"api",
|
||||
password,
|
||||
);
|
||||
const read = (f: string) => readFile(resolve(scratch, f), "utf8");
|
||||
const cert = await read("worker/cert.pem"),
|
||||
key = await read("worker/key.pem"),
|
||||
ca = await read("ca/ca.crt");
|
||||
expect(validateLeaf(cert, key, ca, "worker").serial).toBeTruthy();
|
||||
expect(() => validateLeaf(cert, key, ca, "api")).toThrow(
|
||||
"CERTIFICATE_SAN_INVALID",
|
||||
);
|
||||
expect(() => validateLeaf(cert, key, ca, "worker", 0)).toThrow(
|
||||
"CERTIFICATE_LIFETIME_INVALID",
|
||||
);
|
||||
expect(() =>
|
||||
validateLeaf(cert, key, ca, "worker", Date.now() + 31 * 86400_000),
|
||||
).toThrow("CERTIFICATE_LIFETIME_INVALID");
|
||||
expect(() => validateLeaf(cert, awaitKey, ca, "worker")).toThrow();
|
||||
const otherKey = await read("api/key.pem");
|
||||
expect(() => validateLeaf(cert, otherKey, ca, "worker")).toThrow(
|
||||
"CERTIFICATE_KEY_MISMATCH",
|
||||
);
|
||||
await createCA(resolve(scratch, "foreign"), password);
|
||||
const foreign = await read("foreign/ca.crt");
|
||||
expect(() => validateLeaf(cert, key, foreign, "worker")).toThrow(
|
||||
"CERTIFICATE_CA_INVALID",
|
||||
);
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
const awaitKey = "malformed";
|
||||
@@ -0,0 +1,143 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
local,
|
||||
root,
|
||||
run,
|
||||
privateWrite,
|
||||
compose,
|
||||
requireThat,
|
||||
} from "../scripts/runtime";
|
||||
import { containerID, containerIP } from "../scripts/runtime-inspect";
|
||||
import { tlsProbe, expectDenied } from "./transport";
|
||||
import { images } from "../scripts/topology";
|
||||
export async function postgresTransport() {
|
||||
const ip = await containerIP("postgres");
|
||||
const positive = await tlsProbe(ip, 5432, "postgres", "worker", "");
|
||||
requireThat(
|
||||
positive.authorized && positive.protocol?.startsWith("TLSv1."),
|
||||
"PG_TLS_POSITIVE_FAILED",
|
||||
);
|
||||
const wrongName = await expectDenied(
|
||||
() => tlsProbe(ip, 5432, "invalid.example", "worker", ""),
|
||||
"trust",
|
||||
);
|
||||
const badCA = await expectDenied(
|
||||
() => tlsProbe(ip, 5432, "postgres", "worker", "", "foreign-lb"),
|
||||
"trust",
|
||||
);
|
||||
const envFile = resolve(local, "operator", "pg-worker.env");
|
||||
await privateWrite(
|
||||
envFile,
|
||||
`PGHOST=127.0.0.1\nPGPORT=15432\nPGDATABASE=messenger\nPGUSER=worker\nPGSSLMODE=disable\nPGGSSENCMODE=disable\n`,
|
||||
);
|
||||
const gate = await containerID("worker-gateway");
|
||||
const result = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + gate,
|
||||
"--env-file",
|
||||
envFile,
|
||||
"--entrypoint",
|
||||
"psql",
|
||||
images.postgres,
|
||||
"-X",
|
||||
"-A",
|
||||
"-t",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-c",
|
||||
"SELECT json_build_object('role',current_user,'tls',ssl,'protocol',version,'identity',client_dn)::text FROM pg_stat_ssl WHERE pid=pg_backend_pid()",
|
||||
]);
|
||||
const query = JSON.parse(result.out);
|
||||
requireThat(
|
||||
query.role === "worker" &&
|
||||
query.tls === true &&
|
||||
/^TLSv1\.[23]$/.test(query.protocol) &&
|
||||
["CN=worker", "/CN=worker"].includes(query.identity),
|
||||
"PG_REAL_QUERY_NOT_MTLS",
|
||||
);
|
||||
const impersonation = await run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + gate,
|
||||
"--env-file",
|
||||
envFile,
|
||||
"--env",
|
||||
"PGUSER=api",
|
||||
"--entrypoint",
|
||||
"psql",
|
||||
images.postgres,
|
||||
"-X",
|
||||
"-A",
|
||||
"-t",
|
||||
"-c",
|
||||
"SELECT 1",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
requireThat(
|
||||
impersonation.code !== 0 &&
|
||||
/certificate authentication failed/.test(impersonation.err),
|
||||
"PG_CERT_ROLE_IMPERSONATION_NOT_DENIED",
|
||||
);
|
||||
// Assert actual database-side client cert enforcement, not merely a successful TLS handshake.
|
||||
const rejected = await run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + gate,
|
||||
"--env-file",
|
||||
envFile,
|
||||
"--env",
|
||||
"PGHOST=" + ip,
|
||||
"--env",
|
||||
"PGPORT=5432",
|
||||
"--env",
|
||||
"PGSSLMODE=disable",
|
||||
"--entrypoint",
|
||||
"psql",
|
||||
images.postgres,
|
||||
"-X",
|
||||
"-A",
|
||||
"-t",
|
||||
"-c",
|
||||
"SELECT 1",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
requireThat(
|
||||
rejected.code !== 0 && /pg_hba.conf rejects connection/.test(rejected.err),
|
||||
"PG_PLAINTEXT_NOT_DENIED",
|
||||
);
|
||||
const evidence = {
|
||||
service: "PostgreSQL18.6",
|
||||
direct_tls: "HAProxy ALPN postgresql, verifyhost postgres",
|
||||
actual_query: query,
|
||||
wrong_hostname: wrongName,
|
||||
wrong_ca: badCA,
|
||||
plaintext: "pg_hba.conf rejects connection",
|
||||
different_database_role: "certificate authentication failed",
|
||||
};
|
||||
await Bun.write(
|
||||
resolve(root, "evidence/security/postgres-transport.json"),
|
||||
JSON.stringify(evidence, null, 2) + "\n",
|
||||
);
|
||||
console.log("PASS_POSTGRES_REAL_QUERY_MTLS_AND_NEGATIVE_TRUST");
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
local,
|
||||
root,
|
||||
run,
|
||||
privateWrite,
|
||||
requireThat,
|
||||
compose,
|
||||
} from "../scripts/runtime";
|
||||
import { decrypt } from "../scripts/operator-crypto";
|
||||
import { containerID, containerIP } from "../scripts/runtime-inspect";
|
||||
import { tlsProbe } from "./transport";
|
||||
import { images } from "../scripts/topology";
|
||||
function resp(parts: string[]) {
|
||||
return (
|
||||
"*" +
|
||||
parts.length +
|
||||
"\r\n" +
|
||||
parts.map((p) => "$" + Buffer.byteLength(p) + "\r\n" + p + "\r\n").join("")
|
||||
);
|
||||
}
|
||||
export async function auditWorkerPrivileges(password: string) {
|
||||
const secrets = decrypt<any>(
|
||||
await readFile(resolve(local, "operator/services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
const env = resolve(local, "operator/pg-worker.env");
|
||||
await privateWrite(
|
||||
env,
|
||||
`PGHOST=127.0.0.1\nPGPORT=15432\nPGDATABASE=messenger\nPGUSER=worker\nPGSSLMODE=disable\nPGGSSENCMODE=disable\n`,
|
||||
);
|
||||
const namespace = await containerID("worker-gateway");
|
||||
const sql = async (query: string, okay = true) => {
|
||||
const result = await run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + namespace,
|
||||
"--env-file",
|
||||
env,
|
||||
"--entrypoint",
|
||||
"psql",
|
||||
images.postgres,
|
||||
"-X",
|
||||
"-A",
|
||||
"-t",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-c",
|
||||
query,
|
||||
],
|
||||
{ allowFailure: !okay },
|
||||
);
|
||||
if (!okay)
|
||||
requireThat(
|
||||
result.code !== 0 && /permission denied/.test(result.err),
|
||||
"WORKER_SQL_DENIAL_NOT_PERMISSION",
|
||||
);
|
||||
return result;
|
||||
};
|
||||
await sql("SELECT count(*) FROM attachments");
|
||||
await sql("SELECT count(*) FROM attachment_jobs");
|
||||
for (const table of ["users", "sessions", "chats", "messages"])
|
||||
await sql("SELECT * FROM " + table + " LIMIT 1", false);
|
||||
await sql("CREATE TABLE forbidden_worker_schema(id int)", false);
|
||||
await sql("CREATE ROLE forbidden_worker_role LOGIN", false);
|
||||
const workerFile = resolve(local, "rendered/worker/s3.json");
|
||||
const s3 = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + namespace,
|
||||
"--mount",
|
||||
`type=bind,source=${workerFile},target=/run/worker/s3.json,readonly`,
|
||||
"--entrypoint",
|
||||
"/s3-control",
|
||||
"mtuci-vp7-security-app:local",
|
||||
"-action",
|
||||
"prove-worker",
|
||||
"-config",
|
||||
"/run/worker/s3.json",
|
||||
]);
|
||||
requireThat(
|
||||
s3.out.trim() ===
|
||||
"PASS_WORKER_S3_ALLOWED_VARIANT_DENIED_PREFIX_ADMIN_ANONYMOUS",
|
||||
"WORKER_S3_SCOPE_FAILED",
|
||||
);
|
||||
// Authenticate and execute each command in a fresh TLS connection, so queued replies cannot mask an ACL result.
|
||||
const brokerIP = await containerIP("broker-gateway");
|
||||
const broker = async (parts: string[]) => {
|
||||
const input = resp(["AUTH", "worker", secrets.brokerWorker]) + resp(parts);
|
||||
const result = await tlsProbe(
|
||||
brokerIP,
|
||||
6379,
|
||||
"broker-gateway",
|
||||
"worker",
|
||||
input,
|
||||
"operator",
|
||||
(data) => data.split("\r\n").filter(Boolean).length >= 2,
|
||||
);
|
||||
return result.data;
|
||||
};
|
||||
const ping = await broker(["PING"]);
|
||||
requireThat(ping.includes("+PONG"), "WORKER_BROKER_POSITIVE_FAILED");
|
||||
for (const command of [
|
||||
["GET", "forbidden:scope"],
|
||||
["FLUSHALL"],
|
||||
["CONFIG", "GET", "*"],
|
||||
["ACL", "LIST"],
|
||||
]) {
|
||||
const result = await broker(command);
|
||||
requireThat(result.includes("NOPERM"), "WORKER_BROKER_ACL_NOT_DENIED");
|
||||
}
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/worker-privileges.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
database: {
|
||||
allowed: ["attachments", "attachment_jobs"],
|
||||
denied: [
|
||||
"users",
|
||||
"sessions",
|
||||
"chats",
|
||||
"messages",
|
||||
"CREATE TABLE",
|
||||
"CREATE ROLE",
|
||||
],
|
||||
},
|
||||
s3: {
|
||||
variant_put_get: true,
|
||||
forbidden_prefix_denied: true,
|
||||
bucket_admin_denied: true,
|
||||
anonymous_object_denied: true,
|
||||
},
|
||||
broker: {
|
||||
ping: true,
|
||||
forbidden_key_denied: true,
|
||||
flushall_denied: true,
|
||||
config_denied: true,
|
||||
acl_denied: true,
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_COMPROMISED_WORKER_DB_S3_QUEUE_SCOPE");
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { resolve } from "node:path";
|
||||
import { local } from "../scripts/runtime";
|
||||
import { createCA, issue } from "../scripts/pki";
|
||||
// A second independent CA is a negative-test fixture, never mounted into a service.
|
||||
export async function prepareProbePKI(password: string) {
|
||||
const ca = resolve(local, "operator/foreign-ca");
|
||||
await createCA(ca, password);
|
||||
await issue(ca, resolve(local, "pki/foreign-lb"), "lb", password);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { publicLBEndpoint } from "../scripts/public-endpoint";
|
||||
function fixture(port = "18443") {
|
||||
return {
|
||||
Config: {
|
||||
Labels: {
|
||||
"com.docker.compose.project": "mtuci-vp7-security",
|
||||
"com.docker.compose.service": "lb",
|
||||
},
|
||||
},
|
||||
State: { Running: true },
|
||||
NetworkSettings: {
|
||||
Networks: {
|
||||
private: { IPAddress: "172.20.0.2" },
|
||||
edge: { IPAddress: "172.21.0.2" },
|
||||
},
|
||||
Ports: { "8443/tcp": [{ HostIp: "127.0.0.1", HostPort: port }] },
|
||||
},
|
||||
};
|
||||
}
|
||||
test("selects the actual published loopback listener despite two LB networks", () => {
|
||||
expect(publicLBEndpoint(fixture())).toEqual({
|
||||
host: "127.0.0.1",
|
||||
port: 18443,
|
||||
servername: "localhost",
|
||||
});
|
||||
});
|
||||
test("rejects invalid published ports", () => {
|
||||
for (const port of ["0", "65536", "-1", "x", "18443/secret", ""])
|
||||
expect(() => publicLBEndpoint(fixture(port))).toThrow();
|
||||
});
|
||||
test("rejects unpublished, public, stopped and foreign-resource endpoints", () => {
|
||||
for (const modify of [
|
||||
(x: any) => (x.NetworkSettings.Ports = null),
|
||||
(x: any) => (x.NetworkSettings.Ports["8443/tcp"][0].HostIp = "0.0.0.0"),
|
||||
(x: any) => (x.State.Running = false),
|
||||
(x: any) => (x.Config.Labels["com.docker.compose.project"] = "other"),
|
||||
]) {
|
||||
const f = fixture();
|
||||
modify(f);
|
||||
expect(() => publicLBEndpoint(f)).toThrow();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
createReplicaSnapshot,
|
||||
type ReplicaState,
|
||||
} from "../scripts/replica-snapshot";
|
||||
const aliases = [
|
||||
"33333333-3333-4333-8333-333333333333",
|
||||
"44444444-4444-4444-8444-444444444444",
|
||||
];
|
||||
function fixture() {
|
||||
const commands: string[][] = [],
|
||||
reads: Record<string, number> = {};
|
||||
const state = (service: string): ReplicaState => ({
|
||||
id: (service === "api1" ? "a" : "b").repeat(64),
|
||||
running: true,
|
||||
project: "mtuci-vp7-security",
|
||||
service,
|
||||
started: "2026-11-16T11:00:00Z",
|
||||
});
|
||||
return {
|
||||
commands,
|
||||
reads,
|
||||
state,
|
||||
ports: {
|
||||
inspect: async (service: "api1" | "api2") => {
|
||||
reads[service] = (reads[service] ?? 0) + 1;
|
||||
return state(service);
|
||||
},
|
||||
command: async (args: string[]) => {
|
||||
commands.push(args);
|
||||
if (args[1] === "cp") throw Error("DOCKER_CP_TMPFS_NOT_VISIBLE");
|
||||
return aliases[args[2] === "a".repeat(64) ? 0 : 1];
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
test("read each current UUID through exec in the verified immutable container, without filesystem copy", async () => {
|
||||
const f = fixture(),
|
||||
actual = await createReplicaSnapshot(f.ports)();
|
||||
expect(actual.api1).toEqual({ container: "a".repeat(64), alias: aliases[0] });
|
||||
expect(f.commands).toEqual(
|
||||
["a", "b"].map((c) => [
|
||||
"docker",
|
||||
"exec",
|
||||
c.repeat(64),
|
||||
"/bin/cat",
|
||||
"/tmp/messenger-instance-id",
|
||||
]),
|
||||
);
|
||||
});
|
||||
test("reject process restart while reading the alias", async () => {
|
||||
const f = fixture();
|
||||
f.ports.inspect = async (service) => ({
|
||||
...f.state(service),
|
||||
started:
|
||||
++f.reads[service] > 1 ? "2026-11-16T11:01:00Z" : "2026-11-16T11:00:00Z",
|
||||
});
|
||||
f.reads.api1 = 0;
|
||||
await expect(createReplicaSnapshot(f.ports)()).rejects.toThrow(
|
||||
"FAILOVER_REPLICA_CHANGED_DURING_READ",
|
||||
);
|
||||
});
|
||||
test("reject malformed UUID before any stop operation", async () => {
|
||||
const f = fixture();
|
||||
f.ports.command = async () => "not-a-uuid";
|
||||
await expect(createReplicaSnapshot(f.ports)()).rejects.toThrow(
|
||||
"INVALID_REPLICA_ALIAS",
|
||||
);
|
||||
});
|
||||
test("reject foreign ownership before any command", async () => {
|
||||
const f = fixture();
|
||||
f.ports.inspect = async (service) => ({
|
||||
...f.state(service),
|
||||
project: "foreign",
|
||||
});
|
||||
await expect(createReplicaSnapshot(f.ports)()).rejects.toThrow(
|
||||
"FAILOVER_BASELINE_NOT_OWN_RUNNING_REPLICA",
|
||||
);
|
||||
expect(f.commands).toEqual([]);
|
||||
});
|
||||
test("propagate native exec failure without substituting a stale alias", async () => {
|
||||
const f = fixture(),
|
||||
error = Error("FIXTURE_EXEC_FAILURE");
|
||||
f.ports.command = async () => {
|
||||
throw error;
|
||||
};
|
||||
let actual;
|
||||
try {
|
||||
await createReplicaSnapshot(f.ports)();
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
});
|
||||
test("require explicit ports without process defaults", () =>
|
||||
expect(() => createReplicaSnapshot({} as never)).toThrow(
|
||||
"REPLICA_SNAPSHOT_PORTS_REQUIRED",
|
||||
));
|
||||
@@ -0,0 +1,68 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
createRuntimePreparation,
|
||||
type RuntimeMode,
|
||||
} from "../scripts/runtime-preparation";
|
||||
test("canonical runtime invokes its build exactly once", async () => {
|
||||
const calls: string[] = [];
|
||||
await createRuntimePreparation({
|
||||
build: async () => {
|
||||
calls.push("build");
|
||||
},
|
||||
verifyCache: async () => {
|
||||
calls.push("cache");
|
||||
},
|
||||
})("canonical");
|
||||
expect(calls).toEqual(["build"]);
|
||||
});
|
||||
test("checked cache verifies existing runtime without an implicit build", async () => {
|
||||
const calls: string[] = [];
|
||||
await createRuntimePreparation({
|
||||
build: async () => {
|
||||
calls.push("build");
|
||||
},
|
||||
verifyCache: async () => {
|
||||
calls.push("cache");
|
||||
},
|
||||
})("checked-cache");
|
||||
expect(calls).toEqual(["cache"]);
|
||||
});
|
||||
test("failed cache verification preserves its error and never falls back to a build", async () => {
|
||||
const error = new Error("FIXTURE_WRONG_BINARY"),
|
||||
calls: string[] = [];
|
||||
let observed: unknown;
|
||||
try {
|
||||
await createRuntimePreparation({
|
||||
build: async () => {
|
||||
calls.push("build");
|
||||
},
|
||||
verifyCache: async () => {
|
||||
calls.push("cache");
|
||||
throw error;
|
||||
},
|
||||
})("checked-cache");
|
||||
} catch (e) {
|
||||
observed = e;
|
||||
}
|
||||
expect(observed).toBe(error);
|
||||
expect(calls).toEqual(["cache"]);
|
||||
});
|
||||
test("unknown runtime mode fails before either operational port", async () => {
|
||||
const calls: string[] = [];
|
||||
await expect(
|
||||
createRuntimePreparation({
|
||||
build: async () => {
|
||||
calls.push("build");
|
||||
},
|
||||
verifyCache: async () => {
|
||||
calls.push("cache");
|
||||
},
|
||||
})("foreign" as RuntimeMode),
|
||||
).rejects.toThrow("INVALID_RUNTIME_MODE");
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
test("constructor requires both explicit ports", () => {
|
||||
expect(() =>
|
||||
createRuntimePreparation({ build: async () => {} } as never),
|
||||
).toThrow("RUNTIME_PREPARATION_PORTS_REQUIRED");
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import {
|
||||
createSealedShutdown,
|
||||
sealedServices,
|
||||
type SealedService,
|
||||
type SealedPorts,
|
||||
} from "../scripts/sealed-shutdown";
|
||||
function fixture() {
|
||||
let now = 1_000_000,
|
||||
sealed = false;
|
||||
const calls: string[] = [];
|
||||
const ids = Object.fromEntries(
|
||||
sealedServices.map((s, i) => [s, String(i + 1).repeat(64)]),
|
||||
) as Record<SealedService, string>;
|
||||
const fresh = Object.fromEntries(
|
||||
sealedServices.map((s) => [s, new Date(now).toISOString()]),
|
||||
) as Record<SealedService, string>;
|
||||
const events = Object.fromEntries(
|
||||
sealedServices.map((s) => [
|
||||
s,
|
||||
[{ event: "secret_freshness_failed", milliseconds: now }],
|
||||
]),
|
||||
) as Record<SealedService, { event: string; milliseconds: number }[]>;
|
||||
const stopped = { api1: true, api2: true, worker: true };
|
||||
let replaced = false,
|
||||
initialRunning = true,
|
||||
readError: Error | null = null,
|
||||
readDelay = 0;
|
||||
const ports: SealedPorts = {
|
||||
inspect: async (service, id) => ({
|
||||
id: sealed && replaced ? "f".repeat(64) : ids[service],
|
||||
running: sealed ? !stopped[service] : initialRunning,
|
||||
restarts: sealed && stopped[service] ? 1 : 0,
|
||||
}),
|
||||
readFreshness: async (service) => {
|
||||
if (readError) throw readError;
|
||||
now += readDelay;
|
||||
return fresh[service];
|
||||
},
|
||||
readEvents: async (id, since) => {
|
||||
calls.push("events");
|
||||
const service = sealedServices.find((s) => ids[s] === id)!;
|
||||
return events[service];
|
||||
},
|
||||
retainBaseline: async () => {
|
||||
calls.push("retain");
|
||||
},
|
||||
seal: async () => {
|
||||
calls.push("seal");
|
||||
sealed = true;
|
||||
},
|
||||
now: () => now,
|
||||
sleep: async (ms) => {
|
||||
now += ms;
|
||||
},
|
||||
};
|
||||
return {
|
||||
ports,
|
||||
calls,
|
||||
fresh,
|
||||
events,
|
||||
stopped,
|
||||
setReplaced: () => {
|
||||
replaced = true;
|
||||
},
|
||||
setInitialStopped: () => {
|
||||
initialRunning = false;
|
||||
},
|
||||
setReadError: (e: Error) => {
|
||||
readError = e;
|
||||
},
|
||||
setReadDelay: (ms: number) => {
|
||||
readDelay = ms;
|
||||
},
|
||||
run: () =>
|
||||
createSealedShutdown(ports, {
|
||||
maxAgeMilliseconds: 1000,
|
||||
deadlineMilliseconds: 10,
|
||||
pollMilliseconds: 1,
|
||||
})(),
|
||||
};
|
||||
}
|
||||
test("fresh running processes with post-seal cause and exit prove all three shutdowns", async () => {
|
||||
const f = fixture(),
|
||||
r = await f.run();
|
||||
expect(Object.keys(r.observed).sort()).toEqual([...sealedServices].sort());
|
||||
expect(r.observed.worker?.event).toBe("secret_freshness_failed");
|
||||
expect(f.calls.slice(0, 2)).toEqual(["retain", "seal"]);
|
||||
});
|
||||
test("baseline retention failure prevents seal and preserves its original error", async () => {
|
||||
const f = fixture(),
|
||||
error = Error("FIXTURE_BASELINE_WRITE");
|
||||
f.ports.retainBaseline = async () => {
|
||||
throw error;
|
||||
};
|
||||
let actual;
|
||||
try {
|
||||
await f.run();
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
expect(f.calls).not.toContain("seal");
|
||||
});
|
||||
test("recheck baseline freshness after diagnostic retention latency before dispatching seal", async () => {
|
||||
const f = fixture();
|
||||
f.ports.retainBaseline = async () => {
|
||||
await f.ports.sleep(1001);
|
||||
};
|
||||
await expect(f.run()).rejects.toThrow("SEALED_BASELINE_NOT_FRESH");
|
||||
expect(f.calls).not.toContain("seal");
|
||||
});
|
||||
test("unrelated restart without freshness cause cannot pass sealed acceptance", async () => {
|
||||
const f = fixture();
|
||||
f.events.worker = [];
|
||||
await expect(f.run()).rejects.toThrow("SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
||||
});
|
||||
test("old pre-seal events cannot explain a later unrelated restart", async () => {
|
||||
const f = fixture();
|
||||
f.events.worker[0].milliseconds--;
|
||||
await expect(f.run()).rejects.toThrow("SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
||||
});
|
||||
test("future cause events are not accepted", async () => {
|
||||
const f = fixture();
|
||||
f.events.worker[0].milliseconds += 1000;
|
||||
await expect(f.run()).rejects.toThrow("SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
||||
});
|
||||
test("cause event alone does not prove process exit or restart", async () => {
|
||||
const f = fixture();
|
||||
f.stopped.worker = false;
|
||||
await expect(f.run()).rejects.toThrow("SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
||||
});
|
||||
test.each([
|
||||
{ name: "malformed", value: "invalid" },
|
||||
{ name: "future", value: new Date(1_000_001).toISOString() },
|
||||
{ name: "stale", value: new Date(998_999).toISOString() },
|
||||
])("$name baseline freshness fails before seal", async ({ value }) => {
|
||||
const f = fixture();
|
||||
f.fresh.worker = value;
|
||||
await expect(f.run()).rejects.toThrow("SEALED_BASELINE_NOT_FRESH");
|
||||
expect(f.calls).not.toContain("seal");
|
||||
});
|
||||
test("all baseline processes must be running before seal", async () => {
|
||||
const f = fixture();
|
||||
f.setInitialStopped();
|
||||
await expect(f.run()).rejects.toThrow("SEALED_BASELINE_NOT_RUNNING");
|
||||
expect(f.calls).not.toContain("seal");
|
||||
});
|
||||
test("freshness read I/O error preserves its primary identity and never seals", async () => {
|
||||
const f = fixture(),
|
||||
e = new Error("FIXTURE_READ_FAILED");
|
||||
f.setReadError(e);
|
||||
let actual: unknown;
|
||||
try {
|
||||
await f.run();
|
||||
} catch (error) {
|
||||
actual = error;
|
||||
}
|
||||
expect(actual).toBe(e);
|
||||
expect(f.calls).not.toContain("seal");
|
||||
});
|
||||
test("baseline ages are rechecked after reads immediately before sealing", async () => {
|
||||
const f = fixture();
|
||||
f.setReadDelay(400);
|
||||
await expect(f.run()).rejects.toThrow("SEALED_BASELINE_NOT_FRESH");
|
||||
expect(f.calls).not.toContain("seal");
|
||||
});
|
||||
test("a replaced container cannot satisfy the original process baseline", async () => {
|
||||
const f = fixture();
|
||||
f.setReplaced();
|
||||
await expect(f.run()).rejects.toThrow("SEALED_CONTAINER_CHANGED");
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import {
|
||||
validAge,
|
||||
allowedIdentity,
|
||||
requireTLSURL,
|
||||
} from "../scripts/security-guards";
|
||||
test("age rejects future, invalid and stale receipts", () => {
|
||||
for (const age of [-1, NaN, Infinity, 61])
|
||||
expect(() => validAge(age, 60)).toThrow();
|
||||
expect(validAge(0, 60)).toBe(0);
|
||||
expect(validAge(60, 60)).toBe(60);
|
||||
});
|
||||
test("client role requires exact allowlist membership", () => {
|
||||
expect(allowedIdentity("worker", ["api", "worker"])).toBe("worker");
|
||||
for (const role of ["", "worker.admin", "Worker", "lb"])
|
||||
expect(() => allowedIdentity(role, ["api", "worker"])).toThrow();
|
||||
});
|
||||
test("network endpoints require TLS and an exact intended hostname", () => {
|
||||
expect(requireTLSURL("https://openbao:8200", "openbao").hostname).toBe(
|
||||
"openbao",
|
||||
);
|
||||
for (const url of [
|
||||
"http://openbao:8200",
|
||||
"https://else:8200",
|
||||
"https://user:password@openbao:8200",
|
||||
])
|
||||
expect(() => requireTLSURL(url, "openbao")).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
createSharedLoginCase,
|
||||
type LoginObservation,
|
||||
} from "../scripts/shared-login-case";
|
||||
const aliases = {
|
||||
api1: "11111111-1111-4111-8111-111111111111",
|
||||
api2: "22222222-2222-4222-8222-222222222222",
|
||||
};
|
||||
function fixture() {
|
||||
let count = 0,
|
||||
controls = 0,
|
||||
active = 0,
|
||||
maxActive = 0;
|
||||
const responses: LoginObservation[] = [];
|
||||
return {
|
||||
responses,
|
||||
get controls() {
|
||||
return controls;
|
||||
},
|
||||
get maxActive() {
|
||||
return maxActive;
|
||||
},
|
||||
ports: {
|
||||
now: () => 1000,
|
||||
request: async (
|
||||
replica: "api1" | "api2",
|
||||
kind: "main" | "control",
|
||||
): Promise<LoginObservation> => {
|
||||
active++;
|
||||
maxActive = Math.max(maxActive, active);
|
||||
await Promise.resolve();
|
||||
active--;
|
||||
if (kind === "control") {
|
||||
controls++;
|
||||
return {
|
||||
status: 201,
|
||||
alias: aliases[replica],
|
||||
actorCorrect: true,
|
||||
retryAfter: null,
|
||||
errorCode: null,
|
||||
};
|
||||
}
|
||||
const index = count++,
|
||||
result = responses[index] ?? {
|
||||
status: index < 10 ? 201 : 429,
|
||||
alias: aliases[replica],
|
||||
actorCorrect: true,
|
||||
retryAfter: index < 10 ? null : "60",
|
||||
errorCode: index < 10 ? null : "rate_limited",
|
||||
};
|
||||
return result;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
test("twenty requests in concurrent pairs prove one shared ten-attempt window and two other-account controls", async () => {
|
||||
const f = fixture();
|
||||
expect(await createSharedLoginCase(f.ports)(aliases)).toEqual({
|
||||
requests: 20,
|
||||
accepted: 10,
|
||||
denied: 10,
|
||||
controls: 2,
|
||||
elapsedMilliseconds: 0,
|
||||
});
|
||||
expect(f.maxActive).toBe(2);
|
||||
});
|
||||
test.each([
|
||||
{
|
||||
name: "independent limits",
|
||||
patch: { status: 201 },
|
||||
code: "SHARED_LIMIT_NOT_PROVED",
|
||||
index: 10,
|
||||
},
|
||||
{
|
||||
name: "missing retry",
|
||||
patch: { retryAfter: null },
|
||||
code: "LOGIN_RETRY_AFTER_INVALID",
|
||||
index: 10,
|
||||
},
|
||||
{
|
||||
name: "wrong body",
|
||||
patch: { errorCode: "unavailable" },
|
||||
code: "LOGIN_REJECTION_BODY_INVALID",
|
||||
index: 10,
|
||||
},
|
||||
{
|
||||
name: "wrong instance",
|
||||
patch: { alias: aliases.api2 },
|
||||
code: "LOGIN_INSTANCE_MISMATCH",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
name: "wrong actor",
|
||||
patch: { actorCorrect: false },
|
||||
code: "LOGIN_SUCCESS_ACTOR_MISMATCH",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
name: "unexpected overload",
|
||||
patch: { status: 503 },
|
||||
code: "LOGIN_STATUS_UNEXPECTED",
|
||||
index: 0,
|
||||
},
|
||||
])(
|
||||
"reject $name before dependent control requests",
|
||||
async ({ patch, code, index }) => {
|
||||
const f = fixture();
|
||||
f.responses[index] = {
|
||||
status: index < 10 ? 201 : 429,
|
||||
alias: index % 2 === 0 ? aliases.api1 : aliases.api2,
|
||||
actorCorrect: true,
|
||||
retryAfter: index < 10 ? null : "60",
|
||||
errorCode: index < 10 ? null : "rate_limited",
|
||||
...patch,
|
||||
};
|
||||
await expect(createSharedLoginCase(f.ports)(aliases)).rejects.toThrow(code);
|
||||
expect(f.controls).toBe(0);
|
||||
},
|
||||
);
|
||||
test("native failure preserves its original identity", async () => {
|
||||
const f = fixture(),
|
||||
error = Error("FIXTURE_NATIVE_HTTP");
|
||||
f.ports.request = async () => {
|
||||
throw error;
|
||||
};
|
||||
let actual;
|
||||
try {
|
||||
await createSharedLoginCase(f.ports)(aliases);
|
||||
} catch (e) {
|
||||
actual = e;
|
||||
}
|
||||
expect(actual).toBe(error);
|
||||
});
|
||||
test("expired main window cannot count a second rate window", async () => {
|
||||
const f = fixture();
|
||||
let read = 0;
|
||||
f.ports.now = () => (read++ === 0 ? 1000 : 61000);
|
||||
await expect(createSharedLoginCase(f.ports)(aliases)).rejects.toThrow(
|
||||
"LOGIN_CASE_WINDOW_EXPIRED",
|
||||
);
|
||||
});
|
||||
test("failed other-account control rejects", async () => {
|
||||
const f = fixture(),
|
||||
native = f.ports.request;
|
||||
f.ports.request = async (r, k) =>
|
||||
k === "control"
|
||||
? {
|
||||
status: 429,
|
||||
alias: aliases[r],
|
||||
actorCorrect: false,
|
||||
retryAfter: "60",
|
||||
errorCode: "rate_limited",
|
||||
}
|
||||
: native(r, k);
|
||||
await expect(createSharedLoginCase(f.ports)(aliases)).rejects.toThrow(
|
||||
"LOGIN_CONTROL_FAILED",
|
||||
);
|
||||
});
|
||||
test("explicit ports have no process or network fallback", () =>
|
||||
expect(() => createSharedLoginCase({} as never)).toThrow(
|
||||
"LOGIN_CASE_PORTS_REQUIRED",
|
||||
));
|
||||
@@ -0,0 +1,249 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
run,
|
||||
compose,
|
||||
requireThat,
|
||||
privateWrite,
|
||||
} from "../scripts/runtime";
|
||||
import {
|
||||
createSharedLoginCase,
|
||||
type Replica,
|
||||
} from "../scripts/shared-login-case";
|
||||
import { snapshotReplicas } from "../scripts/hooks";
|
||||
import { containerIP } from "../scripts/runtime-inspect";
|
||||
import { encrypt } from "../scripts/operator-crypto";
|
||||
import { HTTP, syntheticUserIdentity } from "./http";
|
||||
|
||||
export async function sharedLoginRuntime(
|
||||
password: string,
|
||||
operationId: string,
|
||||
) {
|
||||
requireThat(/^[a-f0-9-]{36}$/.test(operationId), "LOGIN_OPERATION_INVALID");
|
||||
const directory = resolve(
|
||||
local,
|
||||
"operator",
|
||||
"login-functional-" + operationId,
|
||||
);
|
||||
await mkdir(directory, { mode: 0o700 });
|
||||
const bucket = (username: string) =>
|
||||
createHash("sha256").update(username).digest().readUInt16BE(0) % 4096;
|
||||
const readBucket = async (value: number) =>
|
||||
JSON.parse(
|
||||
(
|
||||
await compose([
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-X",
|
||||
"-A",
|
||||
"-t",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-c",
|
||||
`SELECT json_build_object('bucket',bucket,'attempts',attempts,'expired',started_at<=clock_timestamp()-interval '60 seconds') FROM login_limits WHERE bucket=${value}`,
|
||||
])
|
||||
).out,
|
||||
);
|
||||
const selectIdentity = async (excluded: number | null) => {
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const identity = syntheticUserIdentity(
|
||||
"Bounded shared login",
|
||||
crypto.randomUUID(),
|
||||
),
|
||||
value = bucket(identity.username),
|
||||
state = await readBucket(value);
|
||||
if (
|
||||
value !== excluded &&
|
||||
(state.expired === true || state.attempts === 0)
|
||||
)
|
||||
return {
|
||||
...identity,
|
||||
bucket: value,
|
||||
password: "Functional-" + crypto.randomUUID(),
|
||||
id: "",
|
||||
};
|
||||
}
|
||||
throw Error("LOGIN_UNUSED_BUCKET_UNAVAILABLE");
|
||||
};
|
||||
const main = await selectIdentity(null),
|
||||
control = await selectIdentity(main.bucket),
|
||||
http = new HTTP();
|
||||
const save = () =>
|
||||
privateWrite(
|
||||
resolve(directory, "identities.enc"),
|
||||
encrypt({ main, control }, password),
|
||||
);
|
||||
await save();
|
||||
for (const identity of [main, control]) {
|
||||
const r = await http.call("POST", "/api/v1/users", 201, {
|
||||
body: {
|
||||
username: identity.username,
|
||||
display_name: identity.display_name,
|
||||
password: identity.password,
|
||||
},
|
||||
});
|
||||
requireThat(
|
||||
typeof r.json?.id === "string" && /^[a-f0-9-]{36}$/.test(r.json.id),
|
||||
"LOGIN_REGISTERED_USER_INVALID",
|
||||
);
|
||||
identity.id = r.json.id;
|
||||
await save();
|
||||
}
|
||||
const baseline = await snapshotReplicas(),
|
||||
ips = {
|
||||
api1: await containerIP("api1-gateway"),
|
||||
api2: await containerIP("api2-gateway"),
|
||||
};
|
||||
const headers = {
|
||||
main: resolve(directory, "main.headers"),
|
||||
control: resolve(directory, "control.headers"),
|
||||
};
|
||||
for (const [kind, identity] of [
|
||||
["main", main],
|
||||
["control", control],
|
||||
] as const)
|
||||
await privateWrite(
|
||||
headers[kind],
|
||||
"Authorization: Basic " +
|
||||
Buffer.from(identity.username + ":" + identity.password).toString(
|
||||
"base64",
|
||||
) +
|
||||
"\n",
|
||||
);
|
||||
let counter = 0;
|
||||
const observations: {
|
||||
replica: Replica;
|
||||
status: number;
|
||||
instance: string;
|
||||
retry_after: string | null;
|
||||
}[] = [];
|
||||
const result = await createSharedLoginCase({
|
||||
now: Date.now,
|
||||
request: async (replica, kind) => {
|
||||
const index = counter++,
|
||||
bodyPath = resolve(directory, "response-" + index + ".json"),
|
||||
headerPath = resolve(directory, "response-" + index + ".headers");
|
||||
await privateWrite(bodyPath, "");
|
||||
await privateWrite(headerPath, "");
|
||||
const hostname = replica + "-gateway",
|
||||
response = await run([
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--max-time",
|
||||
"5",
|
||||
"--max-filesize",
|
||||
"65536",
|
||||
"--cacert",
|
||||
resolve(local, "pki/lb/ca.crt"),
|
||||
"--cert",
|
||||
resolve(local, "pki/lb/cert.pem"),
|
||||
"--key",
|
||||
resolve(local, "pki/lb/key.pem"),
|
||||
"--resolve",
|
||||
hostname + ":8443:" + ips[replica],
|
||||
"--header",
|
||||
"@" + headers[kind],
|
||||
"--request",
|
||||
"POST",
|
||||
"--dump-header",
|
||||
headerPath,
|
||||
"--output",
|
||||
bodyPath,
|
||||
"--write-out",
|
||||
"%{http_code}",
|
||||
"https://" + hostname + ":8443/api/v1/auth/sessions",
|
||||
]);
|
||||
requireThat(/^\d{3}$/.test(response.out), "LOGIN_HTTP_STATUS_INVALID");
|
||||
const status = Number(response.out),
|
||||
raw = await readFile(bodyPath),
|
||||
lines = (await readFile(headerPath, "utf8")).split(/\r?\n/);
|
||||
requireThat(raw.length <= 65536, "LOGIN_HTTP_BODY_TOO_LARGE");
|
||||
const get = (name: string) => {
|
||||
const matches = lines.filter((line) =>
|
||||
line.toLowerCase().startsWith(name + ":"),
|
||||
);
|
||||
requireThat(matches.length <= 1, "LOGIN_DUPLICATE_RESPONSE_HEADER");
|
||||
return matches[0]?.slice(name.length + 1).trim() ?? null;
|
||||
};
|
||||
requireThat(
|
||||
get("content-type")?.startsWith("application/json"),
|
||||
"LOGIN_HTTP_CONTENT_TYPE_INVALID",
|
||||
);
|
||||
const body = JSON.parse(raw.toString()),
|
||||
alias = get("x-instance-id") ?? "",
|
||||
retryAfter = get("retry-after"),
|
||||
identity = kind === "main" ? main : control;
|
||||
observations.push({
|
||||
replica,
|
||||
status,
|
||||
instance: alias,
|
||||
retry_after: retryAfter,
|
||||
});
|
||||
return {
|
||||
status,
|
||||
alias,
|
||||
retryAfter,
|
||||
actorCorrect: body.user?.id === identity.id,
|
||||
errorCode:
|
||||
typeof body.error?.code === "string" ? body.error.code : null,
|
||||
};
|
||||
},
|
||||
})({ api1: baseline.api1.alias, api2: baseline.api2.alias });
|
||||
const after = await snapshotReplicas();
|
||||
requireThat(
|
||||
JSON.stringify(after) === JSON.stringify(baseline),
|
||||
"LOGIN_REPLICA_CHANGED",
|
||||
);
|
||||
const persistedMain = await readBucket(main.bucket),
|
||||
persistedControl = await readBucket(control.bucket);
|
||||
requireThat(
|
||||
persistedMain.attempts === 10 &&
|
||||
persistedMain.expired === false &&
|
||||
persistedControl.attempts === 2 &&
|
||||
persistedControl.expired === false,
|
||||
"LOGIN_NATIVE_COUNTER_MISMATCH",
|
||||
);
|
||||
const path = "evidence/security/shared-login-" + operationId + ".json";
|
||||
await writeFile(
|
||||
resolve(root, path),
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_SHARED_HTTP_LOGIN_LIMIT",
|
||||
operation_id: operationId,
|
||||
...result,
|
||||
observations,
|
||||
replicas: baseline,
|
||||
main_bucket: { bucket: main.bucket, attempts: persistedMain.attempts },
|
||||
control_bucket: {
|
||||
bucket: control.bucket,
|
||||
attempts: persistedControl.attempts,
|
||||
},
|
||||
max_inflight: 2,
|
||||
request_budget: 22,
|
||||
full_service_dos_measured: false,
|
||||
kdf_budget_reference: "ARGON-BUDGET.md",
|
||||
credentials:
|
||||
"encrypted private operator capture; response files private",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
console.log(
|
||||
"PASS_SHARED_HTTP_10_OF_20_LIMIT_BOTH_REPLICAS_RETRY_AFTER_AND_CONTROLS",
|
||||
);
|
||||
return path;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { expectDenied } from "./transport";
|
||||
test("native explicit revoked-certificate alert is client denial, while an application success is not", async () => {
|
||||
expect(
|
||||
await expectDenied(
|
||||
() =>
|
||||
Promise.reject(
|
||||
Object.assign(new Error("synthetic revoked certificate"), {
|
||||
code: "ERR_SSL_SSLV3_ALERT_CERTIFICATE_REVOKED",
|
||||
}),
|
||||
),
|
||||
"client",
|
||||
),
|
||||
).toBe("ERR_SSL_SSLV3_ALERT_CERTIFICATE_REVOKED");
|
||||
await expect(
|
||||
expectDenied(
|
||||
async () => ({
|
||||
data: "HTTP/1.1 200 OK",
|
||||
authorized: true,
|
||||
protocol: "TLSv1.3",
|
||||
}),
|
||||
"client",
|
||||
),
|
||||
).rejects.toThrow("NEGATIVE_FAILED_FOR_UNEXPECTED_REASON");
|
||||
});
|
||||
test("Bun native certificate-required alert counts as client denial while timeout never does", async () => {
|
||||
const certificate = () =>
|
||||
Promise.reject(
|
||||
Object.assign(new Error("synthetic native certificate alert"), {
|
||||
code: "ERR_SSL_TLSV1_ALERT_CERTIFICATE_REQUIRED",
|
||||
}),
|
||||
);
|
||||
expect(await expectDenied(certificate, "client")).toBe(
|
||||
"ERR_SSL_TLSV1_ALERT_CERTIFICATE_REQUIRED",
|
||||
);
|
||||
await expect(
|
||||
expectDenied(
|
||||
() =>
|
||||
Promise.reject(
|
||||
Object.assign(new Error("synthetic timeout"), { code: "ETIMEDOUT" }),
|
||||
),
|
||||
"client",
|
||||
),
|
||||
).rejects.toThrow("NEGATIVE_FAILED_FOR_UNEXPECTED_REASON");
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { connect } from "node:tls";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local, requireThat, privateWrite } from "../scripts/runtime";
|
||||
export async function tlsProbe(
|
||||
ip: string,
|
||||
port: number,
|
||||
hostname: string,
|
||||
role: string | null,
|
||||
input: string,
|
||||
caRole = "operator",
|
||||
complete: (data: string) => boolean = () => true,
|
||||
) {
|
||||
const ca = await readFile(resolve(local, "pki", caRole, "ca.crt"));
|
||||
const credentials = role
|
||||
? {
|
||||
cert: await readFile(resolve(local, "pki", role, "cert.pem")),
|
||||
key: await readFile(resolve(local, "pki", role, "key.pem")),
|
||||
}
|
||||
: {};
|
||||
return new Promise<{
|
||||
data: string;
|
||||
authorized: boolean;
|
||||
protocol: string | null;
|
||||
}>((done, fail) => {
|
||||
let finished = false,
|
||||
buffer = "";
|
||||
const socket = connect({
|
||||
host: ip,
|
||||
port,
|
||||
servername: hostname,
|
||||
ca,
|
||||
...credentials,
|
||||
rejectUnauthorized: true,
|
||||
minVersion: "TLSv1.2",
|
||||
ALPNProtocols:
|
||||
port === 5432 ? ["postgresql"] : port === 4317 ? ["h2"] : undefined,
|
||||
});
|
||||
const timer = setTimeout(
|
||||
() => finish(undefined, new Error("TRANSPORT_TIMEOUT")),
|
||||
4000,
|
||||
);
|
||||
function finish(data?: string, error?: Error) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
const result = {
|
||||
data: data ?? "",
|
||||
authorized: socket.authorized,
|
||||
protocol: socket.getProtocol(),
|
||||
};
|
||||
socket.destroy();
|
||||
if (error) fail(error);
|
||||
else done(result);
|
||||
}
|
||||
socket.on("secureConnect", () => {
|
||||
if (input) socket.write(input);
|
||||
else finish("TLS_HANDSHAKE");
|
||||
});
|
||||
socket.on("data", (data) => {
|
||||
buffer += data.toString();
|
||||
if (buffer.length >= 1048576) {
|
||||
finish(undefined, new Error("TRANSPORT_RESPONSE_TOO_LARGE"));
|
||||
return;
|
||||
}
|
||||
if (complete(buffer)) finish(buffer);
|
||||
});
|
||||
socket.on("end", () => finish(buffer));
|
||||
socket.on("close", () => finish(buffer));
|
||||
socket.on("error", (e) => finish(undefined, e));
|
||||
});
|
||||
}
|
||||
export function transportErrorCode(error: unknown) {
|
||||
const code = (error as { code?: string })?.code;
|
||||
return typeof code === "string" ? code : "UNCLASSIFIED_TLS_ERROR";
|
||||
}
|
||||
export const trustErrors = [
|
||||
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
||||
"SELF_SIGNED_CERT_IN_CHAIN",
|
||||
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
||||
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
||||
"ERR_TLS_CERT_ALTNAME_INVALID",
|
||||
"CERT_HAS_EXPIRED",
|
||||
"CERT_NOT_YET_VALID",
|
||||
];
|
||||
export async function expectDenied(
|
||||
probe: () => ReturnType<typeof tlsProbe>,
|
||||
kind: "trust" | "client" | "role",
|
||||
) {
|
||||
try {
|
||||
const result = await probe();
|
||||
requireThat(
|
||||
kind === "role" && result.data === "" && result.authorized,
|
||||
"TLS_NEGATIVE_UNEXPECTED_SUCCESS",
|
||||
);
|
||||
return "ROLE_CLOSED_BEFORE_APPLICATION_RESPONSE";
|
||||
} catch (error) {
|
||||
const code = transportErrorCode(error);
|
||||
const clientErrors = [
|
||||
"ERR_SSL_TLSV13_ALERT_CERTIFICATE_REQUIRED",
|
||||
"ERR_SSL_TLSV1_ALERT_CERTIFICATE_REQUIRED",
|
||||
"ERR_SSL_TLSV1_ALERT_UNKNOWN_CA",
|
||||
"ERR_SSL_SSLV3_ALERT_BAD_CERTIFICATE",
|
||||
"ERR_SSL_SSLV3_ALERT_CERTIFICATE_REVOKED",
|
||||
"ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE",
|
||||
"ERR_SSL_TLSV1_ALERT_ACCESS_DENIED",
|
||||
"ERR_SSL_TLSV1_ALERT_DECRYPT_ERROR",
|
||||
"ERR_SSL_TLSV1_ALERT_DECODE_ERROR",
|
||||
"ECONNRESET",
|
||||
];
|
||||
await privateWrite(
|
||||
resolve(
|
||||
local,
|
||||
"diagnostics",
|
||||
"tls-negative-" + crypto.randomUUID() + ".json",
|
||||
),
|
||||
JSON.stringify({
|
||||
kind,
|
||||
code,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
}),
|
||||
);
|
||||
requireThat(
|
||||
(kind === "trust" ? trustErrors : clientErrors).includes(code),
|
||||
"NEGATIVE_FAILED_FOR_UNEXPECTED_REASON",
|
||||
);
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { test, expect } from "bun:test";
|
||||
import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { root, local, run, requireThat } from "../scripts/runtime";
|
||||
import { workerACL, publisherACL } from "../scripts/valkey-acl";
|
||||
import { images } from "../scripts/topology";
|
||||
test("worker reclaims a real pending entry but cannot flush the broker", async () => {
|
||||
const scratch = await mkdtemp(resolve(local, "valkey-reclaim-")),
|
||||
name = "vp7-acl-" + randomBytes(6).toString("hex"),
|
||||
password = randomBytes(32).toString("hex");
|
||||
const acl =
|
||||
"user default off\nuser operator on #" +
|
||||
createHash("sha256").update(password).digest("hex") +
|
||||
" ~* &* +@all\n" +
|
||||
workerACL(password) +
|
||||
"\n" +
|
||||
publisherACL(password) +
|
||||
"\n";
|
||||
await writeFile(resolve(scratch, "users.acl"), acl, { mode: 0o600 });
|
||||
let started = false;
|
||||
try {
|
||||
await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--detach",
|
||||
"--rm",
|
||||
"--pull=never",
|
||||
"--name",
|
||||
name,
|
||||
"--label",
|
||||
"vp7.owner=" + name,
|
||||
"--network",
|
||||
"none",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--read-only",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--security-opt",
|
||||
"no-new-privileges",
|
||||
"--pids-limit",
|
||||
"64",
|
||||
"--memory",
|
||||
"128m",
|
||||
"--cpus",
|
||||
"0.5",
|
||||
"--mount",
|
||||
`type=bind,source=${scratch},target=/data`,
|
||||
images.broker,
|
||||
"valkey-server",
|
||||
"--port",
|
||||
"0",
|
||||
"--unixsocket",
|
||||
"/data/valkey.sock",
|
||||
"--unixsocketperm",
|
||||
"600",
|
||||
"--aclfile",
|
||||
"/data/users.acl",
|
||||
"--save",
|
||||
"",
|
||||
"--appendonly",
|
||||
"no",
|
||||
]);
|
||||
started = true;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
if (await Bun.file(resolve(scratch, "valkey.sock")).exists()) break;
|
||||
await Bun.sleep(50);
|
||||
}
|
||||
const cli = async (input: string) =>
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--interactive",
|
||||
"--rm",
|
||||
"--pull=never",
|
||||
"--network",
|
||||
"none",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--mount",
|
||||
`type=bind,source=${scratch},target=/data`,
|
||||
"--entrypoint",
|
||||
"valkey-cli",
|
||||
images.broker,
|
||||
"--raw",
|
||||
"-s",
|
||||
"/data/valkey.sock",
|
||||
],
|
||||
{ input },
|
||||
);
|
||||
const seeded = await cli(
|
||||
`AUTH operator ${password}\nXGROUP CREATE attachment-jobs workers 0 MKSTREAM\nXADD attachment-jobs * job synthetic-reclaim-fixture\nXREADGROUP GROUP workers original COUNT 1 STREAMS attachment-jobs >\n`,
|
||||
);
|
||||
const entry = seeded.out.match(/\b\d+-\d+\b/)?.[0];
|
||||
requireThat(entry, "RECLAIM_POSITIVE_CONTROL_NO_ENTRY");
|
||||
const reclaimed = await cli(
|
||||
`AUTH worker ${password}\nXAUTOCLAIM attachment-jobs workers restarted 0 0-0 COUNT 1\nXPENDING attachment-jobs workers - + 1\n`,
|
||||
);
|
||||
const reclaimOutput = reclaimed.out + reclaimed.err;
|
||||
await writeFile(
|
||||
resolve(
|
||||
root,
|
||||
"evidence/security/valkey-reclaim-split-" +
|
||||
crypto.randomUUID() +
|
||||
".json",
|
||||
),
|
||||
JSON.stringify(
|
||||
{
|
||||
server: "Valkey9.1.2 existing image",
|
||||
real_pending_entry_seeded: !!entry,
|
||||
reclaim_denied: reclaimOutput.includes("NOPERM"),
|
||||
pending_entry_returned: reclaimOutput.includes(entry),
|
||||
new_owner_confirmed: reclaimOutput.includes("restarted"),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
{ flag: "wx" },
|
||||
);
|
||||
expect(reclaimOutput.includes("NOPERM")).toBe(false);
|
||||
expect(reclaimOutput.includes(entry)).toBe(true);
|
||||
expect(reclaimOutput.includes("restarted")).toBe(true);
|
||||
const denied = await cli(`AUTH worker ${password}\nFLUSHALL\n`);
|
||||
expect((denied.out + denied.err).includes("NOPERM")).toBe(true);
|
||||
const consumerPublish = await cli(
|
||||
`AUTH worker ${password}\nXADD attachment-jobs * job forbidden-consumer-publish\n`,
|
||||
);
|
||||
expect((consumerPublish.out + consumerPublish.err).includes("NOPERM")).toBe(
|
||||
true,
|
||||
);
|
||||
const published = await cli(
|
||||
`AUTH publisher ${password}\nXADD attachment-jobs * job allowed-publisher-fixture\n`,
|
||||
);
|
||||
expect(published.out.match(/\b\d+-\d+\b/)).toBeTruthy();
|
||||
const producerConsume = await cli(
|
||||
`AUTH publisher ${password}\nXREADGROUP GROUP workers forbidden COUNT 1 STREAMS attachment-jobs >\n`,
|
||||
);
|
||||
expect((producerConsume.out + producerConsume.err).includes("NOPERM")).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
if (started) {
|
||||
const state = JSON.parse((await run(["docker", "inspect", name])).out)[0];
|
||||
requireThat(
|
||||
state.Config.Labels["vp7.owner"] === name,
|
||||
"RECLAIM_CONTAINER_OWNERSHIP",
|
||||
);
|
||||
await run(["docker", "stop", "--time", "3", name]);
|
||||
}
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -0,0 +1,85 @@
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, run, requireThat, safeFailure } from "../scripts/runtime";
|
||||
import { containerIP } from "../scripts/runtime-inspect";
|
||||
export async function waitReady(
|
||||
replicaServices = ["api1", "api2"],
|
||||
budget = 90_000,
|
||||
) {
|
||||
const deadline = Date.now() + budget;
|
||||
for (const service of replicaServices) {
|
||||
const hostname = service + "-gateway";
|
||||
let ready = false;
|
||||
while (Date.now() < deadline) {
|
||||
const ip = await containerIP(hostname);
|
||||
const result = await run(
|
||||
[
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--max-time",
|
||||
"3",
|
||||
"--cacert",
|
||||
resolve(local, "pki/lb/ca.crt"),
|
||||
"--cert",
|
||||
resolve(local, "pki/lb/cert.pem"),
|
||||
"--key",
|
||||
resolve(local, "pki/lb/key.pem"),
|
||||
"--resolve",
|
||||
`${hostname}:8443:${ip}`,
|
||||
`https://${hostname}:8443/health/ready`,
|
||||
"--write-out",
|
||||
"\n%{http_code}",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
if (result.code === 0) {
|
||||
const split = result.out.lastIndexOf("\n");
|
||||
if (result.out.slice(split + 1) === "200") {
|
||||
try {
|
||||
ready = JSON.parse(result.out.slice(0, split)).status === "ok";
|
||||
} catch {}
|
||||
if (ready) break;
|
||||
}
|
||||
}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(ready, "READINESS_TIMEOUT_" + service.toUpperCase());
|
||||
}
|
||||
let publicReady = false;
|
||||
while (Date.now() < deadline) {
|
||||
const publicResult = await run(
|
||||
[
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--fail",
|
||||
"--max-time",
|
||||
"3",
|
||||
"--cacert",
|
||||
resolve(local, "pki/lb/ca.crt"),
|
||||
`https://localhost:${Bun.env.HTTPS_PORT ?? 18443}/health/ready`,
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
if (publicResult.code === 0) {
|
||||
try {
|
||||
publicReady = JSON.parse(publicResult.out).status === "ok";
|
||||
} catch {}
|
||||
if (publicReady) break;
|
||||
}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(publicReady, "PUBLIC_READINESS_FAILED");
|
||||
console.log("PASS_ALL_REQUIRED_REPLICAS_AND_VERIFIED_HTTPS_READY");
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await waitReady();
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user