forked from mtusi2026/mtusi2026lab7
Prepare verified laboratory 7 implementation and evidence
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
run,
|
||||
compose,
|
||||
requireThat,
|
||||
privateWrite,
|
||||
} from "./runtime";
|
||||
import { start } from "./lab";
|
||||
import { auditMatrix } from "../student-tests/matrix";
|
||||
import { auditBao } from "../student-tests/bao-policy";
|
||||
import { auditWorkerPrivileges } from "../student-tests/privileges";
|
||||
import { waitReady } from "../student-tests/wait";
|
||||
import { postgresTransport } from "../student-tests/postgres-transport";
|
||||
import { checkSource } from "./check-source";
|
||||
import { prepareProbePKI } from "../student-tests/probe-pki";
|
||||
import { type RuntimeMode } from "./runtime-preparation";
|
||||
import { verifyCheckedRuntime } from "./checked-runtime";
|
||||
import { createFailoverReader, type ReplicaService } from "./failover-proof";
|
||||
import { snapshotReplicas } from "./hooks";
|
||||
import { type GitTrackingSource } from "./git-tracking-proof";
|
||||
import { sharedLoginRuntime } from "../student-tests/shared-login-runtime";
|
||||
export async function acceptanceRemainder(
|
||||
password: string,
|
||||
operationId: string,
|
||||
gitSource: GitTrackingSource,
|
||||
setStage: (stage: string) => void,
|
||||
) {
|
||||
const failedReplicas = new Set<ReplicaService>(),
|
||||
failoverReceipts: string[] = [];
|
||||
const readFailover = createFailoverReader({
|
||||
read: async (path) =>
|
||||
JSON.parse(await readFile(resolve(root, path), "utf8")),
|
||||
});
|
||||
const env = {
|
||||
BASE_URL: "https://localhost:18443",
|
||||
CA_FILE: resolve(local, "pki/lb/ca.crt"),
|
||||
VP7_OPERATOR_PASSWORD: password,
|
||||
VP7_ACCEPTANCE_RUN_ID: operationId,
|
||||
PATH: resolve(process.execPath, "..") + ":" + Bun.env.PATH,
|
||||
};
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
setStage("PUBLIC_FAILOVER_" + attempt);
|
||||
const attemptId = crypto.randomUUID(),
|
||||
baseline = await snapshotReplicas();
|
||||
const failure = await run(
|
||||
[
|
||||
"make",
|
||||
"test-failover",
|
||||
"ACTION_SCRIPT=" + resolve(root, "scripts/stop-one.sh"),
|
||||
],
|
||||
{ env: { ...env, VP7_FAILOVER_ATTEMPT_ID: attemptId } },
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/public-failover-" + attempt + ".txt"),
|
||||
failure.out + failure.err,
|
||||
);
|
||||
const observed = await readFailover(operationId, attemptId, baseline);
|
||||
failedReplicas.add(observed.proof.service);
|
||||
failoverReceipts.push(observed.path);
|
||||
await compose(["up", "-d", "api1", "api2"]);
|
||||
await waitReady();
|
||||
if (failedReplicas.size === 2) break;
|
||||
}
|
||||
requireThat(failedReplicas.size === 2, "BOTH_REPLICA_FAILURES_NOT_PROVED");
|
||||
setStage("EXTENDED_ACCEPTANCE");
|
||||
const extra = await import("../student-tests/extended");
|
||||
await extra.extendedAcceptance(password, operationId, gitSource);
|
||||
setStage("SHARED_HTTP_LOGIN");
|
||||
await sharedLoginRuntime(password, operationId);
|
||||
return failoverReceipts;
|
||||
}
|
||||
export async function acceptanceSession(
|
||||
password: string,
|
||||
runtimeMode: RuntimeMode = "canonical",
|
||||
gitSource: GitTrackingSource = { kind: "native-git" },
|
||||
) {
|
||||
const operationId = crypto.randomUUID();
|
||||
let stage = "FULL_STAND_START";
|
||||
try {
|
||||
const checkedRuntime =
|
||||
runtimeMode === "checked-cache"
|
||||
? await verifyCheckedRuntime()
|
||||
: undefined;
|
||||
await start(password, runtimeMode);
|
||||
stage = "PUBLIC_STRUCTURE";
|
||||
const env = {
|
||||
BASE_URL: "https://localhost:18443",
|
||||
CA_FILE: resolve(local, "pki/lb/ca.crt"),
|
||||
VP7_OPERATOR_PASSWORD: password,
|
||||
VP7_ACCEPTANCE_RUN_ID: operationId,
|
||||
PATH: resolve(process.execPath, "..") + ":" + Bun.env.PATH,
|
||||
};
|
||||
await checkSource();
|
||||
for (const target of ["test", "test-security"]) {
|
||||
stage = "PUBLIC_" + target.toUpperCase().replaceAll("-", "_");
|
||||
const r = await run(["make", target], { env });
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/public-" + target + ".txt"),
|
||||
r.out + r.err,
|
||||
);
|
||||
console.log("PASS_" + stage);
|
||||
}
|
||||
stage = "POSTGRES_TRANSPORT";
|
||||
await prepareProbePKI(password);
|
||||
await postgresTransport();
|
||||
stage = "TLS_MATRIX";
|
||||
await auditMatrix();
|
||||
stage = "BAO_POLICY";
|
||||
await auditBao();
|
||||
stage = "WORKER_PRIVILEGES";
|
||||
await auditWorkerPrivileges(password);
|
||||
stage = "PUBLIC_PERSISTENCE";
|
||||
const persistence = await run(
|
||||
[
|
||||
"make",
|
||||
"test-persistence",
|
||||
"ACTION_SCRIPT=" + resolve(root, "scripts/restart.sh"),
|
||||
],
|
||||
{ env },
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/public-persistence.txt"),
|
||||
persistence.out + persistence.err,
|
||||
);
|
||||
const failoverReceipts = await acceptanceRemainder(
|
||||
password,
|
||||
operationId,
|
||||
gitSource,
|
||||
(value) => {
|
||||
stage = value;
|
||||
},
|
||||
);
|
||||
await checkedRuntime?.verify();
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/session.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS",
|
||||
operation_id: operationId,
|
||||
failover_receipts: failoverReceipts,
|
||||
finished_stage: stage,
|
||||
runtime_mode: runtimeMode,
|
||||
grade_awarded: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(() =>
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/acceptance-error.json"),
|
||||
JSON.stringify({
|
||||
stage,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
stack: error instanceof Error ? error.stack : "",
|
||||
}),
|
||||
),
|
||||
),
|
||||
Promise.resolve().then(() =>
|
||||
writeFile(
|
||||
resolve(root, "evidence/security/session.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "FAILED",
|
||||
stage,
|
||||
details: "private .local/diagnostics/acceptance-error.json",
|
||||
grade_awarded: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
),
|
||||
),
|
||||
]);
|
||||
console.error("ACCEPTANCE_STAGE_" + stage);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { resolve } from "node:path";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { local, run, privateWrite, requireThat } from "./runtime";
|
||||
export async function bao(
|
||||
path: string,
|
||||
options: {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
token?: string;
|
||||
role?: string;
|
||||
expected?: number[];
|
||||
} = {},
|
||||
) {
|
||||
requireThat(/^\/[a-zA-Z0-9/_-]+$/.test(path), "INVALID_BAO_PATH");
|
||||
const role = options.role ?? "operator",
|
||||
port = Bun.env.BAO_PORT ?? "18445";
|
||||
requireThat(/^\d{4,5}$/.test(port), "INVALID_BAO_PORT");
|
||||
const scratch = await mkdtemp(resolve(local, "operator", "request-"));
|
||||
try {
|
||||
const headers = resolve(scratch, "headers");
|
||||
await privateWrite(
|
||||
headers,
|
||||
`Content-Type: application/json\n${options.token ? "X-Vault-Token: " + options.token + "\n" : ""}`,
|
||||
);
|
||||
const args = [
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--max-time",
|
||||
"10",
|
||||
"--cacert",
|
||||
resolve(local, "pki", role, "ca.crt"),
|
||||
"--cert",
|
||||
resolve(local, "pki", role, "cert.pem"),
|
||||
"--key",
|
||||
resolve(local, "pki", role, "key.pem"),
|
||||
"--resolve",
|
||||
`openbao:${port}:127.0.0.1`,
|
||||
"--header",
|
||||
"@" + headers,
|
||||
"--request",
|
||||
options.method ?? (options.body ? "POST" : "GET"),
|
||||
"--url",
|
||||
`https://openbao:${port}/v1${path}`,
|
||||
"--write-out",
|
||||
"\n%{http_code}",
|
||||
];
|
||||
if (options.body !== undefined) args.push("--data-binary", "@-");
|
||||
const result = await run(args, {
|
||||
input:
|
||||
options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
});
|
||||
const split = result.out.lastIndexOf("\n"),
|
||||
status = Number(result.out.slice(split + 1)),
|
||||
body = result.out.slice(0, split);
|
||||
let data: any = null;
|
||||
try {
|
||||
data = body ? JSON.parse(body) : null;
|
||||
} catch {
|
||||
await privateWrite(
|
||||
resolve(local, "diagnostics", "bao-malformed.txt"),
|
||||
body,
|
||||
);
|
||||
throw new Error("BAO_INVALID_RESPONSE");
|
||||
}
|
||||
if (!(options.expected ?? [200, 204]).includes(status)) {
|
||||
await privateWrite(
|
||||
resolve(local, "diagnostics", "bao-error.json"),
|
||||
JSON.stringify({ path, status, data }),
|
||||
);
|
||||
throw new Error(`BAO_HTTP_${status}`);
|
||||
}
|
||||
return { status, data };
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { mkdir, readFile, open, chmod } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { randomBytes, createHash } from "node:crypto";
|
||||
import { root, local, privateWrite, requireThat, safeFailure } from "./runtime";
|
||||
import { createCA, issue } from "./pki";
|
||||
import { encrypt, operatorPassword } from "./operator-crypto";
|
||||
import { roles, writeTopology } from "./topology";
|
||||
import { workerACL, publisherACL } from "./valkey-acl";
|
||||
import { prepareOpenObserve } from "./openobserve";
|
||||
import { prepareGrafana } from "./grafana";
|
||||
const random = () => randomBytes(32).toString("hex");
|
||||
export async function bootstrap(password: string) {
|
||||
await mkdir(local, { recursive: true, mode: 0o700 });
|
||||
await chmod(local, 0o700);
|
||||
const claim = await open(resolve(local, "bootstrap-claim.json"), "wx", 0o600);
|
||||
await claim.writeFile(JSON.stringify({ state: "RUNNING" }));
|
||||
await claim.close();
|
||||
const operator = resolve(local, "operator");
|
||||
await mkdir(operator, { recursive: true, mode: 0o700 });
|
||||
const ca = resolve(operator, "ca");
|
||||
await createCA(ca, password);
|
||||
for (const role of roles)
|
||||
await issue(ca, resolve(local, "pki", role), role, password);
|
||||
for (const name of [
|
||||
"postgres",
|
||||
"broker",
|
||||
"s3",
|
||||
"s3-logs",
|
||||
"bao",
|
||||
"collector",
|
||||
"openobserve",
|
||||
"grafana",
|
||||
])
|
||||
await mkdir(resolve(local, "data", name), { recursive: true, mode: 0o700 });
|
||||
await mkdir(resolve(local, "plugins"), { recursive: true, mode: 0o700 });
|
||||
// The official image creates a postgres-owned PGDATA child then drops UID; it must traverse the bind root.
|
||||
await chmod(resolve(local, "data", "postgres"), 0o755);
|
||||
for (const service of ["api1", "api2", "worker"])
|
||||
await mkdir(resolve(local, "rendered", service), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
const secrets = {
|
||||
dbOperator: random(),
|
||||
dbApi: random(),
|
||||
dbWorker: random(),
|
||||
brokerOperator: random(),
|
||||
brokerApi: random(),
|
||||
brokerWorker: random(),
|
||||
brokerPublisher: random(),
|
||||
s3RootAccess: "vp7operator",
|
||||
s3RootSecret: random(),
|
||||
s3ApiAccess: "vp7api",
|
||||
s3ApiSecret: random(),
|
||||
s3WorkerAccess: "vp7worker",
|
||||
s3WorkerSecret: random(),
|
||||
grafana: random(),
|
||||
};
|
||||
// Operator-only encrypted envelope is never mounted into a service. Service bootstrap files are exact single-file mounts.
|
||||
await privateWrite(
|
||||
resolve(operator, "services.enc"),
|
||||
encrypt(secrets, password),
|
||||
);
|
||||
await privateWrite(resolve(operator, "db-password"), secrets.dbOperator);
|
||||
await privateWrite(resolve(operator, "grafana-password"), secrets.grafana);
|
||||
await prepareGrafana(password);
|
||||
await privateWrite(
|
||||
resolve(local, "config", "s3.env"),
|
||||
`RUSTFS_ACCESS_KEY=${secrets.s3RootAccess}\nRUSTFS_SECRET_KEY=${secrets.s3RootSecret}\nRUSTFS_CONSOLE_ENABLE=false\nRUSTFS_OBS_LOG_DIRECTORY=/logs\n`,
|
||||
);
|
||||
const hash = (s: string) => createHash("sha256").update(s).digest("hex");
|
||||
await privateWrite(
|
||||
resolve(local, "config", "users.acl"),
|
||||
`user default off\nuser operator on #${hash(secrets.brokerOperator)} ~* &* +@all\nuser api on #${hash(secrets.brokerApi)} ~profile:* &* -@all +ping +hello +client|setinfo +get +set\n${workerACL(secrets.brokerWorker)}\n${publisherACL(secrets.brokerPublisher)}\n`,
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "config", "valkey.conf"),
|
||||
"bind 127.0.0.1\nport 16379\nprotected-mode yes\naclfile /config/users.acl\nappendonly yes\nappendfsync always\ndir /data\nmaxmemory 134217728\nmaxmemory-policy noeviction\nsave 60 1\nloglevel warning\n",
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(root, ".env"),
|
||||
`LOCAL_UID=${process.getuid?.() ?? 1000}\nLOCAL_GID=${process.getgid?.() ?? 1000}\nHTTPS_PORT=18443\nBAO_PORT=18445\nGRAFANA_PORT=18447\nSESSION_TTL_SECONDS=3600\n`,
|
||||
);
|
||||
await prepareOpenObserve(password);
|
||||
await writeTopology();
|
||||
await privateWrite(
|
||||
resolve(local, "bootstrap-claim.json"),
|
||||
JSON.stringify({ state: "COMPLETE", secret_values_printed: false }),
|
||||
);
|
||||
console.log("PASS_BOOTSTRAP_LOCAL_PKI_ENCRYPTED_OPERATOR_MATERIAL");
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await bootstrap(await operatorPassword());
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
export type BrowserLifecyclePorts<C, R> = {
|
||||
acquire: () => Promise<C>;
|
||||
run: (context: C) => Promise<R>;
|
||||
close: (context: C) => Promise<void>;
|
||||
reportCleanupFailure: (error: unknown) => Promise<void>;
|
||||
};
|
||||
|
||||
export function createBrowserLifecycle<C, R>(
|
||||
ports: BrowserLifecyclePorts<C, R>,
|
||||
) {
|
||||
if (
|
||||
!ports ||
|
||||
[ports.acquire, ports.run, ports.close, ports.reportCleanupFailure].some(
|
||||
(port) => typeof port !== "function",
|
||||
)
|
||||
)
|
||||
throw new Error("BROWSER_LIFECYCLE_PORTS_REQUIRED");
|
||||
return async () => {
|
||||
const context = await ports.acquire();
|
||||
let failed = false;
|
||||
try {
|
||||
return await ports.run(context);
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
throw error;
|
||||
} finally {
|
||||
try {
|
||||
await ports.close(context);
|
||||
} catch (error) {
|
||||
try {
|
||||
await ports.reportCleanupFailure(error);
|
||||
} catch {}
|
||||
if (!failed) throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import {
|
||||
mkdtemp,
|
||||
readdir,
|
||||
copyFile,
|
||||
mkdir,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, run, safeFailure } from "./runtime";
|
||||
// Public check recursively treats every *.json path as a JSON file. RustFS legitimately stores
|
||||
// policy.json as an object directory. Run the unchanged checker against source bytes, not a live data store.
|
||||
export async function checkSource(
|
||||
scope: "security" | "openobserve" | "grafana" = "security",
|
||||
) {
|
||||
await mkdir(local, { recursive: true, mode: 0o700 });
|
||||
const scratch = await mkdtemp(resolve(local, "source-check-"));
|
||||
async function copy(source: string, destination: string) {
|
||||
await mkdir(destination, { recursive: true });
|
||||
for (const entry of await readdir(source, { withFileTypes: true })) {
|
||||
if (
|
||||
[
|
||||
".git",
|
||||
"node_modules",
|
||||
".venv",
|
||||
".env",
|
||||
"dist",
|
||||
"build",
|
||||
"target",
|
||||
"bin",
|
||||
"obj",
|
||||
].includes(entry.name) ||
|
||||
entry.name.startsWith(".local") ||
|
||||
entry.name.endsWith(".zip")
|
||||
)
|
||||
continue;
|
||||
const from = resolve(source, entry.name),
|
||||
to = resolve(destination, entry.name);
|
||||
if (entry.isDirectory()) await copy(from, to);
|
||||
else if (entry.isFile()) await copyFile(from, to);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await copy(root, scratch);
|
||||
const result = await run(["make", "check"], { cwd: scratch });
|
||||
await writeFile(
|
||||
resolve(root, `evidence/${scope}/public-source-check.txt`),
|
||||
result.out + result.err,
|
||||
);
|
||||
console.log("PASS_UNCHANGED_PUBLIC_CHECK_IN_SOURCE_ONLY_SNAPSHOT");
|
||||
return result;
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await checkSource(
|
||||
Bun.argv.includes("--grafana")
|
||||
? "grafana"
|
||||
: Bun.argv.includes("--openobserve")
|
||||
? "openobserve"
|
||||
: "security",
|
||||
);
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { run, requireThat, safeFailure } from "./runtime";
|
||||
import { images } from "./topology";
|
||||
try {
|
||||
const source = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--entrypoint",
|
||||
"sh",
|
||||
images.s3,
|
||||
"-c",
|
||||
"command -v rustfs; rustfs --help",
|
||||
]);
|
||||
const combined = source.out + source.err;
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service: "RustFS",
|
||||
binary: source.out.split("\n")[0],
|
||||
address_flag: combined.includes("--address"),
|
||||
console_enable_flag: combined.includes("--console-enable"),
|
||||
environment_names: [
|
||||
...new Set(combined.match(/\bRUSTFS_[A-Z_]+\b/g) ?? []),
|
||||
],
|
||||
stdout_length: source.out.length,
|
||||
stderr_length: source.err.length,
|
||||
}),
|
||||
);
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { root, run, requireThat } from "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
export async function verifyCheckedRuntime() {
|
||||
const source = await verifyBackendHandover();
|
||||
requireThat(
|
||||
source.count === 112 &&
|
||||
source.sha256 ===
|
||||
"09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609",
|
||||
"CHECKED_RUNTIME_SOURCE_MISMATCH",
|
||||
);
|
||||
const image = "mtuci-vp7-security-app:local",
|
||||
imageID =
|
||||
"sha256:10ba7b17671b785016130f96f781cbee7abb9f8d22ad6ec2e2027bc5eb972e4d";
|
||||
const expected = {
|
||||
app: "37726b99a2b64f888d4cf5a0b72e949ff12318fa5d3a2e162a748573f2a484c0",
|
||||
worker: "9d359b5b6e0a0cbaa515bca37238af9a838c1100cbdd0c698e8d4b500f1f3a3f",
|
||||
"s3-control":
|
||||
"5c6ad096222ade5452574a43c9343ae91dd4d596104f68dac02b15bd6c8837a3",
|
||||
};
|
||||
const buildPath = resolve(root, "evidence/preflight/checked112-build.json"),
|
||||
buildBytes = await readFile(buildPath),
|
||||
build = JSON.parse(buildBytes.toString());
|
||||
const hash = (b: Uint8Array) => createHash("sha256").update(b).digest("hex");
|
||||
requireThat(
|
||||
build.source_handover_sha256 === source.sha256 &&
|
||||
build.source_files_verified === 112 &&
|
||||
Object.entries(expected).every(([p, sha]) => build.binaries[p] === sha),
|
||||
"CHECKED_RUNTIME_BUILD_RECEIPT_MISMATCH",
|
||||
);
|
||||
async function verify() {
|
||||
await source.verify();
|
||||
requireThat(
|
||||
(await readFile(buildPath)).equals(buildBytes),
|
||||
"CHECKED_RUNTIME_BUILD_RECEIPT_CHANGED",
|
||||
);
|
||||
requireThat(
|
||||
hash(await readFile(resolve(root, "scripts/s3-control.go"))) ===
|
||||
build.s3_control_source_sha256,
|
||||
"CHECKED_RUNTIME_HELPER_SOURCE_CHANGED",
|
||||
);
|
||||
const info = JSON.parse(
|
||||
(await run(["docker", "image", "inspect", image])).out,
|
||||
)[0];
|
||||
requireThat(
|
||||
info.Id === imageID &&
|
||||
info.Os === "linux" &&
|
||||
info.Architecture === "amd64",
|
||||
"CHECKED_RUNTIME_IMAGE_CHANGED",
|
||||
);
|
||||
const installed = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--pull=never",
|
||||
"--network",
|
||||
"none",
|
||||
"--entrypoint",
|
||||
"sha256sum",
|
||||
imageID,
|
||||
"/app",
|
||||
"/worker",
|
||||
"/s3-control",
|
||||
]);
|
||||
const lines = installed.out.trim().split("\n");
|
||||
requireThat(lines.length === 3, "CHECKED_RUNTIME_BINARY_OUTPUT_INVALID");
|
||||
const actual: Record<string, string> = {};
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^([a-f0-9]{64})\s+\/(app|worker|s3-control)$/);
|
||||
requireThat(m, "CHECKED_RUNTIME_BINARY_OUTPUT_INVALID");
|
||||
actual[m[2]] = m[1];
|
||||
}
|
||||
requireThat(
|
||||
Object.entries(expected).every(([p, sha]) => actual[p] === sha),
|
||||
"CHECKED_RUNTIME_BINARY_CHANGED",
|
||||
);
|
||||
}
|
||||
await verify();
|
||||
return {
|
||||
image,
|
||||
image_id: imageID,
|
||||
source_sha256: source.sha256,
|
||||
binaries: expected,
|
||||
verify,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { createHash } from "node:crypto";
|
||||
const hash = (bytes: Uint8Array) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
function requireGuard(value: unknown, code: string): asserts value {
|
||||
if (!value) throw new Error(code);
|
||||
}
|
||||
export function assertSameSnapshot(
|
||||
first: Record<string, string>,
|
||||
second: Record<string, string>,
|
||||
) {
|
||||
const paths = Object.keys(first).sort();
|
||||
requireGuard(
|
||||
JSON.stringify(paths) === JSON.stringify(Object.keys(second).sort()) &&
|
||||
paths.every((path) => first[path] === second[path]),
|
||||
"SOURCE_SNAPSHOT_CHANGED",
|
||||
);
|
||||
}
|
||||
export function createEvidencePreserver(ports: {
|
||||
writeExclusive: (path: string, bytes: Uint8Array) => Promise<void>;
|
||||
read: (path: string) => Promise<Uint8Array>;
|
||||
}) {
|
||||
requireGuard(
|
||||
ports &&
|
||||
typeof ports.writeExclusive === "function" &&
|
||||
typeof ports.read === "function",
|
||||
"INVALID_EVIDENCE_PORTS",
|
||||
);
|
||||
return async (path: string, bytes: Uint8Array) => {
|
||||
try {
|
||||
await ports.writeExclusive(path, bytes);
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code !== "EEXIST") throw error;
|
||||
requireGuard(
|
||||
Buffer.from(await ports.read(path)).equals(Buffer.from(bytes)),
|
||||
"HISTORICAL_EVIDENCE_CONFLICT",
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
export async function pinHandover(ports: {
|
||||
readReceipt: () => Promise<Uint8Array>;
|
||||
readSource: (path: string) => Promise<Uint8Array>;
|
||||
}) {
|
||||
requireGuard(
|
||||
ports &&
|
||||
typeof ports.readReceipt === "function" &&
|
||||
typeof ports.readSource === "function",
|
||||
"INVALID_HANDOVER_PORTS",
|
||||
);
|
||||
const initial = Buffer.from(await ports.readReceipt()),
|
||||
receipt = JSON.parse(initial.toString());
|
||||
requireGuard(
|
||||
receipt.runtimeTelemetry === false && receipt.runtimeSecurity === false,
|
||||
"UNEXPECTED_HANDOVER_SCOPE",
|
||||
);
|
||||
const files = { ...receipt.files, ...receipt.preservedFreshness };
|
||||
const paths = Object.keys(files);
|
||||
requireGuard(
|
||||
paths.length > 0 &&
|
||||
paths.length ===
|
||||
Object.keys(receipt.files).length +
|
||||
Object.keys(receipt.preservedFreshness).length,
|
||||
"INVALID_HANDOVER_MAP",
|
||||
);
|
||||
for (const path of paths)
|
||||
requireGuard(
|
||||
!path.startsWith("/") &&
|
||||
!path.split("/").includes("..") &&
|
||||
!/[\x00\r\n]/.test(path) &&
|
||||
/^[a-f0-9]{64}$/.test(files[path]),
|
||||
"INVALID_HANDOVER_PATH_OR_HASH",
|
||||
);
|
||||
const verify = async () => {
|
||||
requireGuard(
|
||||
initial.equals(Buffer.from(await ports.readReceipt())),
|
||||
"HANDOVER_GENERATION_CHANGED",
|
||||
);
|
||||
for (const path of paths)
|
||||
requireGuard(
|
||||
hash(await ports.readSource(path)) === files[path],
|
||||
"HANDOVER_SOURCE_CHANGED",
|
||||
);
|
||||
requireGuard(
|
||||
initial.equals(Buffer.from(await ports.readReceipt())),
|
||||
"HANDOVER_GENERATION_CHANGED",
|
||||
);
|
||||
};
|
||||
await verify();
|
||||
return {
|
||||
receipt,
|
||||
count: paths.length,
|
||||
bytes: Buffer.from(initial),
|
||||
sha256: hash(initial),
|
||||
verify,
|
||||
};
|
||||
}
|
||||
export function assertAcceptedGeneration(
|
||||
accepted: any,
|
||||
source: Uint8Array,
|
||||
build: any,
|
||||
) {
|
||||
try {
|
||||
const receipt = JSON.parse(Buffer.from(source).toString()),
|
||||
count = Object.keys({
|
||||
...receipt.files,
|
||||
...receipt.preservedFreshness,
|
||||
}).length;
|
||||
requireGuard(
|
||||
accepted &&
|
||||
build &&
|
||||
accepted.source_handover_sha256 === hash(source) &&
|
||||
build.source_handover_sha256 === hash(source) &&
|
||||
accepted.backend_checked_at === receipt.checkedAt &&
|
||||
build.backend_checked_at === receipt.checkedAt &&
|
||||
accepted.source_files_verified === count &&
|
||||
build.source_files_verified === count &&
|
||||
accepted.binaries.app === build.binaries.app &&
|
||||
accepted.binaries.worker === build.binaries.worker,
|
||||
"ACCEPTED_GENERATION_MISMATCH",
|
||||
);
|
||||
} catch {
|
||||
throw new Error("ACCEPTED_GENERATION_MISMATCH");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export type CommandOptions = {
|
||||
input?: string;
|
||||
allowFailure?: boolean;
|
||||
env?: Record<string, string>;
|
||||
cwd?: string;
|
||||
};
|
||||
export type CommandResult = { out: string; err: string; code: number };
|
||||
export type CommandRecord = {
|
||||
program: string;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number;
|
||||
};
|
||||
export type CommandPorts = {
|
||||
execute: (args: string[], options: CommandOptions) => Promise<CommandResult>;
|
||||
unique: (record: CommandRecord) => Promise<void>;
|
||||
last: (record: CommandRecord) => Promise<void>;
|
||||
};
|
||||
export function createCommandRunner(ports: CommandPorts) {
|
||||
if (
|
||||
!ports ||
|
||||
typeof ports.execute !== "function" ||
|
||||
typeof ports.unique !== "function" ||
|
||||
typeof ports.last !== "function"
|
||||
)
|
||||
throw new Error("INVALID_COMMAND_RUNNER_PORTS");
|
||||
const { execute, unique, last } = ports;
|
||||
return async (args: string[], options: CommandOptions = {}) => {
|
||||
const result = await execute(args, options);
|
||||
if (result.code !== 0 && !options.allowFailure) {
|
||||
const program = args[0] ?? "unknown",
|
||||
record = {
|
||||
program,
|
||||
code: result.code,
|
||||
stdout: result.out,
|
||||
stderr: result.err,
|
||||
};
|
||||
const primary = new Error(
|
||||
"COMMAND_FAILED_" +
|
||||
program.replace(/[^a-zA-Z0-9]/g, "_") +
|
||||
"_" +
|
||||
result.code,
|
||||
);
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(() => unique(record)),
|
||||
Promise.resolve().then(() => last(record)),
|
||||
]);
|
||||
throw primary;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { decrypt, operatorPassword } from "./operator-crypto";
|
||||
import { local, compose, safeFailure, requireThat } from "./runtime";
|
||||
export async function provisionDB(password: string, grantSchema = false) {
|
||||
const secrets = decrypt<any>(
|
||||
await readFile(resolve(local, "operator", "services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
for (const role of ["api", "worker"]) {
|
||||
const secret = secrets[role === "api" ? "dbApi" : "dbWorker"];
|
||||
requireThat(/^[a-f0-9]{64}$/.test(secret), "INVALID_DATABASE_PASSWORD");
|
||||
// Roles are idempotent; role and password values have fixed grammar before SQL interpolation.
|
||||
await compose(
|
||||
[
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-X",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
],
|
||||
{
|
||||
input: `DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='${role}') THEN CREATE ROLE ${role} LOGIN; END IF; END $$;\nALTER ROLE ${role} WITH LOGIN PASSWORD '${secret}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;\nGRANT CONNECT ON DATABASE messenger TO ${role};\nGRANT USAGE ON SCHEMA public TO ${role};\n`,
|
||||
},
|
||||
);
|
||||
}
|
||||
await compose(
|
||||
[
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-X",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
],
|
||||
{
|
||||
input:
|
||||
"REVOKE CREATE ON SCHEMA public FROM PUBLIC;\nREVOKE ALL ON DATABASE messenger FROM PUBLIC;\nGRANT CONNECT ON DATABASE messenger TO api,worker;\n",
|
||||
},
|
||||
);
|
||||
if (grantSchema)
|
||||
await compose(
|
||||
[
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-X",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
],
|
||||
{
|
||||
input:
|
||||
"GRANT SELECT,INSERT,UPDATE,DELETE ON users,chats,chat_members,messages,sessions,idempotency,attachments,message_attachments,attachment_jobs TO api;\nGRANT SELECT,UPDATE ON login_limits TO api;\nGRANT SELECT,UPDATE ON attachments,attachment_jobs TO worker;\n",
|
||||
},
|
||||
);
|
||||
console.log(
|
||||
grantSchema
|
||||
? "PASS_DB_SCOPED_SCHEMA_GRANTS"
|
||||
: "PASS_DB_SEPARATE_LOGIN_ROLES",
|
||||
);
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await provisionDB(await operatorPassword(), Bun.argv.includes("--schema"));
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local } from "./runtime";
|
||||
const record = JSON.parse(
|
||||
await readFile(resolve(local, "diagnostics/last-command.json"), "utf8"),
|
||||
);
|
||||
const content = String(record.stderr) + "\n" + String(record.stdout);
|
||||
const categories: Record<string, RegExp> = {
|
||||
IMAGE_ABSENT:
|
||||
/No such image|pull access denied|not found locally|image.*not found/i,
|
||||
PORT_BUSY: /port is already allocated|address already in use/i,
|
||||
MOUNT_MISSING: /bind source path does not exist|no such file or directory/i,
|
||||
NETWORK_MODE: /network mode|network namespace|network sharing container/i,
|
||||
CONTAINER_DEPENDENCY: /dependency failed|depends on|not running|not started/i,
|
||||
INVALID_CONFIG:
|
||||
/invalid compose|validating|additional properties|invalid mount config/i,
|
||||
PERMISSION: /permission denied|operation not permitted/i,
|
||||
CONFLICT: /conflict|already in use by container/i,
|
||||
READONLY: /read-only file system/i,
|
||||
EXITED: /exited|exit code/i,
|
||||
};
|
||||
Object.assign(categories, {
|
||||
CLI_USAGE: /unknown flag|unknown shorthand|usage:/i,
|
||||
GO_RUNTIME: /runtime:|fatal error:|goroutine|panic:/i,
|
||||
ALLOCATION: /memory|cannot allocate|resource temporarily unavailable/i,
|
||||
CONNECTION: /cannot connect|connection refused|broken pipe/i,
|
||||
YAML: /yaml:|unmarshal|interpolat/i,
|
||||
NO_SPACE: /no space left/i,
|
||||
});
|
||||
Object.assign(categories, {
|
||||
APPROVAL: /approval|review|permission request|sandbox/i,
|
||||
HERDR: /herdr|hc socket/i,
|
||||
COMPOSE_PLUGIN: /plugin|compose-switch/i,
|
||||
TERMINAL: /terminal|tty|pty/i,
|
||||
SYSTEM_BUS: /dbus|systemd|notification/i,
|
||||
SOCKET: /socket/i,
|
||||
NOT_SUPPORTED: /not supported|not permitted|not available/i,
|
||||
});
|
||||
Object.assign(categories, {
|
||||
JSON_PATH_IS_DIRECTORY: /IsADirectoryError/i,
|
||||
PYTHON_PERMISSION: /PermissionError/i,
|
||||
JSON_DECODE: /JSONDecodeError/i,
|
||||
});
|
||||
console.log(JSON.stringify({ docker_binary: Bun.which("docker") }));
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
diagnostic_terms:
|
||||
content
|
||||
.toLowerCase()
|
||||
.match(
|
||||
/\b(?:accept|connect|binding|send|recv|recvmsg|recvfrom|sendmsg|sendto|notify|hook|pretooluse|tool|connection|exist|managed|bridge|proxy|shutdown|configure|configured|crun|runc|reset|closed|refused|such|running|transport|protocol|mode|argument|malformed|sock_seqpacket|econnrefused|econnreset|eof|eagain|einval|enotconn|enoent|eacces|failed|not|nix|unix|linux|tcp|udp|http|unmarshal|decode|activation|notification|setup|listen|listening|respond|response|request|status|code|before|after|running|server|client|machine|remote|local|wrapper|container|sandbox|policy|database|journal|bus|environ|environment|context|batch|interactive|terminal|timeout|timed|out|stream|input|output|parse|busy|stale|missing|detected|available|connected|disconnected|reset|broken|pipe|lock|waiting|wait|executable|binary|file|function|directory)\b/g,
|
||||
) ?? [],
|
||||
}),
|
||||
);
|
||||
const words =
|
||||
content
|
||||
.toLowerCase()
|
||||
.match(
|
||||
/\b(?:error|failed|unable|cannot|open|read|write|image|manifest|compose|docker|stat|path|file|directory|variable|env|permission|denied|missing|invalid|not|found|unknown|option|unexpected|end|json|yaml|unsupported|credential|helper|executable|plugin|build|network|socket|daemon|connect|pull|registry|login|version|platform|architecture|exec|format|storage|interpolation|valid|credentialstore|panic|timeout|outside|context|syntax|line|character|unclosed|unterminated|exited|code|closed|stdin|stdout|stderr|operation|parse|parsing|mapping|alias|anchor|checking|lookup|address|resolution|host|too|many|levels|symbolic|links)\b/g,
|
||||
) ?? [];
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
program: ["docker", "make"].includes(record.program)
|
||||
? record.program
|
||||
: "OTHER",
|
||||
exit: record.code,
|
||||
stdout_bytes: String(record.stdout).length,
|
||||
stderr_bytes: String(record.stderr).length,
|
||||
categories: Object.entries(categories)
|
||||
.filter(([, pattern]) => pattern.test(content))
|
||||
.map(([code]) => code),
|
||||
words,
|
||||
services: [
|
||||
"postgres",
|
||||
"broker",
|
||||
"s3",
|
||||
"openbao",
|
||||
"lb",
|
||||
"api1",
|
||||
"api2",
|
||||
"worker",
|
||||
"migrate",
|
||||
].filter((name) => new RegExp("\\b" + name + "\\b").test(content)),
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,48 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local, run, compose } from "./runtime";
|
||||
const error = JSON.parse(
|
||||
await readFile(resolve(local, "diagnostics/preflight-error.json"), "utf8"),
|
||||
);
|
||||
const allowed = [
|
||||
"COMMAND_FAILED_curl_22",
|
||||
"COMMAND_FAILED_curl_7",
|
||||
"COMMAND_FAILED_curl_35",
|
||||
"READINESS_TIMEOUT_API1",
|
||||
"READINESS_TIMEOUT_API2",
|
||||
"PUBLIC_READINESS_FAILED",
|
||||
"INVALID_SERVICE_NETWORK",
|
||||
"INVALID_SERVICE_ID",
|
||||
"MATRIX_POSITIVE_API1-GATEWAY",
|
||||
"MATRIX_POSITIVE_API2-GATEWAY",
|
||||
"NEGATIVE_FAILED_FOR_UNEXPECTED_REASON",
|
||||
];
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
cause: allowed.includes(error.message) ? error.message : "OTHER_PRIVATE",
|
||||
}),
|
||||
);
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
const ids = await compose(["ps", "-a", "-q", service]);
|
||||
for (const id of ids.out.trim().split(/\s+/).filter(Boolean)) {
|
||||
const state = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
const logs = await run(["docker", "logs", id], { allowFailure: true }),
|
||||
events: Record<string, number> = {};
|
||||
for (const line of (logs.out + "\n" + logs.err).split("\n")) {
|
||||
try {
|
||||
const event = JSON.parse(line).event;
|
||||
if (["secret_freshness_failed"].includes(event))
|
||||
events[event] = (events[event] ?? 0) + 1;
|
||||
} catch {}
|
||||
}
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service,
|
||||
running: state.State.Running,
|
||||
exit: state.State.ExitCode,
|
||||
restarts: state.RestartCount,
|
||||
events,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local } from "./runtime";
|
||||
const allowed = [
|
||||
"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_HANDSHAKE_FAILURE",
|
||||
"ERR_SSL_TLSV1_ALERT_ACCESS_DENIED",
|
||||
"ERR_SSL_TLSV1_ALERT_DECRYPT_ERROR",
|
||||
"ERR_SSL_TLSV1_ALERT_DECODE_ERROR",
|
||||
"ECONNRESET",
|
||||
"EPROTO",
|
||||
"EPIPE",
|
||||
"UNCLASSIFIED_TLS_ERROR",
|
||||
"ERR_TLS_CERT_ALTNAME_INVALID",
|
||||
"SELF_SIGNED_CERT_IN_CHAIN",
|
||||
];
|
||||
for (const name of await readdir(resolve(local, "diagnostics"))) {
|
||||
if (!name.startsWith("tls-negative-")) continue;
|
||||
const value = JSON.parse(
|
||||
await readFile(resolve(local, "diagnostics", name), "utf8"),
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
kind: ["trust", "client", "role"].includes(value.kind)
|
||||
? value.kind
|
||||
: "OTHER",
|
||||
code: allowed.includes(value.code) ? value.code : "OTHER",
|
||||
unexpected_success: value.message === "TLS_NEGATIVE_UNEXPECTED_SUCCESS",
|
||||
timeout: value.message === "TRANSPORT_TIMEOUT",
|
||||
certificate_required: /certificate required/i.test(value.message),
|
||||
unknown_ca: /unknown ca/i.test(value.message),
|
||||
bad_certificate: /bad certificate/i.test(value.message),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { compose, run, local, privateWrite } from "./runtime";
|
||||
import { resolve } from "node:path";
|
||||
const categories = [
|
||||
"Permission denied",
|
||||
"Operation not permitted",
|
||||
"Unknown command or category name",
|
||||
"Failed trying to load the ACL",
|
||||
"Syntax error",
|
||||
"FATAL",
|
||||
"No such file or directory",
|
||||
"cannot change permissions",
|
||||
"invalid value",
|
||||
"not a valid",
|
||||
"unknown flag",
|
||||
"unrecognized configuration parameter",
|
||||
"could not load",
|
||||
"could not access",
|
||||
"out of memory",
|
||||
"Address already in use",
|
||||
"cannot open",
|
||||
"server key file has group or world access",
|
||||
"server key file must be owned",
|
||||
"invalid connection type",
|
||||
];
|
||||
for (const service of Bun.argv.slice(2)) {
|
||||
const logs = await compose(["logs", "--no-color", "--tail", "80", service], {
|
||||
allowFailure: true,
|
||||
});
|
||||
await privateWrite(
|
||||
resolve(local, "diagnostics", service + "-logs.txt"),
|
||||
logs.out + logs.err,
|
||||
);
|
||||
const content = logs.out + logs.err;
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service,
|
||||
exit: logs.code,
|
||||
categories: categories.filter((x) =>
|
||||
content.toLowerCase().includes(x.toLowerCase()),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
import { createGitProofProducer, proofHash } from "./git-tracking-proof";
|
||||
import {
|
||||
gitProofSourceSnapshot,
|
||||
gitProofSourceDirectories,
|
||||
gitProofRootFiles,
|
||||
} from "./git-tracking-source";
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/Users/rey/mtuci/vp/lab7",
|
||||
"CANONICAL_MAC_GIT_PRODUCER_REQUIRED",
|
||||
);
|
||||
requireThat(
|
||||
(
|
||||
await run(["git", "-C", root, "rev-parse", "--show-toplevel"])
|
||||
).out.trim() === root,
|
||||
"WRONG_CANONICAL_GIT_REPOSITORY",
|
||||
);
|
||||
const proof = await createGitProofProducer({
|
||||
query: async (args) => {
|
||||
const r = await run(args, { allowFailure: true });
|
||||
return { code: r.code, stdout: r.out };
|
||||
},
|
||||
head: async () =>
|
||||
(await run(["git", "-C", root, "rev-parse", "HEAD"])).out.trim(),
|
||||
snapshot: () => gitProofSourceSnapshot(root),
|
||||
})(root);
|
||||
const content = Buffer.from(
|
||||
JSON.stringify(
|
||||
{
|
||||
...proof,
|
||||
source_scope: {
|
||||
kind: "canonical operational source and public contracts",
|
||||
directories: gitProofSourceDirectories,
|
||||
root_files: gitProofRootFiles,
|
||||
excludes:
|
||||
"mutable evidence, submission, private runtime and nonoperational documents",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
if (Bun.argv.includes("--check")) {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
state: "PASS_CANONICAL_GIT_SOURCE_CAPTURE_GUARDS",
|
||||
head: proof.head,
|
||||
source_files: Object.keys(proof.files).length,
|
||||
source_generation_sha256: proof.source_generation_sha256,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const path =
|
||||
"evidence/openbao/canonical-git-proof-" + crypto.randomUUID() + ".json";
|
||||
await mkdir(resolve(root, "evidence/openbao"), { recursive: true });
|
||||
await writeFile(resolve(root, path), content, { flag: "wx", mode: 0o644 });
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
path,
|
||||
sha256: proofHash(content),
|
||||
source_files: Object.keys(proof.files).length,
|
||||
source_generation_sha256: proof.source_generation_sha256,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (import.meta.main)
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
try {
|
||||
const exceptions = new Set([
|
||||
".gitignore",
|
||||
".dockerignore",
|
||||
"REPORT.md",
|
||||
"security/THREAT_MODEL.md",
|
||||
"contracts/trust-matrix.md",
|
||||
]),
|
||||
files: Record<string, string> = {};
|
||||
const head = (await run(["git", "rev-parse", "HEAD"])).out.trim();
|
||||
for (const path of (await run(["git", "ls-files", "-z"])).out
|
||||
.split("\0")
|
||||
.filter(Boolean)) {
|
||||
if (exceptions.has(path)) continue;
|
||||
const child = Bun.spawn(["git", "show", "HEAD:" + path], {
|
||||
cwd: root,
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
});
|
||||
const [bytes, stderr, exit] = await Promise.all([
|
||||
new Response(child.stdout).arrayBuffer(),
|
||||
new Response(child.stderr).text(),
|
||||
child.exited,
|
||||
]);
|
||||
requireThat(exit === 0, "PUBLIC_BASELINE_UNREADABLE");
|
||||
requireThat(
|
||||
Buffer.from(bytes).equals(await readFile(resolve(root, path))),
|
||||
"PUBLIC_BASELINE_DRIFT",
|
||||
);
|
||||
files[path] = createHash("sha256")
|
||||
.update(new Uint8Array(bytes))
|
||||
.digest("hex");
|
||||
}
|
||||
await writeFile(
|
||||
resolve(root, "PUBLIC-BASELINE.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
original_head: head,
|
||||
permitted_student_templates: [...exceptions],
|
||||
files,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_ORIGINAL_PUBLIC_BYTES_MATCH_HEAD");
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
export type ReplicaService = "api1" | "api2";
|
||||
export type ReplicaBaseline = Record<
|
||||
ReplicaService,
|
||||
{ container: string; alias: string }
|
||||
>;
|
||||
export type FailoverProof = {
|
||||
operation_id: string;
|
||||
attempt_id: string;
|
||||
service: ReplicaService;
|
||||
target_alias: string;
|
||||
container: string;
|
||||
before_running: boolean;
|
||||
running: boolean;
|
||||
volumes_removed: boolean;
|
||||
};
|
||||
export function failoverReceiptPath(operation: string, attempt: string) {
|
||||
if (
|
||||
![operation, attempt].every((x) =>
|
||||
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(x),
|
||||
)
|
||||
)
|
||||
throw Error("FAILOVER_OPERATION_INVALID");
|
||||
return "evidence/security/failover-" + operation + "-" + attempt + ".json";
|
||||
}
|
||||
export function createFailoverReader(ports: {
|
||||
read: (path: string) => Promise<unknown>;
|
||||
}) {
|
||||
if (typeof ports?.read !== "function")
|
||||
throw Error("FAILOVER_READ_PORT_REQUIRED");
|
||||
return async (
|
||||
operation: string,
|
||||
attempt: string,
|
||||
baseline: ReplicaBaseline,
|
||||
) => {
|
||||
const path = failoverReceiptPath(operation, attempt),
|
||||
raw = await ports.read(path);
|
||||
if (!raw || typeof raw !== "object") throw Error("FAILOVER_PROOF_INVALID");
|
||||
const proof = raw as FailoverProof;
|
||||
if (proof.operation_id !== operation || proof.attempt_id !== attempt)
|
||||
throw Error("FAILOVER_WRONG_OPERATION");
|
||||
if (proof.service !== "api1" && proof.service !== "api2")
|
||||
throw Error("FAILOVER_SERVICE_INVALID");
|
||||
const expected = baseline[proof.service];
|
||||
if (
|
||||
!expected ||
|
||||
proof.container !== expected.container ||
|
||||
proof.target_alias !== expected.alias
|
||||
)
|
||||
throw Error("FAILOVER_TARGET_MISMATCH");
|
||||
if (
|
||||
proof.before_running !== true ||
|
||||
proof.running !== false ||
|
||||
proof.volumes_removed !== false
|
||||
)
|
||||
throw Error("FAILOVER_STOP_NOT_PROVED");
|
||||
return { path, proof };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { run, safeFailure, privateWrite, local } from "./runtime";
|
||||
import { resolve } from "node:path";
|
||||
let stage = "GO_FORMAT";
|
||||
try {
|
||||
await run([
|
||||
"/home/rey/.local/share/mise/installs/go/1.27.2/bin/gofmt",
|
||||
"-w",
|
||||
"scripts/s3-control.go",
|
||||
]);
|
||||
stage = "DASHBOARD_GENERATE";
|
||||
await run([process.execPath, "scripts/telemetry-dashboard.ts"]);
|
||||
stage = "NATIVE_FORMAT";
|
||||
await run([process.execPath, "scripts/format-check.ts", "--write"]);
|
||||
stage = "NONWRITING_SOURCE_CHECKS";
|
||||
await run([process.execPath, "scripts/validate-source.ts"]);
|
||||
stage = "EXACT_BINARY_BUILD";
|
||||
await run([process.execPath, "scripts/preflight-build.ts"]);
|
||||
console.log("PASS_FINAL_NONWRITING_CHECKS_AND_EXACT_BINARY_BUILD");
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(() =>
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/final-source-check-error.json"),
|
||||
JSON.stringify({
|
||||
stage,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
}),
|
||||
),
|
||||
),
|
||||
]);
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, run, compose, requireThat, safeFailure } from "./runtime";
|
||||
import { preflightBuild, verifyBackendHandover } from "./preflight-build";
|
||||
import { provisionS3 } from "./s3-provision";
|
||||
import {
|
||||
assertAcceptedGeneration,
|
||||
createEvidencePreserver,
|
||||
} from "./checkpoint-guards";
|
||||
try {
|
||||
const summary = JSON.parse(
|
||||
await readFile(resolve(root, "evidence/preflight/summary.json"), "utf8"),
|
||||
);
|
||||
requireThat(summary.state === "PASS", "CACHED_PREFLIGHT_NOT_ACCEPTED");
|
||||
const accepted = summary.accepted_generation;
|
||||
requireThat(
|
||||
accepted && typeof accepted.source_handover_text === "string",
|
||||
"ACCEPTED_GENERATION_MISMATCH",
|
||||
);
|
||||
const sourceBytes = Buffer.from(accepted.source_handover_text),
|
||||
build = accepted.build_receipt;
|
||||
assertAcceptedGeneration(accepted, sourceBytes, build);
|
||||
const lease = await verifyBackendHandover();
|
||||
requireThat(
|
||||
lease.sha256 === accepted.source_handover_sha256,
|
||||
"ACCEPTED_GENERATION_MISMATCH",
|
||||
);
|
||||
const preserve = createEvidencePreserver({
|
||||
writeExclusive: (path, bytes) =>
|
||||
writeFile(path, bytes, { flag: "wx", mode: 0o600 }),
|
||||
read: (path) => readFile(path),
|
||||
});
|
||||
const prefix = "checked" + accepted.source_files_verified;
|
||||
await preserve(
|
||||
resolve(root, "evidence/preflight", prefix + "-source.json"),
|
||||
sourceBytes,
|
||||
);
|
||||
await preserve(
|
||||
resolve(root, "evidence/preflight", prefix + "-build.json"),
|
||||
Buffer.from(JSON.stringify(build, null, 2) + "\n"),
|
||||
);
|
||||
await lease.verify();
|
||||
await preflightBuild();
|
||||
const password = await readFile(
|
||||
resolve(root, ".local-preflight-key"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(/^[a-f0-9]{64}$/.test(password), "INVALID_PREFLIGHT_SESSION_KEY");
|
||||
const receipts = resolve(local, "operator/s3-receipts"),
|
||||
before = new Set(await readdir(receipts));
|
||||
await provisionS3(password);
|
||||
let completed = 0;
|
||||
for (const name of await readdir(receipts)) {
|
||||
if (before.has(name)) continue;
|
||||
const value = JSON.parse(await readFile(resolve(receipts, name), "utf8"));
|
||||
if (value.stage === "bootstrap" && value.state === "COMPLETE") completed++;
|
||||
}
|
||||
requireThat(completed === 1, "S3_BOOTSTRAP_RECEIPT_NOT_COMPLETED");
|
||||
const ids = (await compose(["ps", "-a", "-q"])).out
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
for (const id of ids) {
|
||||
const value = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
requireThat(
|
||||
value.Config.Labels["com.docker.compose.project"] ===
|
||||
"mtuci-vp7-security",
|
||||
"FINAL_STOP_PROJECT_MISMATCH",
|
||||
);
|
||||
}
|
||||
await compose(["--profile", "*", "down", "--remove-orphans"]);
|
||||
const remaining = await run([
|
||||
"docker",
|
||||
"ps",
|
||||
"-a",
|
||||
"-q",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=mtuci-vp7-security",
|
||||
]);
|
||||
requireThat(!remaining.out.trim(), "OWNED_CONTAINERS_REMAIN");
|
||||
await writeFile(
|
||||
resolve(root, "evidence/preflight/finalization.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
new_sdk_bootstrap_receipt_complete: true,
|
||||
owned_containers_remaining: 0,
|
||||
bind_data_retained: true,
|
||||
private_test_key_retained_for_addressed_cleanup: true,
|
||||
native_bao_accepted: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_UPDATED_SDK_RECEIPT_AND_OWNED_STAND_TEARDOWN");
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
try {
|
||||
const files: string[] = [];
|
||||
for (const dir of ["scripts", "student-tests", "infra", "config"]) {
|
||||
const glob = new Bun.Glob("**/*");
|
||||
for await (const file of glob.scan({
|
||||
cwd: root + "/" + dir,
|
||||
onlyFiles: true,
|
||||
}))
|
||||
if (/\.(ts|json|yaml)$/.test(file)) files.push(dir + "/" + file);
|
||||
}
|
||||
const mode = Bun.argv.includes("--write") ? [] : ["--check"];
|
||||
await run([process.execPath, "fmt", ...mode, ...files]);
|
||||
console.log(
|
||||
mode.length
|
||||
? "PASS_NATIVE_FORMAT_NONWRITING_CHECK"
|
||||
: "FORMATTED_OWNED_IMPLEMENTATION_FILES",
|
||||
);
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root } from "./runtime";
|
||||
for (const role of ["api", "worker"]) {
|
||||
const value = `pid_file = "/tmp/bao-agent.pid"
|
||||
log_level = "error"
|
||||
vault {
|
||||
address = "https://openbao:8200"
|
||||
ca_cert = "/pki/ca.crt"
|
||||
}
|
||||
auto_auth {
|
||||
method "cert" {
|
||||
mount_path = "auth/cert"
|
||||
config = {
|
||||
name = "${role}"
|
||||
ca_cert = "/pki/ca.crt"
|
||||
client_cert = "/pki/cert.pem"
|
||||
client_key = "/pki/key.pem"
|
||||
reload = true
|
||||
}
|
||||
}
|
||||
}
|
||||
template_config {
|
||||
static_secret_render_interval = "5s"
|
||||
exit_on_retry_failure = false
|
||||
}
|
||||
${[
|
||||
["database_url", "database_url"],
|
||||
["cache_url", "cache_url"],
|
||||
["s3.json", "s3_json"],
|
||||
...(role === "worker" ? [["publisher_url", "publisher_url"]] : []),
|
||||
["freshness", "timestamp"],
|
||||
]
|
||||
.map(
|
||||
([file, key]) => `template {
|
||||
destination = "/run/app/${file}"
|
||||
perms = "0600"
|
||||
backup = false
|
||||
error_on_missing_key = true
|
||||
contents = <<EOT
|
||||
{{ with secret "kv/data/${role}" }}${key === "timestamp" ? "{{ timestamp }}" : "{{ .Data.data." + key + " }}"}{{ end }}
|
||||
EOT
|
||||
}
|
||||
`,
|
||||
)
|
||||
.join("")}`;
|
||||
await writeFile(resolve(root, "infra/openbao", role + "-agent.hcl"), value);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { type GitTrackingSource } from "./git-tracking-proof";
|
||||
export function parseGitProofCLI(args: string[]): GitTrackingSource {
|
||||
const paths = args.filter((s) => s === "--git-proof").length,
|
||||
hashes = args.filter((s) => s === "--git-proof-sha").length;
|
||||
if (paths === 0 && hashes === 0) return { kind: "native-git" };
|
||||
const path = args[args.indexOf("--git-proof") + 1],
|
||||
sha256 = args[args.indexOf("--git-proof-sha") + 1];
|
||||
if (
|
||||
paths !== 1 ||
|
||||
hashes !== 1 ||
|
||||
typeof path !== "string" ||
|
||||
path.length === 0 ||
|
||||
path.startsWith("--") ||
|
||||
/[\r\n\0]/.test(path) ||
|
||||
!sha256 ||
|
||||
!/^[a-f0-9]{64}$/.test(sha256)
|
||||
)
|
||||
throw Error("GIT_PROOF_CLI_INVALID");
|
||||
return { kind: "canonical-proof", path, sha256 };
|
||||
}
|
||||
export function createAcceptCommand(ports: {
|
||||
verifyProof: (
|
||||
proof: Extract<GitTrackingSource, { kind: "canonical-proof" }>,
|
||||
) => Promise<unknown>;
|
||||
password: () => Promise<string>;
|
||||
accept: (password: string, proof: GitTrackingSource) => Promise<void>;
|
||||
}) {
|
||||
if (
|
||||
[ports?.verifyProof, ports?.password, ports?.accept].some(
|
||||
(p) => typeof p !== "function",
|
||||
)
|
||||
)
|
||||
throw Error("ACCEPT_COMMAND_PORTS_REQUIRED");
|
||||
return async (args: string[]) => {
|
||||
const proof = parseGitProofCLI(args);
|
||||
if (proof.kind === "canonical-proof") await ports.verifyProof(proof);
|
||||
await ports.accept(await ports.password(), proof);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { createHash } from "node:crypto";
|
||||
export type SourceHashes = Record<string, string>;
|
||||
export const privateTrackingPatterns = [".env", ".local/**", "*.key", "*.pem"];
|
||||
export type GitTrackingSource =
|
||||
| { kind: "native-git" }
|
||||
| { kind: "canonical-proof"; path: string; sha256: string };
|
||||
export const sourceGeneration = (files: SourceHashes) =>
|
||||
createHash("sha256")
|
||||
.update(
|
||||
JSON.stringify(
|
||||
Object.keys(files)
|
||||
.sort()
|
||||
.map((path) => [path, files[path]]),
|
||||
),
|
||||
)
|
||||
.digest("hex");
|
||||
export const proofHash = (bytes: Uint8Array) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
function validFiles(files: unknown): files is SourceHashes {
|
||||
return (
|
||||
!!files &&
|
||||
typeof files === "object" &&
|
||||
!Array.isArray(files) &&
|
||||
Object.keys(files).length > 0 &&
|
||||
Object.keys(files).length <= 10000 &&
|
||||
Object.entries(files).every(
|
||||
([path, sha]) =>
|
||||
path.length <= 1024 &&
|
||||
!path.startsWith("/") &&
|
||||
!path.split("/").includes("..") &&
|
||||
!/[\r\n\0]/.test(path) &&
|
||||
typeof sha === "string" &&
|
||||
/^[a-f0-9]{64}$/.test(sha),
|
||||
)
|
||||
);
|
||||
}
|
||||
export function createGitProofProducer(ports: {
|
||||
query: (args: string[]) => Promise<{ code: number; stdout: string }>;
|
||||
head: () => Promise<string>;
|
||||
snapshot: () => Promise<SourceHashes>;
|
||||
}) {
|
||||
if (
|
||||
!ports ||
|
||||
[ports.query, ports.head, ports.snapshot].some(
|
||||
(p) => typeof p !== "function",
|
||||
)
|
||||
)
|
||||
throw Error("GIT_PRODUCER_PORTS_REQUIRED");
|
||||
return async (repository: string) => {
|
||||
const query = [
|
||||
"git",
|
||||
"-C",
|
||||
repository,
|
||||
"ls-files",
|
||||
"-z",
|
||||
"--",
|
||||
...privateTrackingPatterns,
|
||||
],
|
||||
head = await ports.head(),
|
||||
result = await ports.query(query),
|
||||
files = await ports.snapshot();
|
||||
if (
|
||||
!repository.startsWith("/") ||
|
||||
!/^[a-f0-9]{40}$/.test(head) ||
|
||||
!validFiles(files)
|
||||
)
|
||||
throw Error("GIT_CAPTURE_INVALID");
|
||||
if (result.code !== 0 || result.stdout !== "")
|
||||
throw Error("CANONICAL_GIT_PRIVATE_TRACKING");
|
||||
const second = await ports.query(query),
|
||||
afterHead = await ports.head(),
|
||||
after = await ports.snapshot();
|
||||
if (
|
||||
second.code !== 0 ||
|
||||
second.stdout !== "" ||
|
||||
afterHead !== head ||
|
||||
!validFiles(after) ||
|
||||
sourceGeneration(after) !== sourceGeneration(files)
|
||||
)
|
||||
throw Error("GIT_CAPTURE_CHANGED");
|
||||
return {
|
||||
kind: "CANONICAL_GIT_TRACKING_V1",
|
||||
canonical_repository: repository,
|
||||
query,
|
||||
head,
|
||||
result: {
|
||||
exit_code: result.code,
|
||||
stdout_base64: Buffer.from(result.stdout).toString("base64"),
|
||||
},
|
||||
source_generation_sha256: sourceGeneration(files),
|
||||
files,
|
||||
};
|
||||
};
|
||||
}
|
||||
export function createGitProofReader(ports: {
|
||||
read: () => Promise<Uint8Array>;
|
||||
snapshot: () => Promise<SourceHashes>;
|
||||
}) {
|
||||
if (
|
||||
!ports ||
|
||||
[ports.read, ports.snapshot].some((p) => typeof p !== "function")
|
||||
)
|
||||
throw Error("GIT_READER_PORTS_REQUIRED");
|
||||
return async (expectedSHA: string) => {
|
||||
const bytes = await ports.read();
|
||||
if (!/^[a-f0-9]{64}$/.test(expectedSHA) || proofHash(bytes) !== expectedSHA)
|
||||
throw Error("GIT_PROOF_SHA_MISMATCH");
|
||||
if (bytes.length > 2 * 1024 * 1024) throw Error("GIT_PROOF_INVALID");
|
||||
let proof: any;
|
||||
try {
|
||||
proof = JSON.parse(Buffer.from(bytes).toString());
|
||||
} catch {
|
||||
throw Error("GIT_PROOF_INVALID");
|
||||
}
|
||||
if (
|
||||
proof?.kind !== "CANONICAL_GIT_TRACKING_V1" ||
|
||||
typeof proof.canonical_repository !== "string" ||
|
||||
!proof.canonical_repository.startsWith("/") ||
|
||||
!/^[a-f0-9]{40}$/.test(proof.head) ||
|
||||
proof.result?.exit_code !== 0 ||
|
||||
proof.result?.stdout_base64 !== "" ||
|
||||
!validFiles(proof.files) ||
|
||||
JSON.stringify(proof.query) !==
|
||||
JSON.stringify([
|
||||
"git",
|
||||
"-C",
|
||||
proof.canonical_repository,
|
||||
"ls-files",
|
||||
"-z",
|
||||
"--",
|
||||
...privateTrackingPatterns,
|
||||
]) ||
|
||||
proof.source_generation_sha256 !== sourceGeneration(proof.files)
|
||||
)
|
||||
throw Error("GIT_PROOF_INVALID");
|
||||
const current = await ports.snapshot();
|
||||
if (
|
||||
!validFiles(current) ||
|
||||
sourceGeneration(current) !== proof.source_generation_sha256
|
||||
)
|
||||
throw Error("GIT_PROOF_SOURCE_MISMATCH");
|
||||
return {
|
||||
proof_sha256: proofHash(bytes),
|
||||
source_generation_sha256: proof.source_generation_sha256,
|
||||
tracked_private_files: 0,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { open, readFile, readdir, stat } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { resolve, relative } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { root, local, privateWrite, requireThat } from "./runtime";
|
||||
import { createGitProofReader, type SourceHashes } from "./git-tracking-proof";
|
||||
export const gitProofSourceDirectories = [
|
||||
"backend",
|
||||
"scripts",
|
||||
"student-tests",
|
||||
"config",
|
||||
"infra",
|
||||
"contracts",
|
||||
"tests",
|
||||
"examples",
|
||||
".github",
|
||||
];
|
||||
export const gitProofRootFiles = [
|
||||
"Dockerfile",
|
||||
"Dockerfile.example",
|
||||
"compose.yaml",
|
||||
"compose.example.yaml",
|
||||
"package.json",
|
||||
"bun.lock",
|
||||
"tsconfig.json",
|
||||
"Makefile",
|
||||
"PUBLIC-BASELINE.json",
|
||||
"BACKEND-READY.json",
|
||||
".dockerignore",
|
||||
".gitignore",
|
||||
".env.example",
|
||||
"lab.json",
|
||||
"requirements-dev.txt",
|
||||
"OPENBAO-IMAGE.json",
|
||||
];
|
||||
export async function gitProofSourceSnapshot(
|
||||
directory: string,
|
||||
): Promise<SourceHashes> {
|
||||
const result: SourceHashes = {},
|
||||
hash = (bytes: Uint8Array) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
async function add(path: string) {
|
||||
const info = await stat(path);
|
||||
requireThat(
|
||||
info.isFile() && info.size <= 20 * 1024 * 1024,
|
||||
"GIT_SOURCE_FILE_INVALID",
|
||||
);
|
||||
result[relative(directory, path)] = hash(await readFile(path));
|
||||
}
|
||||
async function walk(path: string) {
|
||||
for (const entry of await readdir(path, { withFileTypes: true })) {
|
||||
if (
|
||||
[
|
||||
"node_modules",
|
||||
"__pycache__",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
".ruff_cache",
|
||||
].includes(entry.name) ||
|
||||
/\.(pyc|pyo)$/.test(entry.name)
|
||||
)
|
||||
continue;
|
||||
const p = resolve(path, entry.name);
|
||||
if (entry.isDirectory()) await walk(p);
|
||||
else {
|
||||
requireThat(entry.isFile(), "GIT_SOURCE_NONREGULAR");
|
||||
await add(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const name of gitProofSourceDirectories)
|
||||
await walk(resolve(directory, name));
|
||||
for (const name of gitProofRootFiles) await add(resolve(directory, name));
|
||||
return Object.fromEntries(
|
||||
Object.keys(result)
|
||||
.sort()
|
||||
.map((p) => [p, result[p]]),
|
||||
);
|
||||
}
|
||||
async function boundedProof(path: string) {
|
||||
const handle = await open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
let primary = false;
|
||||
try {
|
||||
requireThat((await handle.stat()).isFile(), "GIT_PROOF_NOT_REGULAR");
|
||||
const buffer = Buffer.alloc(2 * 1024 * 1024 + 1);
|
||||
let position = 0;
|
||||
while (position < buffer.length) {
|
||||
const r = await handle.read(
|
||||
buffer,
|
||||
position,
|
||||
buffer.length - position,
|
||||
null,
|
||||
);
|
||||
if (r.bytesRead === 0) break;
|
||||
position += r.bytesRead;
|
||||
}
|
||||
requireThat(position <= 2 * 1024 * 1024, "GIT_PROOF_TOO_LARGE");
|
||||
return buffer.subarray(0, position);
|
||||
} catch (error) {
|
||||
primary = true;
|
||||
throw error;
|
||||
} finally {
|
||||
try {
|
||||
await handle.close();
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/git-proof-close.json"),
|
||||
JSON.stringify({ code: "GIT_PROOF_CLOSE_FAILED" }),
|
||||
),
|
||||
]);
|
||||
if (!primary) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
export async function readCanonicalGitProof(reference: {
|
||||
path: string;
|
||||
sha256: string;
|
||||
}) {
|
||||
requireThat(
|
||||
/^evidence\/openbao\/canonical-git-proof-[a-f0-9-]+\.json$/.test(
|
||||
reference.path,
|
||||
),
|
||||
"GIT_PROOF_PATH_INVALID",
|
||||
);
|
||||
return createGitProofReader({
|
||||
read: () => boundedProof(resolve(root, reference.path)),
|
||||
snapshot: () => gitProofSourceSnapshot(root),
|
||||
})(reference.sha256);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,148 @@
|
||||
import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { root, local, run, requireThat, safeFailure } from "./runtime";
|
||||
import { createEvidencePreserver } from "./checkpoint-guards";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
const sourceRoot =
|
||||
"/mnt/data/home/bench-saves/mtuci-vp-remaining-20261115/lab6/.local/grafana-approved-31251471-ca6a-4d2e-b823-8e42ff9fefa5";
|
||||
const pluginRoot =
|
||||
"/mnt/data/home/bench-saves/mtuci-vp-remaining-20261115/lab6/.local/grafana-plugins/openobserve";
|
||||
const imageID =
|
||||
"sha256:1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e";
|
||||
const ownAlias = "mtuci-vp7-grafana-cache:13.3.1-1c88285f1dd3";
|
||||
const hash = (bytes: Uint8Array) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"GRAFANA_CACHE_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const lease = await verifyBackendHandover();
|
||||
const readyPath = resolve(sourceRoot, "CACHE-READY.json"),
|
||||
readyBytes = await readFile(readyPath),
|
||||
ready = JSON.parse(readyBytes.toString());
|
||||
requireThat(
|
||||
ready.imported === true &&
|
||||
ready.imageID === imageID &&
|
||||
ready.platform === "linux/amd64" &&
|
||||
ready.nativeVersionExit === 0 &&
|
||||
ready.nativeVersionOutput === "grafana version 13.3.1" &&
|
||||
ready.pluginId === "openobserve" &&
|
||||
ready.pluginVersion === "1.0.1" &&
|
||||
ready.pluginRequiresGrafana === ">=12.4.0" &&
|
||||
ready.upstreamUnmodified === true,
|
||||
"GRAFANA_CACHE_HANDOVER_MISMATCH",
|
||||
);
|
||||
const pluginBytes = await readFile(
|
||||
resolve(sourceRoot, "openobserve-1.0.1.zip"),
|
||||
);
|
||||
requireThat(
|
||||
hash(pluginBytes) ===
|
||||
"e0c2cbcc7cf6d05bcfaa606db39e52249eb0dd234376e45a3f896353831c2fd5" &&
|
||||
ready.pluginArchiveSHA256 === hash(pluginBytes),
|
||||
"GRAFANA_PLUGIN_ARCHIVE_HASH_MISMATCH",
|
||||
);
|
||||
const image = JSON.parse(
|
||||
(await run(["docker", "image", "inspect", ready.alias])).out,
|
||||
)[0];
|
||||
requireThat(
|
||||
image.Id === imageID &&
|
||||
image.Os === "linux" &&
|
||||
image.Architecture === "amd64",
|
||||
"GRAFANA_CACHE_IMAGE_MISMATCH",
|
||||
);
|
||||
const existing = await run(["docker", "image", "inspect", ownAlias], {
|
||||
allowFailure: true,
|
||||
});
|
||||
if (existing.code === 0)
|
||||
requireThat(
|
||||
JSON.parse(existing.out)[0].Id === imageID,
|
||||
"GRAFANA_OWN_ALIAS_CONFLICT",
|
||||
);
|
||||
else await run(["docker", "image", "tag", imageID, ownAlias]);
|
||||
const preserve = createEvidencePreserver({
|
||||
read: readFile,
|
||||
writeExclusive: (path, bytes) =>
|
||||
writeFile(path, bytes, { flag: "wx", mode: 0o644 }),
|
||||
});
|
||||
const files = [
|
||||
"plugin.json",
|
||||
"module.js",
|
||||
"module.js.map",
|
||||
"gpx_openobserve_linux_amd64",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"go_plugin_build_manifest",
|
||||
"img/logo.png",
|
||||
];
|
||||
const copied: Record<string, string> = {};
|
||||
for (const path of files) {
|
||||
const bytes = await readFile(resolve(pluginRoot, path));
|
||||
if (ready.filesSHA256[path])
|
||||
requireThat(
|
||||
hash(bytes) === ready.filesSHA256[path],
|
||||
"GRAFANA_PLUGIN_SOURCE_DRIFT",
|
||||
);
|
||||
if (path === "gpx_openobserve_linux_amd64")
|
||||
requireThat(
|
||||
hash(bytes) ===
|
||||
"dc91fdfaf25708cb2573c4e533754cb5cc5ecd02d43beb7ee21bee06fbc09c50",
|
||||
"GRAFANA_PLUGIN_BACKEND_HASH_MISMATCH",
|
||||
);
|
||||
const target = resolve(local, "plugins/openobserve", path);
|
||||
await mkdir(resolve(target, ".."), { recursive: true, mode: 0o755 });
|
||||
await preserve(target, bytes);
|
||||
if (path === "gpx_openobserve_linux_amd64") await chmod(target, 0o755);
|
||||
copied[path] = hash(await readFile(target));
|
||||
requireThat(copied[path] === hash(bytes), "GRAFANA_PLUGIN_COPY_DRIFT");
|
||||
}
|
||||
requireThat(
|
||||
hash(await readFile(readyPath)) === hash(readyBytes),
|
||||
"GRAFANA_CACHE_HANDOVER_CHANGED",
|
||||
);
|
||||
requireThat(
|
||||
JSON.parse((await run(["docker", "image", "inspect", ownAlias])).out)[0]
|
||||
.Id === imageID,
|
||||
"GRAFANA_OWN_ALIAS_POSTGUARD_FAILED",
|
||||
);
|
||||
await lease.verify();
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/grafana/cache-freeze-" + crypto.randomUUID() + ".json",
|
||||
);
|
||||
await mkdir(resolve(receipt, ".."), { recursive: true });
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_OWN_GRAFANA_CACHE_NO_PULL",
|
||||
source_receipt: { path: readyPath, sha256: hash(readyBytes) },
|
||||
image_id: imageID,
|
||||
own_alias: ownAlias,
|
||||
platform: "linux/amd64",
|
||||
version: "13.3.1",
|
||||
plugin_archive_sha256: hash(pluginBytes),
|
||||
plugin_id: "openobserve",
|
||||
plugin_version: "1.0.1",
|
||||
copied_files: copied,
|
||||
upstream_modified: false,
|
||||
source_cache_mutated: false,
|
||||
new_network_bytes: 0,
|
||||
backend_handover_sha256: lease.sha256,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
console.log("PASS_OWN_GRAFANA_ALIAS_AND_PLUGIN_NO_SECOND_DOWNLOAD");
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { requireThat } from "./runtime";
|
||||
type Request = (path: string) => Promise<{ status: number; body: any }>;
|
||||
export async function readGrafanaDatasources(request: Request) {
|
||||
requireThat(
|
||||
typeof request === "function",
|
||||
"GRAFANA_DATASOURCE_REQUEST_PORT_REQUIRED",
|
||||
);
|
||||
const list = await request("/api/datasources");
|
||||
requireThat(
|
||||
list.status === 200 && Array.isArray(list.body) && list.body.length === 2,
|
||||
"GRAFANA_DATASOURCE_PROVISIONING_FAILED",
|
||||
);
|
||||
const uids = ["prometheus", "openobserve"];
|
||||
for (const uid of uids) {
|
||||
requireThat(
|
||||
list.body.some((d: any) => d.uid === uid && d.basicAuth === true),
|
||||
"GRAFANA_DATASOURCE_PROVISIONING_FAILED",
|
||||
);
|
||||
const detail = await request("/api/datasources/uid/" + uid);
|
||||
requireThat(
|
||||
detail.status === 200 &&
|
||||
detail.body?.uid === uid &&
|
||||
detail.body.basicAuth === true &&
|
||||
detail.body.basicAuthUser === "vp7-query@example.invalid" &&
|
||||
detail.body.secureJsonFields?.basicAuthPassword === true,
|
||||
"GRAFANA_DATASOURCE_PRINCIPAL_MISMATCH",
|
||||
);
|
||||
const health = await request("/api/datasources/uid/" + uid + "/health");
|
||||
requireThat(
|
||||
health.status === 200 && health.body?.status === "OK",
|
||||
"GRAFANA_DATASOURCE_HEALTH_FAILED",
|
||||
);
|
||||
}
|
||||
return uids;
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
import { readFile, writeFile, mkdir, rename } from "node:fs/promises";
|
||||
import { resolve, relative } from "node:path";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
privateWrite,
|
||||
requireThat,
|
||||
} from "./runtime";
|
||||
import { encrypt, decrypt } from "./operator-crypto";
|
||||
import {
|
||||
grafanaRequest,
|
||||
metricFrameValues,
|
||||
assertOriginalGrafanaRules,
|
||||
} from "./grafana";
|
||||
import { HTTP } from "../student-tests/http";
|
||||
import { waitReady } from "../student-tests/wait";
|
||||
import { containerIP } from "./runtime-inspect";
|
||||
import { tlsProbe } from "../student-tests/transport";
|
||||
const components = [
|
||||
"postgres",
|
||||
"broker-gateway",
|
||||
"broker",
|
||||
"s3-gateway",
|
||||
"s3",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"worker-gateway",
|
||||
"lb",
|
||||
"collector-gateway",
|
||||
"collector",
|
||||
];
|
||||
export async function runGrafanaIncidents(
|
||||
password: string,
|
||||
): Promise<Record<string, any>> {
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/grafana/incidents-" + crypto.randomUUID() + ".json",
|
||||
);
|
||||
await mkdir(resolve(receipt, ".."), { recursive: true });
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify({ state: "RUNNING", stage: "CHECKED112_BINARY_GUARD" }),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
let stage = "CHECKED112_BINARY_GUARD",
|
||||
timer: ReturnType<typeof setInterval> | undefined,
|
||||
pending: Promise<void> | undefined,
|
||||
heartbeatFailed = false,
|
||||
started = false,
|
||||
primary: unknown;
|
||||
const proof: Record<string, any> = {
|
||||
native_bao: false,
|
||||
provider: "explicit-operator-files-heartbeat",
|
||||
synthetic_alert_expressions: false,
|
||||
public_smoke_repeated: false,
|
||||
grade5: false,
|
||||
};
|
||||
const save = async (state: string) =>
|
||||
writeFile(
|
||||
receipt,
|
||||
JSON.stringify({ state, stage, ...proof }, null, 2) + "\n",
|
||||
);
|
||||
try {
|
||||
const build = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "evidence/preflight/checked112-build.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const binaries = (
|
||||
await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--pull=never",
|
||||
"--network",
|
||||
"none",
|
||||
"--read-only",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--entrypoint",
|
||||
"/bin/sh",
|
||||
"mtuci-vp7-security-app:local",
|
||||
"-c",
|
||||
"sha256sum /app /worker",
|
||||
])
|
||||
).out
|
||||
.trim()
|
||||
.split("\n");
|
||||
requireThat(
|
||||
binaries.length === 2 &&
|
||||
binaries[0].split(/\s+/)[0] === build.binaries.app &&
|
||||
binaries[1].split(/\s+/)[0] === build.binaries.worker,
|
||||
"GRAFANA_INCIDENT_BINARY_DRIFT",
|
||||
);
|
||||
proof.binary_hashes = {
|
||||
app: build.binaries.app,
|
||||
worker: build.binaries.worker,
|
||||
};
|
||||
stage = "OPERATOR_PROVIDER_FILES";
|
||||
for (const name of ["api1", "api2", "worker"])
|
||||
for (const file of [
|
||||
"database_url",
|
||||
"cache_url",
|
||||
"s3.json",
|
||||
...(name === "worker" ? ["publisher_url"] : []),
|
||||
])
|
||||
requireThat(
|
||||
(await Bun.file(resolve(local, "rendered", name, file)).stat()).size >
|
||||
0,
|
||||
"GRAFANA_INCIDENT_PROVIDER_FILE_MISSING",
|
||||
);
|
||||
const timestamp = async () => {
|
||||
for (const name of ["api1", "api2", "worker"]) {
|
||||
const path = resolve(local, "rendered", name, "freshness"),
|
||||
temporary = path + "." + crypto.randomUUID();
|
||||
await privateWrite(temporary, new Date().toISOString() + "\n");
|
||||
await rename(temporary, path);
|
||||
}
|
||||
};
|
||||
await timestamp();
|
||||
timer = setInterval(() => {
|
||||
if (pending) return;
|
||||
pending = timestamp()
|
||||
.catch(() => {
|
||||
heartbeatFailed = true;
|
||||
})
|
||||
.finally(() => {
|
||||
pending = undefined;
|
||||
});
|
||||
}, 1000);
|
||||
stage = "CACHED_APPLICATION_DEPENDENCIES_START";
|
||||
started = true;
|
||||
await compose(["up", "-d", "--no-build", ...components]);
|
||||
stage = "CURRENT112_APPLICATION_START";
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"--no-build",
|
||||
"--no-deps",
|
||||
"api1",
|
||||
"api2",
|
||||
"worker",
|
||||
]);
|
||||
await waitReady();
|
||||
stage = "ORIGINAL_RULES_NATIVE_READ";
|
||||
const config = Bun.YAML.parse(
|
||||
await readFile(
|
||||
resolve(root, "infra/grafana/provisioning/alerting/messenger.yaml"),
|
||||
"utf8",
|
||||
),
|
||||
) as any;
|
||||
const originals = config.groups[0].rules;
|
||||
const configured = await grafanaRequest("/api/v1/provisioning/alert-rules");
|
||||
requireThat(
|
||||
configured.status === 200,
|
||||
"GRAFANA_INCIDENT_RULES_HTTP_FAILED",
|
||||
);
|
||||
assertOriginalGrafanaRules(configured.body, originals);
|
||||
const http = new HTTP();
|
||||
const resume = Bun.argv
|
||||
.find((value) => value.startsWith("--fixture="))
|
||||
?.slice("--fixture=".length);
|
||||
let actor: any, peer: any, chat: any;
|
||||
if (resume) {
|
||||
stage = "RESUME_EXISTING_PRIVATE_FIXTURE";
|
||||
requireThat(
|
||||
/^\.local\/operator\/grafana-incident-[a-f0-9-]+\.enc$/.test(resume),
|
||||
"GRAFANA_FIXTURE_PATH_INVALID",
|
||||
);
|
||||
const saved = decrypt<any>(
|
||||
await readFile(resolve(root, resume), "utf8"),
|
||||
password,
|
||||
);
|
||||
({ actor, peer, chat } = saved);
|
||||
requireThat(
|
||||
[actor?.id, peer?.id, chat?.id].every(
|
||||
(id) => typeof id === "string" && /^[a-f0-9-]{36}$/.test(id),
|
||||
) &&
|
||||
typeof actor?.token === "string" &&
|
||||
!/[\r\n]/.test(actor.token),
|
||||
"GRAFANA_FIXTURE_SHAPE_INVALID",
|
||||
);
|
||||
await http.call("GET", "/api/v1/chats", 200, { actor: actor.token });
|
||||
} else {
|
||||
stage = "FIXTURE_ACTOR_CREATE_LOGIN";
|
||||
actor = await http.user("grafana-alert");
|
||||
const fixturePath = resolve(
|
||||
local,
|
||||
"operator/grafana-incident-" + crypto.randomUUID() + ".enc",
|
||||
);
|
||||
await writeFile(fixturePath, encrypt({ actor }, password), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
stage = "FIXTURE_PEER_CREATE_LOGIN";
|
||||
peer = await http.user("grafana-peer");
|
||||
await writeFile(fixturePath, encrypt({ actor, peer }, password));
|
||||
stage = "FIXTURE_CHAT_CREATE";
|
||||
chat = (
|
||||
await http.call("POST", "/api/v1/chats", 201, {
|
||||
actor: actor.token,
|
||||
body: {
|
||||
title: "Grafana bounded incidents " + crypto.randomUUID(),
|
||||
member_ids: [actor.id, peer.id],
|
||||
},
|
||||
})
|
||||
).json;
|
||||
await writeFile(fixturePath, encrypt({ actor, peer, chat }, password), {
|
||||
mode: 0o600,
|
||||
});
|
||||
}
|
||||
proof.fixture = {
|
||||
chat_id: chat.id,
|
||||
actor_ids: [actor.id, peer.id],
|
||||
encrypted_credential_capture: true,
|
||||
reused_existing_fixture: Boolean(resume),
|
||||
uploads: [],
|
||||
};
|
||||
const image = new Uint8Array(
|
||||
await readFile(resolve(root, "tests/fixtures/sample.png")),
|
||||
);
|
||||
const upload = async () => {
|
||||
const response = await http.call(
|
||||
"POST",
|
||||
`/api/v1/chats/${chat.id}/attachments?filename=grafana-incident.png`,
|
||||
202,
|
||||
{
|
||||
actor: actor.token,
|
||||
raw: image,
|
||||
headers: { "Content-Type": "image/png" },
|
||||
},
|
||||
);
|
||||
requireThat(
|
||||
response.json?.status === "queued" &&
|
||||
typeof response.json.id === "string",
|
||||
"GRAFANA_INCIDENT_UPLOAD_NOT_QUEUED",
|
||||
);
|
||||
proof.fixture.uploads.push(response.json.id);
|
||||
return response.json.id;
|
||||
};
|
||||
const traffic = () =>
|
||||
http.call("GET", "/api/v1/chats", 200, { actor: actor.token });
|
||||
const readState = async (uid: string) => {
|
||||
const response = await grafanaRequest(
|
||||
"/api/prometheus/grafana/api/v1/rules",
|
||||
);
|
||||
requireThat(
|
||||
response.status === 200 &&
|
||||
response.body?.status === "success" &&
|
||||
Array.isArray(response.body?.data?.groups),
|
||||
"GRAFANA_RULE_STATE_READER_FAILED",
|
||||
);
|
||||
const title = originals.find((r: any) => r.uid === uid)?.title,
|
||||
rule = response.body.data.groups
|
||||
.flatMap((g: any) => g.rules ?? [])
|
||||
.find((r: any) => r.name === title);
|
||||
requireThat(
|
||||
rule && ["inactive", "pending", "firing"].includes(rule.state),
|
||||
"GRAFANA_RULE_STATE_MISSING_OR_UNKNOWN",
|
||||
);
|
||||
requireThat(
|
||||
["ok", "err", "error", "unknown", "nodata", "no_data"].includes(
|
||||
rule.health,
|
||||
),
|
||||
"GRAFANA_RULE_HEALTH_UNKNOWN",
|
||||
);
|
||||
return {
|
||||
uid,
|
||||
state: rule.state,
|
||||
health: rule.health,
|
||||
last_evaluation:
|
||||
typeof rule.lastEvaluation === "string" &&
|
||||
/^\d{4}-\d{2}-\d{2}T[0-9:.]+Z$/.test(rule.lastEvaluation)
|
||||
? rule.lastEvaluation
|
||||
: null,
|
||||
};
|
||||
};
|
||||
const waitState = async (
|
||||
uid: string,
|
||||
wanted: string,
|
||||
action: () => Promise<unknown>,
|
||||
budget = 150000,
|
||||
) => {
|
||||
const begin = Date.now(),
|
||||
states: any[] = [],
|
||||
deadline = begin + budget;
|
||||
const phase = stage;
|
||||
while (Date.now() < deadline) {
|
||||
stage = phase + "_BUSINESS_REQUEST";
|
||||
await action();
|
||||
stage = phase + "_RULE_STATE";
|
||||
const state = await readState(uid);
|
||||
if (
|
||||
!states.length ||
|
||||
states.at(-1).state !== state.state ||
|
||||
states.at(-1).health !== state.health
|
||||
)
|
||||
states.push({ ...state, elapsed_ms: Date.now() - begin });
|
||||
requireThat(
|
||||
state.health !== "error" && state.health !== "err",
|
||||
"GRAFANA_RULE_EVALUATION_ERROR",
|
||||
);
|
||||
if (state.state === wanted && state.health === "ok") {
|
||||
stage = phase + "_RULE_VALUE";
|
||||
const original = originals.find((r: any) => r.uid === uid);
|
||||
const point = Date.now() - 1000;
|
||||
const query = await grafanaRequest("/api/ds/query", {
|
||||
body: {
|
||||
from: String(point - 60000),
|
||||
to: String(point),
|
||||
queries: [
|
||||
{
|
||||
refId: "A",
|
||||
datasource: { uid: "prometheus", type: "prometheus" },
|
||||
expr: original.data[0].model.expr,
|
||||
instant: true,
|
||||
range: false,
|
||||
intervalMs: 1000,
|
||||
maxDataPoints: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
requireThat(query.status === 200, "GRAFANA_RULE_VALUE_HTTP_FAILED");
|
||||
const values = metricFrameValues(query.body);
|
||||
const threshold =
|
||||
original.data[2].model.conditions[0].evaluator.params[0];
|
||||
requireThat(
|
||||
values.length === 1 &&
|
||||
(wanted === "firing"
|
||||
? values[0] > threshold
|
||||
: values[0] <= threshold),
|
||||
"GRAFANA_RULE_STATE_VALUE_DISAGREEMENT",
|
||||
);
|
||||
return {
|
||||
states,
|
||||
elapsed_ms: Date.now() - begin,
|
||||
measured_value: values[0],
|
||||
threshold,
|
||||
query_time_milliseconds: point,
|
||||
};
|
||||
}
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
proof.last_rule_wait = { uid, wanted, states };
|
||||
throw Error(
|
||||
"GRAFANA_RULE_TRANSITION_TIMEOUT_" + uid.replaceAll("-", "_"),
|
||||
);
|
||||
};
|
||||
stage = "BASELINE_COMPLETION_AND_FRESH_HTTP";
|
||||
const baselineJob = await upload();
|
||||
await http.ready(actor.token, baselineJob);
|
||||
const baselineUntil = Date.now() + 12000;
|
||||
while (Date.now() < baselineUntil) {
|
||||
await traffic();
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
proof.baseline_rules = {
|
||||
worker: await waitState("vp7-old-jobs", "inactive", traffic),
|
||||
server: await waitState("vp7-server-errors", "inactive", traffic),
|
||||
};
|
||||
await save("RUNNING");
|
||||
stage = "WORKER_REAL_STOP";
|
||||
console.log("GRAFANA_INCIDENT_BASELINE_RULES_HEALTHY");
|
||||
await compose(["stop", "worker"]);
|
||||
const pendingJob = await upload(),
|
||||
workerIncidentStart = Date.now();
|
||||
stage = "WORKER_BACKLOG_NATIVE_FIRING";
|
||||
const firing = await waitState("vp7-old-jobs", "firing", traffic);
|
||||
proof.worker_incident = {
|
||||
attachment_id: pendingJob,
|
||||
started_milliseconds: workerIncidentStart,
|
||||
firing,
|
||||
};
|
||||
console.log("GRAFANA_INCIDENT_WORKER_FIRING_OBSERVED");
|
||||
await save("RUNNING");
|
||||
stage = "WORKER_REAL_RECOVERY";
|
||||
await compose(["up", "-d", "--no-build", "--no-deps", "worker"]);
|
||||
await http.ready(actor.token, pendingJob);
|
||||
const resolved = await waitState("vp7-old-jobs", "inactive", traffic);
|
||||
proof.worker_incident.resolved = resolved;
|
||||
proof.worker_incident.same_job_ready = true;
|
||||
console.log("GRAFANA_INCIDENT_WORKER_RECOVERY_RESOLVED");
|
||||
stage = "SECOND_COMPLETION_IN_RECOVERED_WORKER_INSTANCE";
|
||||
const afterExport = Date.now() + 4000;
|
||||
while (Date.now() < afterExport) {
|
||||
await traffic();
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
const freshJob = await upload();
|
||||
await http.ready(actor.token, freshJob);
|
||||
const exportDeadline = Date.now() + 5000;
|
||||
while (Date.now() < exportDeadline) {
|
||||
await traffic();
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
stage = "LIVE_19_NATIVE_PANEL_QUERIES";
|
||||
const dashboard = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "infra/grafana/dashboards/messenger.json"),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
point = Date.now() - 1000,
|
||||
panels = [];
|
||||
for (const panel of dashboard.panels) {
|
||||
stage = "LIVE_METRIC_PANEL_" + panel.id;
|
||||
const response = await grafanaRequest("/api/ds/query", {
|
||||
body: {
|
||||
from: String(point - 15 * 60000),
|
||||
to: String(point),
|
||||
queries: [
|
||||
{
|
||||
refId: "A",
|
||||
datasource: { type: "prometheus", uid: "prometheus" },
|
||||
expr: panel.targets[0].expr,
|
||||
instant: true,
|
||||
range: false,
|
||||
intervalMs: 1000,
|
||||
maxDataPoints: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
requireThat(
|
||||
response.status === 200,
|
||||
"GRAFANA_LIVE_METRIC_HTTP_" + response.status,
|
||||
);
|
||||
const values = metricFrameValues(response.body);
|
||||
panels.push({
|
||||
id: panel.id,
|
||||
title: panel.title,
|
||||
samples: values.length,
|
||||
values,
|
||||
});
|
||||
}
|
||||
requireThat(panels.length === 19, "GRAFANA_LIVE_PANEL_COUNT_MISMATCH");
|
||||
proof.live_panels = { query_time_milliseconds: point, panels };
|
||||
console.log("GRAFANA_INCIDENT_LIVE_19_PANELS_FINITE");
|
||||
await save("RUNNING");
|
||||
stage = "DIRECT_MTLS_API_POSITIVE";
|
||||
const apiIP = await containerIP("api1-gateway");
|
||||
const apiStatus = async () => {
|
||||
const response = await tlsProbe(
|
||||
apiIP,
|
||||
8443,
|
||||
"api1-gateway",
|
||||
"lb",
|
||||
`GET /api/v1/chats HTTP/1.1\r\nHost: api1-gateway\r\nAuthorization: Bearer ${actor.token}\r\nConnection: close\r\n\r\n`,
|
||||
"operator",
|
||||
(data) => data.includes("\r\n\r\n"),
|
||||
);
|
||||
requireThat(response.authorized, "GRAFANA_INCIDENT_API_TLS_UNAUTHORIZED");
|
||||
const match = /^HTTP\/1\.[01] ([0-9]{3})/.exec(response.data);
|
||||
requireThat(match, "GRAFANA_INCIDENT_API_RESPONSE_MISSING");
|
||||
return Number(match[1]);
|
||||
};
|
||||
requireThat(
|
||||
(await apiStatus()) === 200,
|
||||
"GRAFANA_INCIDENT_API_POSITIVE_FAILED",
|
||||
);
|
||||
stage = "DATABASE_REAL_STOP";
|
||||
await compose(["stop", "postgres"]);
|
||||
let observed5xx = 0;
|
||||
const errorTraffic = async () => {
|
||||
const status = await apiStatus();
|
||||
requireThat(
|
||||
status >= 500 && status <= 599,
|
||||
"GRAFANA_DB_INCIDENT_EXPECTED_5XX",
|
||||
);
|
||||
observed5xx++;
|
||||
};
|
||||
stage = "DATABASE_ERROR_NATIVE_FIRING";
|
||||
const databaseStart = Date.now(),
|
||||
serverFiring = await waitState(
|
||||
"vp7-server-errors",
|
||||
"firing",
|
||||
errorTraffic,
|
||||
);
|
||||
requireThat(observed5xx > 0, "GRAFANA_DB_INCIDENT_NO_NATIVE_5XX");
|
||||
proof.database_incident = {
|
||||
started_milliseconds: databaseStart,
|
||||
instrumented_direct_mtls_api_5xx: observed5xx,
|
||||
public_lb_health_withdrawal_not_counted_as_api_5xx: true,
|
||||
firing: serverFiring,
|
||||
};
|
||||
console.log("GRAFANA_INCIDENT_DATABASE_FIRING_OBSERVED");
|
||||
await save("RUNNING");
|
||||
stage = "DATABASE_REAL_RECOVERY";
|
||||
await compose(["up", "-d", "--no-build", "postgres"]);
|
||||
await waitReady();
|
||||
proof.database_incident.resolved = await waitState(
|
||||
"vp7-server-errors",
|
||||
"inactive",
|
||||
traffic,
|
||||
);
|
||||
proof.database_incident.public_api_200_after_recovery = true;
|
||||
console.log("GRAFANA_INCIDENT_DATABASE_RECOVERY_RESOLVED");
|
||||
stage = "INCIDENT_FINAL_GUARDS";
|
||||
requireThat(!heartbeatFailed, "GRAFANA_INCIDENT_HEARTBEAT_FAILED");
|
||||
proof.alert_transitions_accepted = true;
|
||||
proof.upload_count = proof.fixture.uploads.length;
|
||||
requireThat(
|
||||
proof.upload_count === 3,
|
||||
"GRAFANA_INCIDENT_FIXTURE_BOUND_EXCEEDED",
|
||||
);
|
||||
await save("PASS_NATIVE_GRAFANA_REAL_WORKER_DB_INCIDENTS_AND_19_PANELS");
|
||||
return { receipt: relative(root, receipt), ...proof };
|
||||
} catch (error) {
|
||||
primary = error;
|
||||
proof.code =
|
||||
error instanceof Error &&
|
||||
/^[A-Z][A-Za-z0-9_:-]{0,240}$/.test(error.message)
|
||||
? error.message
|
||||
: "PRIVATE_DETAILS_ONLY";
|
||||
await Promise.allSettled([save("FAILED")]);
|
||||
throw error;
|
||||
} finally {
|
||||
if (timer) clearInterval(timer);
|
||||
await pending;
|
||||
if (started) {
|
||||
const outcomes = await Promise.allSettled([
|
||||
compose(["stop", "api1", "api2", "worker"], { allowFailure: true }),
|
||||
]);
|
||||
const code =
|
||||
outcomes[0].status === "fulfilled" ? outcomes[0].value.code : null;
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(async () => {
|
||||
const saved = JSON.parse(await readFile(receipt, "utf8"));
|
||||
saved.application_stop_exit = code;
|
||||
if (code !== 0 && !primary) saved.state = "FAILED_TEARDOWN";
|
||||
await writeFile(receipt, JSON.stringify(saved, null, 2) + "\n");
|
||||
}),
|
||||
]);
|
||||
if (code !== 0 && !primary)
|
||||
throw Error("GRAFANA_INCIDENT_APPLICATION_STOP_FAILED");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
run,
|
||||
compose,
|
||||
privateWrite,
|
||||
requireThat,
|
||||
safeFailure,
|
||||
} from "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
import { writeTopology } from "./topology";
|
||||
import { provisionOpenObserve, openObserveRequest } from "./openobserve";
|
||||
import { prepareGrafana, grafanaRequest, metricFrameValues } from "./grafana";
|
||||
import { readGrafanaDatasources } from "./grafana-datasources";
|
||||
import { runGrafanaIncidents } from "./grafana-incidents";
|
||||
import { runGrafanaBrowser } from "./grafana-browser";
|
||||
const hash = (bytes: Uint8Array) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"GRAFANA_PREFLIGHT_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const cachePath = Bun.argv[2];
|
||||
const withIncidents = Bun.argv.includes("--incidents");
|
||||
const withBrowser = Bun.argv.includes("--browser");
|
||||
requireThat(
|
||||
!(withIncidents && withBrowser),
|
||||
"GRAFANA_SEPARATE_INCIDENT_AND_BROWSER_RECEIPTS_REQUIRED",
|
||||
);
|
||||
requireThat(
|
||||
/^evidence\/grafana\/cache-freeze-[a-f0-9-]+\.json$/.test(cachePath ?? ""),
|
||||
"GRAFANA_CACHE_RECEIPT_ARGUMENT_REQUIRED",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/grafana/preflight-" + 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;
|
||||
let result: Record<string, unknown> = {};
|
||||
try {
|
||||
const lease = await verifyBackendHandover();
|
||||
requireThat(
|
||||
lease.sha256 ===
|
||||
"09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609",
|
||||
"GRAFANA_BACKEND_LEASE_MISMATCH",
|
||||
);
|
||||
stage = "OWN_STAND_IDLE";
|
||||
requireThat(
|
||||
(
|
||||
await run([
|
||||
"docker",
|
||||
"ps",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=mtuci-vp7-security",
|
||||
"--format",
|
||||
"{{.ID}}",
|
||||
])
|
||||
).out.trim() === "",
|
||||
"GRAFANA_OWN_STAND_ALREADY_RUNNING",
|
||||
);
|
||||
stage = "CACHED_ARTIFACT_GUARD";
|
||||
const cacheBytes = await readFile(resolve(root, cachePath)),
|
||||
cache = JSON.parse(cacheBytes.toString());
|
||||
requireThat(
|
||||
cache.state === "PASS_OWN_GRAFANA_CACHE_NO_PULL" &&
|
||||
cache.image_id ===
|
||||
"sha256:1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e" &&
|
||||
cache.own_alias === "mtuci-vp7-grafana-cache:13.3.1-1c88285f1dd3",
|
||||
"GRAFANA_CACHE_RECEIPT_MISMATCH",
|
||||
);
|
||||
requireThat(
|
||||
JSON.parse(
|
||||
(await run(["docker", "image", "inspect", cache.own_alias])).out,
|
||||
)[0].Id === cache.image_id,
|
||||
"GRAFANA_IMAGE_DRIFT",
|
||||
);
|
||||
for (const [path, sha] of Object.entries(cache.copied_files))
|
||||
requireThat(
|
||||
hash(await readFile(resolve(local, "plugins/openobserve", path))) ===
|
||||
sha,
|
||||
"GRAFANA_PLUGIN_DRIFT",
|
||||
);
|
||||
stage = "PRIVATE_INITIALIZER_GUARDS";
|
||||
const password = await readFile(
|
||||
resolve(root, ".local-preflight-key"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(password),
|
||||
"INVALID_PREFLIGHT_SESSION_KEY",
|
||||
);
|
||||
const initializer = await prepareGrafana(password);
|
||||
stage = "OWN_CACHED_IMAGE_BINDING";
|
||||
let environment = await readFile(resolve(root, ".env"), "utf8");
|
||||
const line = "VP7_GRAFANA_IMAGE=" + cache.own_alias;
|
||||
requireThat(
|
||||
!environment.includes("VP7_GRAFANA_IMAGE=") ||
|
||||
environment.split("\n").includes(line),
|
||||
"GRAFANA_IMAGE_ENV_CONFLICT",
|
||||
);
|
||||
if (!environment.split("\n").includes(line))
|
||||
await privateWrite(
|
||||
resolve(root, ".env"),
|
||||
environment + "\n" + line + "\n",
|
||||
);
|
||||
stage = "CURRENT_COMPOSE_GENERATION";
|
||||
await writeTopology();
|
||||
await compose(["config", "--quiet"]);
|
||||
stage = "RETAINED_STORAGE_START";
|
||||
started = true;
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"--no-build",
|
||||
"openobserve-gateway",
|
||||
"openobserve",
|
||||
]);
|
||||
stage = "QUERY_ACCOUNT_NATIVE_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 (error) {
|
||||
await Promise.allSettled([
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/grafana-storage-last-error.json"),
|
||||
JSON.stringify({
|
||||
stage,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
code: (error as { code?: unknown })?.code,
|
||||
stack: error instanceof Error ? error.stack : "",
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(ready, "GRAFANA_STORAGE_READY_TIMEOUT");
|
||||
stage = "SAVED_SERVICE_ACCOUNT_AUTH_GUARDS";
|
||||
const accountGuards = await provisionOpenObserve(password);
|
||||
stage = "GRAFANA_NATIVE_FIRST_START";
|
||||
await compose(["up", "-d", "--no-build", "grafana-gateway", "grafana"]);
|
||||
stage = "PUBLISHED_HTTPS_GRAFANA_HEALTH";
|
||||
let health: any;
|
||||
const grafanaDeadline = Date.now() + 90000;
|
||||
while (Date.now() < grafanaDeadline) {
|
||||
try {
|
||||
health = await grafanaRequest("/api/health");
|
||||
if (health.status === 200 && health.body?.database === "ok") break;
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/grafana-health-last-error.json"),
|
||||
JSON.stringify({
|
||||
stage,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
code: (error as { code?: unknown })?.code,
|
||||
stack: error instanceof Error ? error.stack : "",
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(
|
||||
health?.status === 200 &&
|
||||
health.body?.database === "ok" &&
|
||||
health.body?.version === "13.3.1",
|
||||
"GRAFANA_NATIVE_HEALTH_TIMEOUT",
|
||||
);
|
||||
stage = "CLIENT_NETWORK_DNS";
|
||||
const dns = await compose([
|
||||
"exec",
|
||||
"-T",
|
||||
"grafana",
|
||||
"getent",
|
||||
"hosts",
|
||||
"openobserve-gateway",
|
||||
]);
|
||||
requireThat(
|
||||
/\b\d+\.\d+\.\d+\.\d+\b/.test(dns.out),
|
||||
"GRAFANA_OPENOBSERVE_DNS_FAILED",
|
||||
);
|
||||
stage = "NATIVE_DATASOURCE_PROVISIONING";
|
||||
const datasourceUIDs = await readGrafanaDatasources(grafanaRequest);
|
||||
stage = "MOUNTED_DASHBOARD_NATIVE_READ";
|
||||
const dashboardResponse = await grafanaRequest(
|
||||
"/api/dashboards/uid/messenger-security",
|
||||
),
|
||||
mounted = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "infra/grafana/dashboards/messenger.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
requireThat(
|
||||
dashboardResponse.status === 200 &&
|
||||
dashboardResponse.body?.dashboard?.panels?.length === 19,
|
||||
"GRAFANA_DASHBOARD_PANEL_COUNT_MISMATCH",
|
||||
);
|
||||
const history = JSON.parse(
|
||||
await readFile(
|
||||
resolve(
|
||||
root,
|
||||
"evidence/openobserve/persisted-readback-8fa17baa-a9f5-419c-bf24-e9ac820fdfbf.json",
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const point = Math.floor(history.query_time_milliseconds);
|
||||
requireThat(
|
||||
Number.isSafeInteger(point) && point > 0,
|
||||
"GRAFANA_HISTORY_POINT_INVALID",
|
||||
);
|
||||
stage = withIncidents
|
||||
? "REAL_WORKER_DATABASE_INCIDENTS"
|
||||
: "HISTORICAL_METRIC_READS";
|
||||
const incidents = withIncidents
|
||||
? await runGrafanaIncidents(password)
|
||||
: undefined;
|
||||
const panels = incidents?.live_panels.panels ?? [];
|
||||
const browserProof = withBrowser ? await runGrafanaBrowser() : undefined;
|
||||
for (const panel of withIncidents || withBrowser ? [] : mounted.panels) {
|
||||
stage = "HISTORICAL_METRIC_PANEL_" + panel.id;
|
||||
const response = await grafanaRequest("/api/ds/query", {
|
||||
body: {
|
||||
from: String(point - 15 * 60000),
|
||||
to: String(point),
|
||||
queries: [
|
||||
{
|
||||
refId: "A",
|
||||
datasource: { type: "prometheus", uid: "prometheus" },
|
||||
expr: panel.targets[0].expr,
|
||||
instant: true,
|
||||
range: false,
|
||||
intervalMs: 1000,
|
||||
maxDataPoints: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
requireThat(
|
||||
response.status === 200,
|
||||
"GRAFANA_METRIC_HTTP_STATUS_" + response.status,
|
||||
);
|
||||
const values = metricFrameValues(response.body);
|
||||
panels.push({
|
||||
id: panel.id,
|
||||
title: panel.title,
|
||||
samples: values.length,
|
||||
values,
|
||||
});
|
||||
}
|
||||
stage = "NATIVE_RULE_PROVISIONING";
|
||||
const rules = await grafanaRequest("/api/v1/provisioning/alert-rules");
|
||||
requireThat(
|
||||
rules.status === 200 &&
|
||||
Array.isArray(rules.body) &&
|
||||
rules.body.length === 2 &&
|
||||
rules.body.every((r: any) =>
|
||||
["vp7-server-errors", "vp7-old-jobs"].includes(r.uid),
|
||||
),
|
||||
"GRAFANA_NATIVE_RULES_MISMATCH",
|
||||
);
|
||||
stage = "SOURCE_AND_ARTIFACT_POSTGUARDS";
|
||||
await lease.verify();
|
||||
requireThat(
|
||||
hash(await readFile(resolve(root, cachePath))) === hash(cacheBytes),
|
||||
"GRAFANA_CACHE_LEASE_CHANGED",
|
||||
);
|
||||
result = {
|
||||
state: withBrowser
|
||||
? "OBSERVED_GRAFANA_BROWSER_PENDING_FINAL_ACCEPTANCE"
|
||||
: withIncidents
|
||||
? "PASS_NATIVE_GRAFANA_LIVE_19_METRICS_AND_REAL_ALERT_INCIDENTS"
|
||||
: "PASS_NATIVE_GRAFANA_BOOTSTRAP_AND_19_HISTORICAL_METRICS",
|
||||
stage,
|
||||
backend_handover_sha256: lease.sha256,
|
||||
cache_receipt: { path: cachePath, sha256: hash(cacheBytes) },
|
||||
initializer,
|
||||
accountGuards,
|
||||
grafana_version: health.body.version,
|
||||
grafana_build_commit: health.body.commit,
|
||||
datasource_uids: datasourceUIDs,
|
||||
panels,
|
||||
rule_uids: rules.body.map((r: any) => r.uid),
|
||||
metric_query_time_milliseconds:
|
||||
incidents?.live_panels.query_time_milliseconds ?? point,
|
||||
retained_trace_history_query_time_milliseconds: point,
|
||||
producer_started: withIncidents,
|
||||
incidents,
|
||||
browser: browserProof,
|
||||
smoke_repeated: false,
|
||||
native_grafana_bootstrap: true,
|
||||
native_grafana_ui: false,
|
||||
alert_transitions_accepted: withIncidents,
|
||||
response_cap_accepted: false,
|
||||
native_bao: false,
|
||||
grade5: false,
|
||||
};
|
||||
await writeFile(receipt, JSON.stringify(result, null, 2) + "\n");
|
||||
console.log(
|
||||
withBrowser
|
||||
? "OBSERVED_BROWSER_NOT_FINAL_ACCEPTANCE"
|
||||
: withIncidents
|
||||
? "PASS_GRAFANA_LIVE_19_METRICS_REAL_INCIDENTS_NO_UI_OR_CAP_ACCEPTANCE"
|
||||
: "PASS_GRAFANA_BOOTSTRAP_19_METRICS_NO_UI_OR_ALERT_ACCEPTANCE",
|
||||
);
|
||||
} catch (error) {
|
||||
primary = error;
|
||||
result = {
|
||||
state: "FAILED",
|
||||
stage,
|
||||
code:
|
||||
error instanceof Error &&
|
||||
/^[A-Z][A-Za-z0-9_:-]{0,240}$/.test(error.message)
|
||||
? error.message
|
||||
: "PRIVATE_DETAILS_ONLY",
|
||||
native_bao: false,
|
||||
grade5: false,
|
||||
};
|
||||
await Promise.allSettled([
|
||||
writeFile(receipt, JSON.stringify(result, null, 2) + "\n"),
|
||||
]);
|
||||
throw error;
|
||||
} finally {
|
||||
if (started) {
|
||||
const stopped = await Promise.allSettled([
|
||||
compose(
|
||||
withIncidents
|
||||
? ["stop"]
|
||||
: [
|
||||
"stop",
|
||||
"grafana",
|
||||
"grafana-gateway",
|
||||
"openobserve",
|
||||
"openobserve-gateway",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
),
|
||||
]);
|
||||
const code =
|
||||
stopped[0].status === "fulfilled" ? stopped[0].value.code : null;
|
||||
await Promise.allSettled([
|
||||
writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
...result,
|
||||
stop_exit: code,
|
||||
...(code !== 0 && !primary ? { state: "FAILED_TEARDOWN" } : {}),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
),
|
||||
]);
|
||||
if (code !== 0 && !primary) throw Error("GRAFANA_PREFLIGHT_STOP_FAILED");
|
||||
console.log(
|
||||
code === 0
|
||||
? "OWN_GRAFANA_PREFLIGHT_STOPPED"
|
||||
: "OWN_GRAFANA_STOP_REQUIRES_INSPECTION",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { local, project, run, requireThat } from "./runtime";
|
||||
import { decrypt, encrypt } from "./operator-crypto";
|
||||
import { createEvidencePreserver } from "./checkpoint-guards";
|
||||
import { containerID } from "./runtime-inspect";
|
||||
export function isOwnHistoryWrite(
|
||||
method: string,
|
||||
path: string,
|
||||
body: any,
|
||||
name: string,
|
||||
) {
|
||||
const collection =
|
||||
"/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage";
|
||||
if (!/^grafana-page-history:[a-z0-9]{8,40}$/.test(name)) return false;
|
||||
return (
|
||||
(method === "POST" &&
|
||||
[collection, collection + "/"].includes(path) &&
|
||||
body?.metadata?.name === name) ||
|
||||
(method === "PATCH" &&
|
||||
path === collection + "/" + name &&
|
||||
typeof body?.metadata?.resourceVersion === "string" &&
|
||||
body.metadata.resourceVersion.length > 0)
|
||||
);
|
||||
}
|
||||
export function publicGrafanaEndpoint(info: any) {
|
||||
requireThat(
|
||||
info?.Config?.Labels?.["com.docker.compose.project"] === project &&
|
||||
info?.Config?.Labels?.["com.docker.compose.service"] ===
|
||||
"grafana-gateway" &&
|
||||
info?.State?.Running === true,
|
||||
"GRAFANA_ENDPOINT_RESOURCE_MISMATCH",
|
||||
);
|
||||
const bindings = info?.NetworkSettings?.Ports?.["3443/tcp"];
|
||||
requireThat(
|
||||
Array.isArray(bindings) && bindings.length === 1,
|
||||
"GRAFANA_ENDPOINT_BINDING_MISSING",
|
||||
);
|
||||
const binding = bindings[0];
|
||||
requireThat(
|
||||
binding.HostIp === "127.0.0.1" &&
|
||||
typeof binding.HostPort === "string" &&
|
||||
/^[0-9]{1,5}$/.test(binding.HostPort),
|
||||
"GRAFANA_ENDPOINT_BINDING_UNSAFE",
|
||||
);
|
||||
const port = Number(binding.HostPort);
|
||||
requireThat(port >= 1 && port <= 65535, "GRAFANA_ENDPOINT_PORT_INVALID");
|
||||
return { host: "127.0.0.1", port };
|
||||
}
|
||||
export function metricFrameValues(body: any, ref = "A") {
|
||||
const result = body?.results?.[ref];
|
||||
requireThat(
|
||||
result &&
|
||||
!result.error &&
|
||||
(!result.status || result.status === 200) &&
|
||||
Array.isArray(result.frames) &&
|
||||
result.frames.length > 0,
|
||||
"GRAFANA_METRIC_RESULT_INVALID",
|
||||
);
|
||||
const numbers: number[] = [];
|
||||
for (const frame of result.frames) {
|
||||
const fields = frame?.schema?.fields,
|
||||
values = frame?.data?.values;
|
||||
requireThat(
|
||||
Array.isArray(fields) &&
|
||||
Array.isArray(values) &&
|
||||
fields.length === values.length &&
|
||||
fields.length > 0,
|
||||
"GRAFANA_METRIC_FRAME_INVALID",
|
||||
);
|
||||
const rows = values[0]?.length;
|
||||
requireThat(
|
||||
Number.isInteger(rows) &&
|
||||
rows > 0 &&
|
||||
values.every(
|
||||
(column: any) => Array.isArray(column) && column.length === rows,
|
||||
),
|
||||
"GRAFANA_METRIC_FRAME_EMPTY_OR_RAGGED",
|
||||
);
|
||||
for (let i = 0; i < fields.length; i++) {
|
||||
if (fields[i].type !== "number") continue;
|
||||
for (const value of values[i]) {
|
||||
if (value === null) continue;
|
||||
requireThat(
|
||||
typeof value === "number" && Number.isFinite(value),
|
||||
"GRAFANA_METRIC_SAMPLE_INVALID",
|
||||
);
|
||||
numbers.push(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
requireThat(numbers.length > 0, "GRAFANA_METRIC_NO_FINITE_SAMPLES");
|
||||
return numbers;
|
||||
}
|
||||
export async function prepareGrafana(password: string) {
|
||||
const services = decrypt<{ grafana: string }>(
|
||||
await readFile(resolve(local, "operator/services.enc"), "utf8"),
|
||||
password,
|
||||
),
|
||||
consumer = await readFile(
|
||||
resolve(local, "operator/grafana-password"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(services.grafana) && consumer === services.grafana,
|
||||
"GRAFANA_ADMIN_ENVELOPE_CONSUMER_MISMATCH",
|
||||
);
|
||||
const path = resolve(local, "operator/grafana-security.enc");
|
||||
let secret: { secretKey: string };
|
||||
if (await Bun.file(path).exists())
|
||||
secret = decrypt(await readFile(path, "utf8"), password);
|
||||
else {
|
||||
secret = { secretKey: randomBytes(32).toString("hex") };
|
||||
await writeFile(path, encrypt(secret, password), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
}
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(secret.secretKey),
|
||||
"GRAFANA_SECURITY_KEY_SHAPE_INVALID",
|
||||
);
|
||||
const preserve = createEvidencePreserver({
|
||||
read: readFile,
|
||||
writeExclusive: (p, b) => writeFile(p, b, { flag: "wx", mode: 0o600 }),
|
||||
});
|
||||
await preserve(
|
||||
resolve(local, "operator/grafana-secret-key"),
|
||||
Buffer.from(secret.secretKey),
|
||||
);
|
||||
return {
|
||||
admin_envelope_matches_consumer: true,
|
||||
security_key_encrypted_before_publication: true,
|
||||
admin_password_shape_and_envelope_verified: true,
|
||||
};
|
||||
}
|
||||
export async function grafanaAddress() {
|
||||
const id = await containerID("grafana-gateway");
|
||||
return publicGrafanaEndpoint(
|
||||
JSON.parse((await run(["docker", "inspect", id])).out)[0],
|
||||
);
|
||||
}
|
||||
export async function grafanaRequest(
|
||||
path: string,
|
||||
options: { body?: unknown; method?: string; anonymous?: boolean } = {},
|
||||
) {
|
||||
requireThat(
|
||||
/^\/api\/[A-Za-z0-9_./?=&%-]+$/.test(path) && !path.includes(".."),
|
||||
"GRAFANA_REQUEST_PATH_INVALID",
|
||||
);
|
||||
const endpoint = await grafanaAddress(),
|
||||
ca = await readFile(resolve(local, "pki/grafana/ca.crt"));
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (!options.anonymous) {
|
||||
const password = await readFile(
|
||||
resolve(local, "operator/grafana-password"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(password),
|
||||
"GRAFANA_ADMIN_CONSUMER_INVALID",
|
||||
);
|
||||
headers.Authorization =
|
||||
"Basic " + Buffer.from("operator:" + password).toString("base64");
|
||||
}
|
||||
const scratch = resolve(
|
||||
local,
|
||||
"diagnostics/grafana-request-" + crypto.randomUUID(),
|
||||
);
|
||||
await mkdir(scratch, { recursive: true, mode: 0o700 });
|
||||
const response = await fetch(
|
||||
`https://${endpoint.host}:${endpoint.port}${path}`,
|
||||
{
|
||||
method: options.method ?? (options.body === undefined ? "GET" : "POST"),
|
||||
headers,
|
||||
body:
|
||||
options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
tls: { ca: ca.toString() },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
redirect: "manual",
|
||||
},
|
||||
);
|
||||
const meta = {
|
||||
status: response.status,
|
||||
content_type: response.headers.get("content-type") ?? "",
|
||||
};
|
||||
await Promise.allSettled([
|
||||
writeFile(resolve(scratch, "http.json"), JSON.stringify(meta), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
}),
|
||||
]);
|
||||
const reader = response.body?.getReader(),
|
||||
chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
try {
|
||||
if (reader)
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.length;
|
||||
if (size > 12 * 1024 * 1024) await reader.cancel();
|
||||
requireThat(
|
||||
size <= 12 * 1024 * 1024,
|
||||
"GRAFANA_TEST_CLIENT_LIMIT_12MIB",
|
||||
);
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader?.releaseLock();
|
||||
}
|
||||
const bytes = Buffer.concat(chunks);
|
||||
await Promise.allSettled([
|
||||
writeFile(resolve(scratch, "response"), bytes, { flag: "wx", mode: 0o600 }),
|
||||
]);
|
||||
let body: any = null;
|
||||
if (meta.content_type.includes("application/json")) {
|
||||
try {
|
||||
body = JSON.parse(bytes.toString());
|
||||
} catch {
|
||||
requireThat(response.status >= 400, "GRAFANA_SUCCESS_INVALID_JSON");
|
||||
}
|
||||
}
|
||||
return { ...meta, body, bytes: bytes.length };
|
||||
}
|
||||
|
||||
export function assertOriginalGrafanaRules(actual: any[], expected: any[]) {
|
||||
requireThat(
|
||||
Array.isArray(actual) &&
|
||||
actual.length === expected.length &&
|
||||
expected.length > 0,
|
||||
"GRAFANA_INCIDENT_RULES_MISSING",
|
||||
);
|
||||
for (const e of expected) {
|
||||
const a = actual.find((r) => r.uid === e.uid),
|
||||
ae = a?.data?.[2]?.model?.conditions?.[0]?.evaluator,
|
||||
ee = e.data[2].model.conditions[0].evaluator;
|
||||
requireThat(
|
||||
a &&
|
||||
a.title === e.title &&
|
||||
a.data?.[0]?.model?.expr === e.data[0].model.expr &&
|
||||
ae?.type === ee.type &&
|
||||
Array.isArray(ae.params) &&
|
||||
ae.params.length === ee.params.length &&
|
||||
ae.params.every(
|
||||
(value: any, i: number) =>
|
||||
typeof value === "number" &&
|
||||
Number.isFinite(value) &&
|
||||
value === ee.params[i],
|
||||
),
|
||||
"GRAFANA_INCIDENT_RULE_CHANGED",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
export function freshSecretsAfterSeal(
|
||||
contents: string[],
|
||||
sealedAt: number,
|
||||
now: number,
|
||||
maxAgeMilliseconds: number,
|
||||
) {
|
||||
return (
|
||||
contents.length === 3 &&
|
||||
[sealedAt, now, maxAgeMilliseconds].every(Number.isFinite) &&
|
||||
sealedAt >= 0 &&
|
||||
now >= sealedAt &&
|
||||
maxAgeMilliseconds > 0 &&
|
||||
contents.every((content) => {
|
||||
const value = content.trim();
|
||||
if (
|
||||
content.length > 128 ||
|
||||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(
|
||||
value,
|
||||
)
|
||||
)
|
||||
return false;
|
||||
const timestamp = Date.parse(value),
|
||||
age = now - timestamp;
|
||||
return (
|
||||
Number.isFinite(age) &&
|
||||
age >= 0 &&
|
||||
age <= maxAgeMilliseconds &&
|
||||
timestamp > sealedAt
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
export function createHealthConvergence(
|
||||
ports: {
|
||||
read: () => Promise<string>;
|
||||
now: () => number;
|
||||
sleep: (milliseconds: number) => Promise<void>;
|
||||
},
|
||||
budgetMilliseconds: number,
|
||||
pollMilliseconds: number,
|
||||
) {
|
||||
if (
|
||||
[ports?.read, ports?.now, ports?.sleep].some((p) => typeof p !== "function")
|
||||
)
|
||||
throw Error("HEALTH_PORTS_REQUIRED");
|
||||
if (
|
||||
!Number.isSafeInteger(budgetMilliseconds) ||
|
||||
!Number.isSafeInteger(pollMilliseconds) ||
|
||||
pollMilliseconds <= 0 ||
|
||||
budgetMilliseconds < pollMilliseconds
|
||||
)
|
||||
throw Error("HEALTH_LIMITS_INVALID");
|
||||
return async () => {
|
||||
const started = ports.now();
|
||||
if (!Number.isFinite(started) || started < 0)
|
||||
throw Error("HEALTH_CLOCK_INVALID");
|
||||
let reads = 0;
|
||||
for (;;) {
|
||||
const state = await ports.read();
|
||||
reads++;
|
||||
const elapsedMilliseconds = ports.now() - started;
|
||||
if (!Number.isFinite(elapsedMilliseconds) || elapsedMilliseconds < 0)
|
||||
throw Error("HEALTH_CLOCK_INVALID");
|
||||
if (!["healthy", "starting", "unhealthy"].includes(state))
|
||||
throw Error("BAO_HEALTH_INVALID");
|
||||
if (state === "healthy" && elapsedMilliseconds <= budgetMilliseconds)
|
||||
return { elapsedMilliseconds, reads };
|
||||
if (elapsedMilliseconds >= budgetMilliseconds)
|
||||
throw Error("BAO_HEALTH_NOT_CONVERGED");
|
||||
await ports.sleep(
|
||||
Math.min(pollMilliseconds, budgetMilliseconds - elapsedMilliseconds),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, compose, run, requireThat, safeFailure } from "./runtime";
|
||||
import { containerID } from "./runtime-inspect";
|
||||
import { operatorPassword } from "./operator-crypto";
|
||||
import { unseal } from "./openbao-operator";
|
||||
import { waitReady } from "../student-tests/wait";
|
||||
import { createReplicaSnapshot } from "./replica-snapshot";
|
||||
import {
|
||||
failoverReceiptPath,
|
||||
type ReplicaBaseline,
|
||||
type ReplicaService,
|
||||
} from "./failover-proof";
|
||||
async function snapshot(services: string[]) {
|
||||
const result = [];
|
||||
for (const service of services) {
|
||||
const id = await containerID(service),
|
||||
info = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
result.push({ service, id, started_at: info.State.StartedAt });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export async function restart(password: string) {
|
||||
const services = [
|
||||
"postgres",
|
||||
"broker",
|
||||
"s3",
|
||||
"openbao",
|
||||
"collector",
|
||||
"openobserve",
|
||||
"grafana",
|
||||
"api1-agent",
|
||||
"api2-agent",
|
||||
"worker-agent",
|
||||
"worker",
|
||||
"api1",
|
||||
"api2",
|
||||
"lb",
|
||||
];
|
||||
const before = await snapshot(services);
|
||||
await compose(["restart", ...services]);
|
||||
await unseal(password);
|
||||
await waitReady();
|
||||
const after = await snapshot(services);
|
||||
for (const old of before)
|
||||
requireThat(
|
||||
after.find((x) => x.service === old.service)?.started_at !==
|
||||
old.started_at,
|
||||
"RESTART_MISSING_" + old.service.toUpperCase(),
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/persistence-processes.json"),
|
||||
JSON.stringify({ before, after, volumes_removed: false }, null, 2) + "\n",
|
||||
);
|
||||
console.log("PASS_REAL_STORES_AND_APPLICATION_RESTARTED");
|
||||
}
|
||||
export async function snapshotReplicas() {
|
||||
return createReplicaSnapshot({
|
||||
inspect: async (service) => {
|
||||
const id = await containerID(service);
|
||||
const info = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
return {
|
||||
id: info.Id,
|
||||
running: info.State.Running,
|
||||
project: info.Config.Labels["com.docker.compose.project"],
|
||||
service: info.Config.Labels["com.docker.compose.service"],
|
||||
started: info.State.StartedAt,
|
||||
};
|
||||
},
|
||||
command: async (args) => (await run(args)).out,
|
||||
})();
|
||||
}
|
||||
export async function stopOne() {
|
||||
const target = Bun.env.TARGET_INSTANCE_ID;
|
||||
requireThat(
|
||||
typeof target === "string" && /^[a-f0-9-]{36}$/.test(target),
|
||||
"INVALID_TARGET_INSTANCE_ID",
|
||||
);
|
||||
const operationId = Bun.env.VP7_ACCEPTANCE_RUN_ID ?? crypto.randomUUID();
|
||||
const attemptId = Bun.env.VP7_FAILOVER_ATTEMPT_ID ?? crypto.randomUUID();
|
||||
const receiptPath = failoverReceiptPath(operationId, attemptId);
|
||||
const baseline = await snapshotReplicas();
|
||||
const matches = (Object.keys(baseline) as ReplicaService[]).filter(
|
||||
(service) => baseline[service].alias === target,
|
||||
);
|
||||
requireThat(matches.length === 1, "TARGET_REPLICA_NOT_UNIQUE");
|
||||
const id = baseline[matches[0]].container;
|
||||
// Stop the immutable, ownership-verified container that supplied this alias.
|
||||
await run(["docker", "stop", "--timeout", "15", id]);
|
||||
const info = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
requireThat(
|
||||
info.Id === id && info.State.Running === false,
|
||||
"TARGET_STILL_RUNNING",
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, receiptPath),
|
||||
JSON.stringify(
|
||||
{
|
||||
operation_id: operationId,
|
||||
attempt_id: attemptId,
|
||||
target_alias: target,
|
||||
service: matches[0],
|
||||
container: id,
|
||||
before_running: true,
|
||||
running: false,
|
||||
volumes_removed: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
console.log("PASS_EXACT_TARGET_API_STOPPED");
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
if (Bun.argv[2] === "restart") await restart(await operatorPassword());
|
||||
else if (Bun.argv[2] === "stop-one") await stopOne();
|
||||
else throw new Error("INVALID_HOOK_ACTION");
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
try {
|
||||
const ref = "openbao/openbao:2.7.2",
|
||||
repo = "openbao/openbao";
|
||||
const index = JSON.parse(
|
||||
(await run(["docker", "buildx", "imagetools", "inspect", ref, "--raw"]))
|
||||
.out,
|
||||
);
|
||||
const digest = index.manifests?.find(
|
||||
(x: any) =>
|
||||
x.platform?.os === "linux" && x.platform?.architecture === "amd64",
|
||||
)?.digest;
|
||||
requireThat(/^sha256:[a-f0-9]{64}$/.test(digest), "NO_AMD64_MANIFEST");
|
||||
const manifest = JSON.parse(
|
||||
(
|
||||
await run([
|
||||
"docker",
|
||||
"buildx",
|
||||
"imagetools",
|
||||
"inspect",
|
||||
repo + "@" + digest,
|
||||
"--raw",
|
||||
])
|
||||
).out,
|
||||
);
|
||||
const bytes = manifest.layers.reduce(
|
||||
(sum: number, layer: any) => sum + layer.size,
|
||||
0,
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "OPENBAO-IMAGE.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
ref,
|
||||
image: repo + "@" + digest,
|
||||
compressed_bytes: bytes,
|
||||
platform: "linux/amd64",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log(JSON.stringify({ ref, compressed_bytes: bytes, digest }));
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { run, root, safeFailure } from "./runtime";
|
||||
try {
|
||||
await run([
|
||||
process.execPath,
|
||||
"add",
|
||||
"--dev",
|
||||
"--ignore-scripts",
|
||||
"@types/bun",
|
||||
]);
|
||||
const pkg = await Bun.file(root + "/package.json").json();
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
installed: "development type declarations only",
|
||||
types_bun: pkg.devDependencies?.["@types/bun"],
|
||||
}),
|
||||
);
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { requireThat } from "./runtime";
|
||||
export type Role = "api" | "worker";
|
||||
export type ServiceSecrets = {
|
||||
database_url: string;
|
||||
cache_url: string;
|
||||
s3_json: string;
|
||||
publisher_url?: string;
|
||||
};
|
||||
function roleURL(
|
||||
value: string,
|
||||
protocol: string,
|
||||
port: string,
|
||||
identity: string,
|
||||
) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new Error("BAO_ROLE_MISMATCH");
|
||||
}
|
||||
requireThat(
|
||||
url.protocol === protocol &&
|
||||
url.hostname === "127.0.0.1" &&
|
||||
url.port === port &&
|
||||
url.username === identity,
|
||||
"BAO_ROLE_MISMATCH",
|
||||
);
|
||||
}
|
||||
export function parseKV(
|
||||
response: { status: number; data: any },
|
||||
role: Role,
|
||||
): { secrets: ServiceSecrets; version: number } {
|
||||
requireThat(response.status === 200, "BAO_KV_HTTP_NOT_SUCCESS");
|
||||
const envelope = response.data?.data,
|
||||
payload = envelope?.data,
|
||||
version = envelope?.metadata?.version;
|
||||
requireThat(
|
||||
payload && typeof payload === "object" && !Array.isArray(payload),
|
||||
"BAO_KV_V2_ENVELOPE_INVALID",
|
||||
);
|
||||
const keys = [
|
||||
"database_url",
|
||||
"cache_url",
|
||||
"s3_json",
|
||||
...(role === "worker" ? ["publisher_url"] : []),
|
||||
];
|
||||
for (const key of keys)
|
||||
requireThat(
|
||||
typeof payload[key] === "string" &&
|
||||
payload[key].length > 0 &&
|
||||
payload[key].length <= 8192,
|
||||
"BAO_MISSING_ROLE_SECRETS",
|
||||
);
|
||||
requireThat(
|
||||
Number.isSafeInteger(version) && version >= 1,
|
||||
"BAO_KV_VERSION_INVALID",
|
||||
);
|
||||
roleURL(payload.database_url, "postgresql:", "15432", role);
|
||||
roleURL(payload.cache_url, "redis:", "16379", role);
|
||||
if (role === "worker")
|
||||
roleURL(payload.publisher_url, "redis:", "16379", "publisher");
|
||||
else requireThat(payload.publisher_url === undefined, "BAO_ROLE_MISMATCH");
|
||||
let s3: any;
|
||||
try {
|
||||
s3 = JSON.parse(payload.s3_json);
|
||||
} catch {
|
||||
throw new Error("BAO_S3_JSON_INVALID");
|
||||
}
|
||||
requireThat(
|
||||
s3.Endpoint === "127.0.0.1:19000" &&
|
||||
s3.Access === "vp7" + role &&
|
||||
s3.Bucket === "messenger-attachments",
|
||||
"BAO_ROLE_MISMATCH",
|
||||
);
|
||||
requireThat(
|
||||
typeof s3.Secret === "string" &&
|
||||
s3.Secret.length > 0 &&
|
||||
s3.Secret.length <= 4096,
|
||||
"BAO_MISSING_ROLE_SECRETS",
|
||||
);
|
||||
const secrets: ServiceSecrets = {
|
||||
database_url: payload.database_url,
|
||||
cache_url: payload.cache_url,
|
||||
s3_json: payload.s3_json,
|
||||
};
|
||||
if (role === "worker") secrets.publisher_url = payload.publisher_url;
|
||||
return { secrets, version };
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
requireThat,
|
||||
privateWrite,
|
||||
safeFailure,
|
||||
} from "./runtime";
|
||||
import { operatorPassword, decrypt } from "./operator-crypto";
|
||||
import { bootstrap } from "./bootstrap";
|
||||
import { writeTopology } from "./topology";
|
||||
import { initialize, unseal } from "./openbao-operator";
|
||||
import { createAcceptCommand } from "./git-proof-cli";
|
||||
import { readCanonicalGitProof } from "./git-tracking-source";
|
||||
import { bao } from "./bao-client";
|
||||
import { provisionDB } from "./db-provision";
|
||||
import { provisionS3 } from "./s3-provision";
|
||||
import { waitReady } from "../student-tests/wait";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
import { prepareGrafana } from "./grafana";
|
||||
import {
|
||||
createRuntimePreparation,
|
||||
type RuntimeMode,
|
||||
} from "./runtime-preparation";
|
||||
import { verifyCheckedRuntime } from "./checked-runtime";
|
||||
import {
|
||||
prepareOpenObserve,
|
||||
provisionOpenObserve,
|
||||
openObserveRequest,
|
||||
} from "./openobserve";
|
||||
export async function start(
|
||||
password: string,
|
||||
runtimeMode: RuntimeMode = "canonical",
|
||||
) {
|
||||
requireThat(
|
||||
await Bun.file(resolve(root, "BACKEND-READY.json")).exists(),
|
||||
"CHECKED_BACKEND_HANDOVER_REQUIRED",
|
||||
);
|
||||
const sourceLease = await verifyBackendHandover();
|
||||
await prepareOpenObserve(password);
|
||||
await prepareGrafana(password);
|
||||
await writeTopology();
|
||||
await import("./generate-agent-configs");
|
||||
await import("./telemetry-dashboard");
|
||||
await compose(["config", "--quiet"]);
|
||||
const effectiveImages = (await compose(["config", "--images"])).out
|
||||
.trim()
|
||||
.split("\n");
|
||||
for (const image of new Set(
|
||||
effectiveImages.filter((image) => image !== "mtuci-vp7-security-app:local"),
|
||||
))
|
||||
await run(["docker", "image", "inspect", image]);
|
||||
let checkedRuntime:
|
||||
Awaited<ReturnType<typeof verifyCheckedRuntime>> | undefined;
|
||||
await createRuntimePreparation({
|
||||
build: async () => {
|
||||
await compose(["build", "--pull=false", "api1"]);
|
||||
},
|
||||
verifyCache: async () => {
|
||||
checkedRuntime = await verifyCheckedRuntime();
|
||||
},
|
||||
})(runtimeMode);
|
||||
await sourceLease.verify();
|
||||
requireThat(
|
||||
(await verifyBackendHandover()).sha256 === sourceLease.sha256,
|
||||
"HANDOVER_GENERATION_CHANGED",
|
||||
);
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"postgres",
|
||||
"broker-gateway",
|
||||
"broker",
|
||||
"s3-gateway",
|
||||
"s3",
|
||||
"openbao",
|
||||
]);
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
const r = await compose(
|
||||
[
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"pg_isready",
|
||||
"-h",
|
||||
"127.0.0.1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
if (r.code === 0) break;
|
||||
requireThat(attempt < 39, "PG_BOOT_TIMEOUT");
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
let initialized = false,
|
||||
responded = false;
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
try {
|
||||
const state = await bao("/sys/init");
|
||||
initialized = state.data.initialized === true;
|
||||
responded = true;
|
||||
break;
|
||||
} catch {
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
}
|
||||
requireThat(responded, "BAO_TLS_STARTUP_TIMEOUT");
|
||||
if (initialized) await unseal(password);
|
||||
else await initialize(password);
|
||||
await provisionDB(password);
|
||||
const secrets = decrypt<any>(
|
||||
await readFile(resolve(local, "operator/services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "operator/migration-url"),
|
||||
`postgresql://operator:${secrets.dbOperator}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt&sslcert=/pki/cert.pem&sslkey=/pki/key.pem`,
|
||||
);
|
||||
await compose(["run", "--rm", "--no-deps", "migrate"]);
|
||||
await provisionDB(password, true);
|
||||
// RustFS may need to finish its first durable drive bootstrap before the operator's bounded SDK request.
|
||||
let bootstrapped = false;
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
try {
|
||||
await provisionS3(password);
|
||||
bootstrapped = true;
|
||||
break;
|
||||
} catch {
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
}
|
||||
requireThat(bootstrapped, "S3_BOOTSTRAP_TIMEOUT");
|
||||
await compose(["up", "-d", "openobserve-gateway", "openobserve"]);
|
||||
let storageReady = false;
|
||||
const storageDeadline = Date.now() + 60_000;
|
||||
while (Date.now() < storageDeadline) {
|
||||
try {
|
||||
if (
|
||||
(await openObserveRequest("/api/default/streams", { password }))
|
||||
.status === 200
|
||||
) {
|
||||
storageReady = true;
|
||||
break;
|
||||
}
|
||||
} catch {}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(storageReady, "OPENOBSERVE_AUTHENTICATED_BOOT_TIMEOUT");
|
||||
await provisionOpenObserve(password);
|
||||
await compose(["up", "-d"]);
|
||||
await waitReady();
|
||||
await checkedRuntime?.verify();
|
||||
console.log("PASS_FULL_STAND_STARTED_WITH_VERIFIED_HTTPS");
|
||||
}
|
||||
const usage =
|
||||
"bun scripts/lab.ts prepare | start [--checked-cache] | wait | stop | unseal | accept [--checked-cache] [--git-proof PATH --git-proof-sha SHA256] | help";
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const action = Bun.argv[2] ?? "help";
|
||||
if (["help", "--help", "-h"].includes(action)) console.log(usage);
|
||||
else if (action === "prepare") {
|
||||
await bootstrap(await operatorPassword());
|
||||
await import("./generate-agent-configs");
|
||||
await import("./telemetry-dashboard");
|
||||
} else if (action === "start")
|
||||
await start(
|
||||
await operatorPassword(),
|
||||
Bun.argv.includes("--checked-cache") ? "checked-cache" : "canonical",
|
||||
);
|
||||
else if (action === "wait") await waitReady();
|
||||
else if (action === "accept") {
|
||||
const { acceptanceSession } = await import("./acceptance-session");
|
||||
await createAcceptCommand({
|
||||
verifyProof: readCanonicalGitProof,
|
||||
password: operatorPassword,
|
||||
accept: (password, proof) =>
|
||||
acceptanceSession(
|
||||
password,
|
||||
Bun.argv.includes("--checked-cache")
|
||||
? "checked-cache"
|
||||
: "canonical",
|
||||
proof,
|
||||
),
|
||||
})(Bun.argv.slice(3));
|
||||
} else if (action === "unseal") {
|
||||
await unseal(await operatorPassword());
|
||||
console.log("PASS_BAO_UNSEALED");
|
||||
} else if (action === "stop") {
|
||||
await compose(["--profile", "*", "stop"]);
|
||||
console.log("PASS_OWNED_STAND_STOPPED_DATA_RETAINED");
|
||||
} else throw new Error("UNKNOWN_LAB_ACTION");
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { resolve, relative } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
run,
|
||||
compose,
|
||||
requireThat,
|
||||
privateWrite,
|
||||
safeFailure,
|
||||
} from "./runtime";
|
||||
import { verifyCheckedRuntime } from "./checked-runtime";
|
||||
import { acceptanceSession } from "./acceptance-session";
|
||||
import { decrypt } from "./operator-crypto";
|
||||
import { createBrowserLifecycle } from "./browser-lifecycle";
|
||||
import { readCanonicalGitProof } from "./git-tracking-source";
|
||||
import { type GitTrackingSource } from "./git-tracking-proof";
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"NATIVE_SECURITY_OWN_DIRECTORY_REQUIRED",
|
||||
);
|
||||
const lease = await verifyCheckedRuntime();
|
||||
const proofPath = Bun.argv[Bun.argv.indexOf("--git-proof") + 1];
|
||||
const proofSHA = Bun.argv[Bun.argv.indexOf("--git-proof-sha") + 1];
|
||||
requireThat(
|
||||
Bun.argv.includes("--git-proof") &&
|
||||
Bun.argv.includes("--git-proof-sha") &&
|
||||
/^[a-f0-9]{64}$/.test(proofSHA ?? ""),
|
||||
"CANONICAL_GIT_PROOF_REFERENCE_REQUIRED",
|
||||
);
|
||||
const gitSource: GitTrackingSource = {
|
||||
kind: "canonical-proof",
|
||||
path: proofPath,
|
||||
sha256: proofSHA,
|
||||
};
|
||||
const gitGuard = await readCanonicalGitProof(gitSource);
|
||||
requireThat(
|
||||
(
|
||||
await run([
|
||||
"docker",
|
||||
"ps",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=mtuci-vp7-security",
|
||||
"--format",
|
||||
"{{.ID}}",
|
||||
])
|
||||
).out.trim() === "",
|
||||
"NATIVE_SECURITY_OWN_STAND_ALREADY_RUNNING",
|
||||
);
|
||||
await compose(["config", "--quiet"]);
|
||||
if (Bun.argv.includes("--check")) {
|
||||
console.log(
|
||||
"PASS_NATIVE_SECURITY_INITIAL_SOURCE_BINARY_IMAGE_COMPOSE_GUARDS",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const operationId = crypto.randomUUID(),
|
||||
path = resolve(
|
||||
root,
|
||||
"evidence/openbao/native-acceptance-" + operationId + ".json",
|
||||
);
|
||||
await mkdir(resolve(path, ".."), { recursive: true });
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
state: "RUNNING",
|
||||
operation_id: operationId,
|
||||
stage: "PRESERVE_HISTORY",
|
||||
expected_git_proof: gitSource,
|
||||
source_generation_sha256: gitGuard.source_generation_sha256,
|
||||
}) + "\n",
|
||||
{ flag: "wx", mode: 0o644 },
|
||||
);
|
||||
let stage = "PRESERVE_HISTORY",
|
||||
primary: unknown,
|
||||
failed = false,
|
||||
stopExit: number | null = null,
|
||||
postGuard = false,
|
||||
remaining: number | null = null,
|
||||
stopSeconds: number | null = null,
|
||||
inner: any = null;
|
||||
const prior: Record<string, string> = {},
|
||||
hash = (b: Uint8Array) => createHash("sha256").update(b).digest("hex");
|
||||
try {
|
||||
// Reuse the tested generic required-port ownership helper; no browser dependency is loaded.
|
||||
await createBrowserLifecycle({
|
||||
acquire: async () => operationId,
|
||||
run: async () => {
|
||||
const history = resolve(local, "native-history-" + operationId);
|
||||
async function preserve(dir: string) {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const source = resolve(dir, entry.name),
|
||||
name = relative(resolve(root, "evidence/security"), source),
|
||||
target = resolve(history, "evidence/security", name);
|
||||
if (entry.isDirectory()) await preserve(source);
|
||||
else {
|
||||
requireThat(entry.isFile(), "NONREGULAR_SECURITY_EVIDENCE");
|
||||
const bytes = await readFile(source);
|
||||
await mkdir(resolve(target, ".."), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
await writeFile(target, bytes, { flag: "wx", mode: 0o600 });
|
||||
prior[name] = hash(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
await preserve(resolve(root, "evidence/security"));
|
||||
stage = "PRIVATE_OPERATOR_GUARD";
|
||||
const password = await readFile(
|
||||
resolve(root, ".local-preflight-key"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(password),
|
||||
"INVALID_PRIVATE_OPERATOR_KEY",
|
||||
);
|
||||
decrypt(
|
||||
await readFile(resolve(local, "operator/services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
stage = "NATIVE_BAO_SECURITY_ACCEPTANCE";
|
||||
await acceptanceSession(password, "checked-cache", gitSource);
|
||||
inner = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "evidence/security/session.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
requireThat(
|
||||
inner.state === "PASS" &&
|
||||
inner.runtime_mode === "checked-cache" &&
|
||||
/^[a-f0-9-]{36}$/.test(inner.operation_id),
|
||||
"NATIVE_ACCEPTANCE_RESULT_UNBOUND",
|
||||
);
|
||||
stage = "POST_SOURCE_BINARY_IMAGE_GUARDS";
|
||||
await lease.verify();
|
||||
await readCanonicalGitProof(gitSource);
|
||||
postGuard = true;
|
||||
stage = "COMPLETE";
|
||||
},
|
||||
close: async () => {
|
||||
if (stage === "COMPLETE") stage = "OWN_TEARDOWN";
|
||||
const stopStarted = Date.now();
|
||||
const stopped = await compose(["--profile", "*", "stop"], {
|
||||
allowFailure: true,
|
||||
});
|
||||
stopExit = stopped.code;
|
||||
stopSeconds = (Date.now() - stopStarted) / 1000;
|
||||
const ps = await run([
|
||||
"docker",
|
||||
"ps",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=mtuci-vp7-security",
|
||||
"--format",
|
||||
"{{.ID}}",
|
||||
]);
|
||||
remaining = ps.out.trim() ? ps.out.trim().split("\n").length : 0;
|
||||
requireThat(
|
||||
stopExit === 0 && remaining === 0,
|
||||
"NATIVE_SECURITY_TEARDOWN_FAILED",
|
||||
);
|
||||
if (stage === "OWN_TEARDOWN") stage = "COMPLETE";
|
||||
},
|
||||
reportCleanupFailure: (error) =>
|
||||
privateWrite(
|
||||
resolve(
|
||||
local,
|
||||
"diagnostics/native-security-cleanup-" + operationId + ".json",
|
||||
),
|
||||
JSON.stringify({
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
}),
|
||||
),
|
||||
})();
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
primary = error;
|
||||
await Promise.allSettled([
|
||||
privateWrite(
|
||||
resolve(
|
||||
local,
|
||||
"diagnostics/native-security-primary-" + operationId + ".json",
|
||||
),
|
||||
JSON.stringify({
|
||||
stage,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
stack: error instanceof Error ? error.stack : null,
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
try {
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify(
|
||||
{
|
||||
state:
|
||||
!failed && stopExit === 0 && remaining === 0 && postGuard
|
||||
? "PASS_DEFINED_NATIVE_ACCEPTANCE"
|
||||
: "FAILED",
|
||||
operation_id: operationId,
|
||||
stage,
|
||||
runtime_mode:
|
||||
"checked112 cached app binaries; native Bao2.7.2/PebbleDB and Agent",
|
||||
provider:
|
||||
"native OpenBao cert auto-auth/Agent, not operator heartbeat",
|
||||
backend_files: 112,
|
||||
backend_sha256: lease.source_sha256,
|
||||
image_id: lease.image_id,
|
||||
binaries: lease.binaries,
|
||||
expected_git_proof: gitSource,
|
||||
source_generation_sha256: gitGuard.source_generation_sha256,
|
||||
post_source_binary_image_guards: postGuard,
|
||||
inner_acceptance_operation: inner?.operation_id ?? null,
|
||||
inner_acceptance_receipt: "evidence/security/session.json",
|
||||
preserved_previous_public_evidence_files: Object.keys(prior).length,
|
||||
preserved_history: relative(
|
||||
root,
|
||||
resolve(local, "native-history-" + operationId),
|
||||
),
|
||||
preserved_history_hashes: prior,
|
||||
stop_exit: stopExit,
|
||||
stop_seconds: stopSeconds,
|
||||
remaining_owned_containers: remaining,
|
||||
full_security_complete: false,
|
||||
whole_telemetry_complete: false,
|
||||
grade_awarded: false,
|
||||
primary_details_private: failed,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
} catch (error) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
primary = error;
|
||||
}
|
||||
await Promise.allSettled([
|
||||
privateWrite(
|
||||
resolve(
|
||||
local,
|
||||
"diagnostics/native-security-receipt-" + operationId + ".json",
|
||||
),
|
||||
JSON.stringify({
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
receipt: path,
|
||||
state:
|
||||
!failed && stopExit === 0 && remaining === 0 && postGuard
|
||||
? "PASS_DEFINED_NATIVE_ACCEPTANCE"
|
||||
: "FAILED",
|
||||
stage,
|
||||
stop_exit: stopExit,
|
||||
remaining_owned_containers: remaining,
|
||||
}),
|
||||
);
|
||||
if (failed) throw primary;
|
||||
requireThat(
|
||||
stopExit === 0 && remaining === 0,
|
||||
"NATIVE_SECURITY_TEARDOWN_FAILED",
|
||||
);
|
||||
}
|
||||
if (import.meta.main)
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { readFile, open } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { bao } from "./bao-client";
|
||||
import { encrypt, decrypt, operatorPassword } from "./operator-crypto";
|
||||
import { local, root, privateWrite, requireThat, safeFailure } from "./runtime";
|
||||
export type BaoOperator = { root_token: string; keys_base64: string[] };
|
||||
export async function unlock(password: string) {
|
||||
return decrypt<BaoOperator>(
|
||||
await readFile(resolve(local, "operator", "bao.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
}
|
||||
export async function initialize(password: string) {
|
||||
const status = await bao("/sys/init");
|
||||
requireThat(
|
||||
status.data.initialized === false,
|
||||
"BAO_ALREADY_INITIALIZED_USE_UNSEAL",
|
||||
);
|
||||
const claim = await open(
|
||||
resolve(local, "operator", "bao-init-claim.json"),
|
||||
"wx",
|
||||
0o600,
|
||||
);
|
||||
await claim.writeFile('{"state":"RUNNING"}');
|
||||
await claim.close();
|
||||
let response: Awaited<ReturnType<typeof bao>>;
|
||||
try {
|
||||
response = await bao("/sys/init", {
|
||||
method: "PUT",
|
||||
body: { secret_shares: 3, secret_threshold: 2 },
|
||||
});
|
||||
} catch (error) {
|
||||
// An accepted init can lose its response. Encrypt any partial transport receipt before other diagnostics.
|
||||
const path = resolve(local, "diagnostics", "last-command.json");
|
||||
if (await Bun.file(path).exists()) {
|
||||
const captured = await readFile(path, "utf8");
|
||||
await privateWrite(
|
||||
resolve(local, "operator", "bao-init-uncertain.enc"),
|
||||
encrypt({ transport_receipt: captured }, password),
|
||||
);
|
||||
await privateWrite(
|
||||
path,
|
||||
'{"stage":"BAO_INIT_UNCERTAIN","details":"encrypted operator receipt"}',
|
||||
);
|
||||
}
|
||||
await privateWrite(
|
||||
resolve(local, "operator", "bao-init-claim.json"),
|
||||
'{"state":"INIT_UNCERTAIN_DO_NOT_RETRY"}',
|
||||
);
|
||||
throw new Error("BAO_INIT_UNCERTAIN_DO_NOT_RETRY");
|
||||
}
|
||||
// Persist encrypted init receipt before any readback or unseal; uncertain writes are never automatically retried.
|
||||
await privateWrite(
|
||||
resolve(local, "operator", "bao.enc"),
|
||||
encrypt(response.data, password),
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "operator", "bao-init-claim.json"),
|
||||
'{"state":"INIT_SAVED_ENCRYPTED"}',
|
||||
);
|
||||
await unseal(password);
|
||||
await configure(password);
|
||||
console.log("PASS_BAO_NONDEV_INIT_UNSEAL_SCOPED_CERT_AUTH");
|
||||
}
|
||||
export async function unseal(password: string) {
|
||||
const op = await unlock(password);
|
||||
for (const key of op.keys_base64.slice(0, 2))
|
||||
await bao("/sys/unseal", { method: "PUT", body: { key } });
|
||||
const status = await bao("/sys/seal-status");
|
||||
requireThat(status.data.sealed === false, "BAO_STILL_SEALED");
|
||||
}
|
||||
export async function configure(password: string) {
|
||||
const op = await unlock(password),
|
||||
token = op.root_token;
|
||||
await bao("/sys/mounts/kv", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: { type: "kv", options: { version: "2" } },
|
||||
});
|
||||
await bao("/sys/auth/cert", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: { type: "cert" },
|
||||
});
|
||||
const cert = await readFile(
|
||||
resolve(local, "operator", "ca", "ca.crt"),
|
||||
"utf8",
|
||||
);
|
||||
for (const role of ["api", "worker"]) {
|
||||
const policy = await readFile(
|
||||
resolve(root, "infra/openbao", role + ".hcl"),
|
||||
"utf8",
|
||||
);
|
||||
await bao("/sys/policies/acl/" + role, {
|
||||
method: "PUT",
|
||||
token,
|
||||
body: { policy },
|
||||
});
|
||||
await bao("/auth/cert/certs/" + role, {
|
||||
method: "POST",
|
||||
token,
|
||||
body: {
|
||||
display_name: role,
|
||||
certificate: cert,
|
||||
allowed_common_names: [role],
|
||||
allowed_dns_sans: [role],
|
||||
token_policies: [role],
|
||||
token_no_default_policy: true,
|
||||
token_ttl: 60,
|
||||
token_max_ttl: 300,
|
||||
},
|
||||
});
|
||||
}
|
||||
const secrets = decrypt<any>(
|
||||
await readFile(resolve(local, "operator", "services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
for (const role of ["api", "worker"]) {
|
||||
const suffix = role === "api" ? "Api" : "Worker";
|
||||
await bao("/kv/data/" + role, {
|
||||
method: "POST",
|
||||
token,
|
||||
body: {
|
||||
data: {
|
||||
database_url: `postgresql://${role}@127.0.0.1:15432/messenger?sslmode=disable`,
|
||||
cache_url: `redis://${role}:${secrets["broker" + suffix]}@127.0.0.1:16379/0`,
|
||||
...(role === "worker"
|
||||
? {
|
||||
publisher_url: `redis://publisher:${secrets.brokerPublisher}@127.0.0.1:16379/0`,
|
||||
}
|
||||
: {}),
|
||||
s3_json: JSON.stringify({
|
||||
Endpoint: "127.0.0.1:19000",
|
||||
Access: secrets["s3" + suffix + "Access"],
|
||||
Secret: secrets["s3" + suffix + "Secret"],
|
||||
Bucket: "messenger-attachments",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
// OpenBao2.7 manages this device through the server HCL audit stanza.
|
||||
// API-driven device creation is disabled by default; retain that native boundary.
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const password = await operatorPassword();
|
||||
const action = Bun.argv[2];
|
||||
if (action === "init") await initialize(password);
|
||||
else if (action === "unseal") {
|
||||
await unseal(password);
|
||||
console.log("PASS_BAO_UNSEALED");
|
||||
} else throw new Error("USE_INIT_OR_UNSEAL");
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
export type Principal = "ingest" | "query";
|
||||
export interface Account {
|
||||
user: string;
|
||||
token: string;
|
||||
}
|
||||
export interface AccountPorts {
|
||||
create: (
|
||||
path: string,
|
||||
body: { email: string; first_name: string; last_name: string },
|
||||
) => Promise<{ status: number; data: unknown }>;
|
||||
save: (principal: Principal, account: Account) => Promise<void>;
|
||||
}
|
||||
export function createAccountProvisioner(ports: AccountPorts) {
|
||||
if (typeof ports.create !== "function" || typeof ports.save !== "function")
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_PORTS_REQUIRED");
|
||||
return async (principal: Principal): Promise<Account> => {
|
||||
if (principal !== "ingest" && principal !== "query")
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_INVALID_PRINCIPAL");
|
||||
const email = `vp7-${principal}@example.invalid`;
|
||||
const response = await ports.create("/api/default/service_accounts", {
|
||||
email,
|
||||
first_name: "VP7",
|
||||
last_name: principal,
|
||||
});
|
||||
if (response.status !== 200)
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_CREATE_REJECTED");
|
||||
const data = response.data as (Partial<Account> & { code?: number }) | null;
|
||||
if (
|
||||
data?.code !== 200 ||
|
||||
data.user !== email ||
|
||||
typeof data.token !== "string" ||
|
||||
data.token.length < 1 ||
|
||||
data.token.length > 4096 ||
|
||||
/[\r\n\x00]/.test(data.token)
|
||||
)
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_INVALID_RESPONSE");
|
||||
const account = { user: data.user, token: data.token };
|
||||
await ports.save(principal, account);
|
||||
return account;
|
||||
};
|
||||
}
|
||||
export interface AccountWorkflowPorts {
|
||||
positive: (principal: Principal, account: Account) => Promise<number>;
|
||||
deny: (principal: Principal, account: Account) => Promise<number>;
|
||||
publish: (accounts: Record<Principal, Account>) => Promise<void>;
|
||||
}
|
||||
export function validateStoredAccount(
|
||||
principal: Principal,
|
||||
input: unknown,
|
||||
): Account {
|
||||
if (principal !== "ingest" && principal !== "query")
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_INVALID_PRINCIPAL");
|
||||
const account = input as Partial<Account> | null;
|
||||
if (
|
||||
!account ||
|
||||
account.user !== `vp7-${principal}@example.invalid` ||
|
||||
typeof account.token !== "string" ||
|
||||
account.token.length < 1 ||
|
||||
account.token.length > 4096 ||
|
||||
!/^[A-Za-z0-9!#%+,.\/:;=?@^_~-]+$/.test(account.token)
|
||||
)
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_INVALID_RESPONSE");
|
||||
return { user: account.user, token: account.token };
|
||||
}
|
||||
export function createAccountWorkflow(ports: AccountWorkflowPorts) {
|
||||
if (
|
||||
!ports ||
|
||||
typeof ports.positive !== "function" ||
|
||||
typeof ports.deny !== "function" ||
|
||||
typeof ports.publish !== "function"
|
||||
)
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_WORKFLOW_PORTS_REQUIRED");
|
||||
const { positive, deny, publish } = ports;
|
||||
return async (accounts: Record<Principal, Account>) => {
|
||||
if (
|
||||
!accounts ||
|
||||
JSON.stringify(Object.keys(accounts).sort()) !==
|
||||
JSON.stringify(["ingest", "query"])
|
||||
)
|
||||
throw new Error("OPENOBSERVE_ACCOUNT_SLOTS_INVALID");
|
||||
const checked = {
|
||||
ingest: validateStoredAccount("ingest", accounts.ingest),
|
||||
query: validateStoredAccount("query", accounts.query),
|
||||
};
|
||||
const controls: {
|
||||
principal: Principal;
|
||||
positive_http: number;
|
||||
deny_http: number;
|
||||
}[] = [];
|
||||
for (const name of ["ingest", "query"] as const) {
|
||||
const success = await positive(name, { ...checked[name] });
|
||||
if (success !== 200)
|
||||
throw new Error(
|
||||
`OPENOBSERVE_CREDENTIAL_${name.toUpperCase()}_POSITIVE_HTTP_${success}`,
|
||||
);
|
||||
const rejected = await deny(name, { ...checked[name] });
|
||||
if (rejected !== 403)
|
||||
throw new Error(
|
||||
`OPENOBSERVE_CREDENTIAL_${name.toUpperCase()}_DENY_HTTP_${rejected}`,
|
||||
);
|
||||
controls.push({
|
||||
principal: name,
|
||||
positive_http: success,
|
||||
deny_http: rejected,
|
||||
});
|
||||
}
|
||||
await publish(checked);
|
||||
return controls;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
const copyRoot =
|
||||
"/mnt/data/home/bench-saves/mtuci-vp-remaining-20261115/lab6/.local/oci-copy-21c9f273-7c3d-4235-9522-b2ade24db55c";
|
||||
const declarations = [
|
||||
{
|
||||
name: "openobserve",
|
||||
source: "mtuci-vp6-openobserve-cache:v1.1.2",
|
||||
target: "mtuci-vp7-openobserve-cache:v1.1.2-26618f379c86",
|
||||
digest:
|
||||
"sha256:26618f379c86b253c0d91624c487dd14b71293699845ecbc8457c94dca14819f",
|
||||
layers: 26,
|
||||
},
|
||||
{
|
||||
name: "collector",
|
||||
source: "mtuci-vp6-collector-cache:0.163.2",
|
||||
target: "mtuci-vp7-collector-cache:0.163.2-a65df9129a5b",
|
||||
digest:
|
||||
"sha256:a65df9129a5b3f99ee4434c5e53aee1965ff0129eda6a2da75ea917165b7fa6b",
|
||||
layers: 2,
|
||||
},
|
||||
];
|
||||
async function inspect(image: string) {
|
||||
return JSON.parse((await run(["docker", "image", "inspect", image])).out)[0];
|
||||
}
|
||||
export async function freezeCachedImages(apply: boolean) {
|
||||
const lease = await verifyBackendHandover();
|
||||
const receiptPaths = [
|
||||
resolve(copyRoot, "COPY.json"),
|
||||
resolve(copyRoot, "OPENOBSERVE-COMPLETE.json"),
|
||||
resolve(
|
||||
copyRoot,
|
||||
"openobserve-import-8b8023dc-a86f-4d88-9eeb-e3d94ad755cf/IMPORT-READY.json",
|
||||
),
|
||||
];
|
||||
const receipts = await Promise.all(
|
||||
receiptPaths.map(async (path) => {
|
||||
const bytes = await readFile(path);
|
||||
return {
|
||||
path,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
data: JSON.parse(bytes.toString()),
|
||||
};
|
||||
}),
|
||||
);
|
||||
const copy = receipts[0].data,
|
||||
complete = receipts[1].data,
|
||||
ready = receipts[2].data;
|
||||
requireThat(
|
||||
copy.nodeStopped === true &&
|
||||
copy.sourceMutated === false &&
|
||||
copy.copied.length > 0 &&
|
||||
copy.copied.every((d: any) => d.shaVerified === true),
|
||||
"CACHE_SOURCE_COPY_NOT_VERIFIED",
|
||||
);
|
||||
requireThat(
|
||||
complete.complete === true &&
|
||||
complete.manifestDigest === declarations[0].digest &&
|
||||
ready.completeRehashed === true &&
|
||||
ready.manifestDigest === complete.manifestDigest &&
|
||||
ready.configDigest === complete.configDigest,
|
||||
"CACHE_OPENOBSERVE_HANDOVER_INVALID",
|
||||
);
|
||||
requireThat(
|
||||
copy.complete.some(
|
||||
(entry: any) =>
|
||||
entry.id === "collector" &&
|
||||
entry.manifestDigest === declarations[1].digest,
|
||||
),
|
||||
"CACHE_COLLECTOR_HANDOVER_INVALID",
|
||||
);
|
||||
const images = [];
|
||||
for (const item of declarations) {
|
||||
const source = await inspect(item.source);
|
||||
requireThat(
|
||||
source.Id === item.digest &&
|
||||
source.Os === "linux" &&
|
||||
source.Architecture === "amd64" &&
|
||||
source.RootFS.Layers.length === item.layers &&
|
||||
source.RepoDigests.some((d: string) => d.endsWith("@" + item.digest)),
|
||||
"CACHE_IMAGE_IDENTITY_INVALID",
|
||||
);
|
||||
const existing = await run(["docker", "image", "inspect", item.target], {
|
||||
allowFailure: true,
|
||||
});
|
||||
if (existing.code === 0)
|
||||
requireThat(
|
||||
JSON.parse(existing.out)[0].Id === item.digest,
|
||||
"CACHE_OWN_ALIAS_CONFLICT",
|
||||
);
|
||||
else if (apply)
|
||||
await run(["docker", "image", "tag", source.Id, item.target]);
|
||||
if (apply)
|
||||
requireThat(
|
||||
(await inspect(item.target)).Id === item.digest,
|
||||
"CACHE_OWN_ALIAS_POSTGUARD_FAILED",
|
||||
);
|
||||
images.push({
|
||||
...item,
|
||||
image_id: source.Id,
|
||||
platform: "linux/amd64",
|
||||
normalized_docker_identity: true,
|
||||
upstream_config_digest_not_assumed: true,
|
||||
});
|
||||
}
|
||||
requireThat(
|
||||
(await verifyBackendHandover()).sha256 === lease.sha256,
|
||||
"CACHE_BACKEND_GENERATION_CHANGED",
|
||||
);
|
||||
if (apply) {
|
||||
const target = resolve(root, "evidence/openobserve/image-freeze.json");
|
||||
await mkdir(resolve(target, ".."), { recursive: true });
|
||||
const bytes =
|
||||
JSON.stringify(
|
||||
{
|
||||
checkedAt: new Date().toISOString(),
|
||||
source_receipts: receipts.map(({ path, sha256 }) => ({
|
||||
path,
|
||||
sha256,
|
||||
})),
|
||||
images,
|
||||
no_network_pulls: true,
|
||||
source_cache_mutated: false,
|
||||
backend_handover_sha256: lease.sha256,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
await writeFile(target, bytes, { flag: "wx", mode: 0o600 });
|
||||
}
|
||||
console.log(
|
||||
apply
|
||||
? "PASS_OWN_CACHED_ALIASES_FROZEN_NO_PULL"
|
||||
: "PASS_READONLY_CACHE_LEASE_AND_PLATFORM",
|
||||
);
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
requireThat(
|
||||
["--check", "--apply"].includes(Bun.argv[2]),
|
||||
"CACHE_ACTION_CHECK_OR_APPLY_REQUIRED",
|
||||
);
|
||||
await freezeCachedImages(Bun.argv[2] === "--apply");
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { run, safeFailure } from "./runtime";
|
||||
try {
|
||||
await import("./telemetry-dashboard");
|
||||
await run([
|
||||
process.execPath,
|
||||
"test",
|
||||
"student-tests/openobserve-config.test.ts",
|
||||
"student-tests/openobserve-topology.test.ts",
|
||||
]);
|
||||
console.log("PASS_OPENOBSERVE_GENERATED_CONFIG_REGRESSIONS");
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
import { readFile, writeFile, mkdir, rename } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
privateWrite,
|
||||
requireThat,
|
||||
safeFailure,
|
||||
} from "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
import { waitReady } from "../student-tests/wait";
|
||||
import { openObserveRequest } from "./openobserve";
|
||||
import { assertOpenObserveSignals } from "../student-tests/openobserve-signals";
|
||||
const components = [
|
||||
"postgres",
|
||||
"broker-gateway",
|
||||
"broker",
|
||||
"s3-gateway",
|
||||
"s3",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"worker-gateway",
|
||||
"lb",
|
||||
"openobserve-gateway",
|
||||
"openobserve",
|
||||
"collector-gateway",
|
||||
"collector",
|
||||
];
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"OPENOBSERVE_PIPELINE_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/openobserve",
|
||||
"pipeline-" + 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,
|
||||
heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
let heartbeatError = false;
|
||||
try {
|
||||
const lease = await verifyBackendHandover();
|
||||
requireThat(
|
||||
lease.sha256 ===
|
||||
"09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609",
|
||||
"OPENOBSERVE_PIPELINE_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 = "CHECKED112_APP_BINARY";
|
||||
const build = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "evidence/preflight/checked112-build.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
requireThat(
|
||||
build.source_handover_sha256 === lease.sha256,
|
||||
"OPENOBSERVE_APP_RECEIPT_GENERATION_MISMATCH",
|
||||
);
|
||||
const image = JSON.parse(
|
||||
(
|
||||
await run([
|
||||
"docker",
|
||||
"image",
|
||||
"inspect",
|
||||
"mtuci-vp7-security-app:local",
|
||||
])
|
||||
).out,
|
||||
)[0];
|
||||
const binaries = (
|
||||
await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--pull=never",
|
||||
"--network",
|
||||
"none",
|
||||
"--read-only",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--entrypoint",
|
||||
"/bin/sh",
|
||||
image.Id,
|
||||
"-c",
|
||||
"sha256sum /app /worker",
|
||||
])
|
||||
).out
|
||||
.trim()
|
||||
.split("\n");
|
||||
requireThat(
|
||||
binaries.length === 2 &&
|
||||
binaries[0].split(/\s+/)[0] === build.binaries.app &&
|
||||
binaries[1].split(/\s+/)[0] === build.binaries.worker,
|
||||
"OPENOBSERVE_APP_BINARY_DRIFT",
|
||||
);
|
||||
stage = "OPERATOR_PROVIDER_FILES";
|
||||
const password = await readFile(
|
||||
resolve(root, ".local-preflight-key"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(password),
|
||||
"INVALID_PREFLIGHT_SESSION_KEY",
|
||||
);
|
||||
for (const name of ["api1", "api2", "worker"])
|
||||
for (const file of [
|
||||
"database_url",
|
||||
"cache_url",
|
||||
"s3.json",
|
||||
...(name === "worker" ? ["publisher_url"] : []),
|
||||
])
|
||||
requireThat(
|
||||
(await Bun.file(resolve(local, "rendered", name, file)).stat()).size >
|
||||
0,
|
||||
"OPENOBSERVE_SCOPED_PROVIDER_FILE_MISSING",
|
||||
);
|
||||
stage = "NATIVE_STORES_START";
|
||||
started = true;
|
||||
await compose(["up", "-d", "--no-build", ...components]);
|
||||
stage = "OPENOBSERVE_READY";
|
||||
let storageReady = false;
|
||||
const bootDeadline = Date.now() + 60_000;
|
||||
while (Date.now() < bootDeadline) {
|
||||
try {
|
||||
if (
|
||||
(
|
||||
await openObserveRequest("/api/default/streams", {
|
||||
password,
|
||||
account: "query",
|
||||
role: "grafana",
|
||||
})
|
||||
).status === 200
|
||||
) {
|
||||
storageReady = true;
|
||||
break;
|
||||
}
|
||||
} catch {}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(storageReady, "OPENOBSERVE_PIPELINE_STORAGE_START_TIMEOUT");
|
||||
stage = "SIGNALS_BASELINE_RED";
|
||||
let baselineRed: string | null = null;
|
||||
try {
|
||||
await assertOpenObserveSignals(password, Date.now() - 60_000);
|
||||
} catch (error) {
|
||||
const code = error instanceof Error ? error.message : "";
|
||||
requireThat(
|
||||
[
|
||||
"OPENOBSERVE_TRACE_STREAM_MISSING",
|
||||
"OPENOBSERVE_WORKER_TRACE_MISSING",
|
||||
"OPENOBSERVE_SIGNAL_QUERY_REJECTED",
|
||||
].includes(code),
|
||||
"OPENOBSERVE_BASELINE_WRONG_FAILURE",
|
||||
);
|
||||
baselineRed = code;
|
||||
}
|
||||
requireThat(
|
||||
baselineRed !== null,
|
||||
"OPENOBSERVE_SIGNAL_BASELINE_ALREADY_POPULATED",
|
||||
);
|
||||
const start = Date.now() - 1000;
|
||||
const timestamp = async () => {
|
||||
for (const name of ["api1", "api2", "worker"]) {
|
||||
const path = resolve(local, "rendered", name, "freshness"),
|
||||
temporary = path + "." + crypto.randomUUID();
|
||||
await privateWrite(temporary, new Date().toISOString() + "\n");
|
||||
await rename(temporary, path);
|
||||
}
|
||||
};
|
||||
await timestamp();
|
||||
let writing = false;
|
||||
heartbeat = setInterval(() => {
|
||||
if (writing) return;
|
||||
writing = true;
|
||||
timestamp()
|
||||
.catch(() => {
|
||||
heartbeatError = true;
|
||||
})
|
||||
.finally(() => {
|
||||
writing = false;
|
||||
});
|
||||
}, 1000);
|
||||
stage = "CURRENT112_API_WORKER_START";
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"--no-build",
|
||||
"--no-deps",
|
||||
"api1",
|
||||
"api2",
|
||||
"worker",
|
||||
]);
|
||||
await waitReady();
|
||||
stage = "CURRENT112_PUBLIC_SMOKE";
|
||||
const smoke = await run(["make", "test"], {
|
||||
env: {
|
||||
BASE_URL: "https://localhost:18443",
|
||||
CA_FILE: resolve(local, "pki/lb/ca.crt"),
|
||||
},
|
||||
});
|
||||
await writeFile(receipt + ".public-smoke.txt", smoke.out + smoke.err, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
stage = "CURRENT112_NATIVE_ALL3_READBACK";
|
||||
let signals:
|
||||
Awaited<ReturnType<typeof assertOpenObserveSignals>> | undefined;
|
||||
let lastCode = "OPENOBSERVE_SIGNAL_NOT_CHECKED";
|
||||
const signalDeadline = Date.now() + 90_000;
|
||||
while (Date.now() < signalDeadline) {
|
||||
try {
|
||||
signals = await assertOpenObserveSignals(password, start);
|
||||
break;
|
||||
} catch (error) {
|
||||
lastCode =
|
||||
error instanceof Error ? error.message : "OPENOBSERVE_SIGNAL_UNKNOWN";
|
||||
}
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
requireThat(signals, "OPENOBSERVE_ALL3_NOT_READY_" + lastCode);
|
||||
requireThat(!heartbeatError, "OPENOBSERVE_OPERATOR_HEARTBEAT_FAILED");
|
||||
stage = "CURRENT112_SOURCE_POSTGUARD";
|
||||
await lease.verify();
|
||||
requireThat(
|
||||
(await verifyBackendHandover()).sha256 === lease.sha256,
|
||||
"OPENOBSERVE_PIPELINE_GENERATION_CHANGED",
|
||||
);
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_SCOPED_NATIVE_ALL3",
|
||||
stage,
|
||||
source_handover_sha256: lease.sha256,
|
||||
binaries: build.binaries,
|
||||
image_id: image.Id,
|
||||
baseline_red: baselineRed,
|
||||
provider:
|
||||
"existing scoped operator files + explicit heartbeat; not OpenBao",
|
||||
signals,
|
||||
native_grafana: false,
|
||||
native_bao: false,
|
||||
grade5: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_CURRENT112_NATIVE_ALL3_NO_BAO_OR_GRAFANA_ACCEPTANCE");
|
||||
} 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 (heartbeat) clearInterval(heartbeat);
|
||||
if (started) {
|
||||
const stop = await Promise.allSettled([
|
||||
compose(["stop", "api1", "api2", "worker", ...components], {
|
||||
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_PIPELINE_STOP_FAILED");
|
||||
console.log(
|
||||
stopped
|
||||
? "OWN_ALL3_STAND_STOPPED"
|
||||
: "OWN_ALL3_STOP_REQUIRES_INSPECTION",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Native HAProxy request guards originate in lab6 dd110001, histogram delta04ca06e9.
|
||||
// The response block8aa801e8 is independently reviewed; lab7 retains its own8MiB budget.
|
||||
// TLS CN=grafana replaces lab6 HTTP auth. Operator bootstrap stays a separate client identity.
|
||||
// query.size is an input guard, not a hard result row cap: SQL has independent LIMIT semantics.
|
||||
export const openobserveQueryPolicy = String.raw` timeout client 10s
|
||||
timeout server 10s
|
||||
timeout http-request 3s
|
||||
timeout http-keep-alive 1s
|
||||
timeout queue 1s
|
||||
acl grafana ssl_c_s_dn(CN) -m str grafana
|
||||
acl read_method method GET
|
||||
acl search_method method POST
|
||||
acl search_path path -m str /api/default/_search
|
||||
acl read_path path -m str /api/organizations /api/default/streams
|
||||
acl read_path path_reg ^/api/default/streams/[A-Za-z0-9_]+/schema$
|
||||
acl read_path path -m str /api/default/messenger/_values
|
||||
acl read_path path_reg ^/api/default/prometheus/api/v1/(query|query_range|labels|series|metadata)$
|
||||
acl read_path path_reg ^/api/default/prometheus/api/v1/label/[A-Za-z0-9_]+/values$
|
||||
http-request deny deny_status 403 unless !grafana or read_method read_path or search_method search_path
|
||||
http-request wait-for-body time 2s if grafana search_method search_path
|
||||
http-request deny deny_status 413 if grafana search_method search_path { req.body_len gt 65536 }
|
||||
http-request set-var(txn.rows) req.body,json_query('$.query.size','int') if grafana search_method search_path
|
||||
http-request set-var(txn.begin) req.body,json_query('$.query.start_time','int') if grafana search_method search_path
|
||||
http-request set-var(txn.end) req.body,json_query('$.query.end_time','int') if grafana search_method search_path
|
||||
http-request set-var(txn.window) var(txn.end),sub(txn.begin) if grafana search_method search_path
|
||||
# Native plugin supplementary histogram omits size; preserve native default and explicit zero.
|
||||
acl search_size_present req.body,json_query('$.query.size') -m found
|
||||
http-request deny deny_status 400 if grafana search_method search_path search_size_present !{ var(txn.rows) -m int 0:1000 }
|
||||
http-request deny deny_status 400 if grafana search_method search_path !{ var(txn.begin) -m int gt 0 }
|
||||
http-request deny deny_status 400 if grafana search_method search_path !{ var(txn.window) -m int 1:3600000000 }
|
||||
acl duplicate_query query,url_dec -m reg (^|&)size=[^&]*(&[^&]*)*&size= (^|&)start_time=[^&]*(&[^&]*)*&start_time= (^|&)end_time=[^&]*(&[^&]*)*&end_time= (^|&)start=[^&]*(&[^&]*)*&start= (^|&)end=[^&]*(&[^&]*)*&end= (^|&)query=[^&]*(&[^&]*)*&query=
|
||||
http-request deny deny_status 400 if grafana read_method duplicate_query
|
||||
acl values_path path -m str /api/default/messenger/_values
|
||||
http-request set-var(txn.rows) url_param(size),add(0) if grafana read_method values_path
|
||||
http-request set-var(txn.begin) url_param(start_time),add(0) if grafana read_method values_path
|
||||
http-request set-var(txn.end) url_param(end_time),add(0) if grafana read_method values_path
|
||||
http-request set-var(txn.window) var(txn.end),sub(txn.begin) if grafana read_method values_path
|
||||
http-request deny deny_status 400 if grafana read_method values_path !{ var(txn.rows) -m int 1:1000 }
|
||||
http-request deny deny_status 400 if grafana read_method values_path !{ var(txn.window) -m int 1:3600000000 }
|
||||
acl range_path path -m str /api/default/prometheus/api/v1/query_range
|
||||
http-request set-var(txn.begin_s) url_param(start),field(1,.),add(0) if grafana read_method range_path
|
||||
http-request set-var(txn.end_s) url_param(end),field(1,.),add(0) if grafana read_method range_path
|
||||
http-request set-var(txn.window_s) var(txn.end_s),sub(txn.begin_s) if grafana read_method range_path
|
||||
http-request deny deny_status 400 if grafana read_method range_path !{ var(txn.begin_s) -m int gt 0 }
|
||||
http-request deny deny_status 400 if grafana read_method range_path !{ var(txn.window_s) -m int 1:3599 }
|
||||
# Recognized native OO framing only; not a streaming/decompression or SQL work cap.
|
||||
# Adapted from reviewed lab6 8aa801e8, retaining lab7's mTLS identities and 8MiB budget.
|
||||
http-request set-header Accept-Encoding identity
|
||||
acl response_encoded res.fhdr_cnt(Content-Encoding) gt 0
|
||||
acl response_transfer_encoded res.fhdr_cnt(Transfer-Encoding) gt 0
|
||||
acl response_length_single res.fhdr_cnt(Content-Length) eq 1
|
||||
acl response_length_canonical res.fhdr(Content-Length) -m reg ^(0|[1-9][0-9]{0,6})$
|
||||
acl response_length_excessive res.fhdr(Content-Length) -m int gt 8388608
|
||||
http-response return status 502 content-type application/json string '{"error":"query_response_boundary"}' if response_encoded or response_transfer_encoded or !response_length_single or !response_length_canonical or response_length_excessive
|
||||
`;
|
||||
@@ -0,0 +1,208 @@
|
||||
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 "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
import { openObserveRequest } from "./openobserve";
|
||||
import { assertOpenObserveSignals } from "../student-tests/openobserve-signals";
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"OPENOBSERVE_READBACK_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const parentPath = resolve(
|
||||
root,
|
||||
"evidence/openobserve/pipeline-fc1a31a6-7c89-4e10-98d4-fb127a6e352a.json",
|
||||
);
|
||||
const parentBytes = await readFile(parentPath),
|
||||
parent = JSON.parse(parentBytes.toString()),
|
||||
parentTime = (await stat(parentPath)).mtimeMs;
|
||||
requireThat(
|
||||
parent.state === "FAILED" &&
|
||||
parent.stage === "CURRENT112_NATIVE_ALL3_READBACK" &&
|
||||
parent.code ===
|
||||
"OPENOBSERVE_ALL3_NOT_READY_INVALID_OPENOBSERVE_REQUEST_PATH",
|
||||
"OPENOBSERVE_READBACK_PARENT_MISMATCH",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/openobserve",
|
||||
"persisted-readback-" + 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_READBACK_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 = "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_AUTHENTICATED_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_READBACK_STORAGE_TIMEOUT");
|
||||
stage = "PERSISTED_ACTUAL112_SIGNALS";
|
||||
const signals = await assertOpenObserveSignals(
|
||||
password,
|
||||
parentTime - 15 * 60_000,
|
||||
parentTime - 5000,
|
||||
);
|
||||
stage = "PERSISTENCE_RESTART";
|
||||
await compose(["restart", "openobserve"]);
|
||||
let recovered: typeof signals | undefined;
|
||||
const recoveryDeadline = Date.now() + 60_000;
|
||||
while (Date.now() < recoveryDeadline) {
|
||||
try {
|
||||
recovered = await assertOpenObserveSignals(
|
||||
password,
|
||||
parentTime - 15 * 60_000,
|
||||
parentTime - 5000,
|
||||
);
|
||||
break;
|
||||
} catch {}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(
|
||||
recovered && recovered.trace_id === signals.trace_id,
|
||||
"OPENOBSERVE_PERSISTED_SIGNALS_CHANGED",
|
||||
);
|
||||
stage = "SOURCE_POSTGUARD";
|
||||
await lease.verify();
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_PERSISTED_ACTUAL112_ALL3_READBACK",
|
||||
stage,
|
||||
parent_failure: {
|
||||
path: parentPath,
|
||||
sha256: createHash("sha256").update(parentBytes).digest("hex"),
|
||||
state: parent.state,
|
||||
stage: parent.stage,
|
||||
code: parent.code,
|
||||
},
|
||||
source_handover_sha256: lease.sha256,
|
||||
signals,
|
||||
restart_retained_same_trace: true,
|
||||
query_time_milliseconds: parentTime - 5000,
|
||||
producer_repeated: false,
|
||||
smoke_repeated: false,
|
||||
native_bao: false,
|
||||
native_grafana: false,
|
||||
grade5: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log(
|
||||
"PASS_PERSISTED_ACTUAL112_ALL3_NATIVE_QUERIES_NO_BAO_OR_GRAFANA",
|
||||
);
|
||||
} 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_READBACK_STOP_FAILED");
|
||||
console.log(
|
||||
stopped
|
||||
? "OWN_READBACK_STORAGE_STOPPED"
|
||||
: "OWN_READBACK_STOP_REQUIRES_INSPECTION",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export function validateOpenObservePath(path: string) {
|
||||
if (
|
||||
!/^\/api\/(?:organizations|default\/[A-Za-z0-9_/@.%-]+|default\/prometheus\/api\/v1\/[A-Za-z0-9_]+)(?:\?[A-Za-z0-9_=%&.,:+-]+)?$/.test(
|
||||
path,
|
||||
)
|
||||
)
|
||||
throw new Error("INVALID_OPENOBSERVE_REQUEST_PATH");
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export function parseOpenObserveResponse(status: number, body: string) {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = body.length ? JSON.parse(body) : null;
|
||||
} catch {
|
||||
if (status >= 400) return { status, data: null };
|
||||
throw new Error(`OPENOBSERVE_HTTP_${status}_INVALID_JSON`);
|
||||
}
|
||||
return { status, data };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export function nativeSearchWindow(
|
||||
startMilliseconds: number,
|
||||
endMilliseconds: number,
|
||||
) {
|
||||
const start_time = Math.trunc(startMilliseconds * 1000),
|
||||
end_time = Math.trunc(endMilliseconds * 1000);
|
||||
if (
|
||||
!Number.isFinite(startMilliseconds) ||
|
||||
!Number.isFinite(endMilliseconds) ||
|
||||
!Number.isSafeInteger(start_time) ||
|
||||
!Number.isSafeInteger(end_time) ||
|
||||
start_time <= 0 ||
|
||||
end_time <= start_time ||
|
||||
end_time - start_time > 3600000000
|
||||
)
|
||||
throw new Error("INVALID_OPENOBSERVE_SEARCH_WINDOW");
|
||||
return { start_time, end_time };
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
requireThat,
|
||||
safeFailure,
|
||||
privateWrite,
|
||||
} from "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
import { writeTopology } from "./topology";
|
||||
import { issue } from "./pki";
|
||||
import {
|
||||
prepareOpenObserve,
|
||||
provisionOpenObserve,
|
||||
openObserveRequest,
|
||||
} from "./openobserve";
|
||||
async function main() {
|
||||
requireThat(
|
||||
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
|
||||
"OPENOBSERVE_SESSION_REMOTE_BOUNDARY_REQUIRED",
|
||||
);
|
||||
const receipt = resolve(
|
||||
root,
|
||||
"evidence/openobserve",
|
||||
"native-session-" + 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,
|
||||
failed = false;
|
||||
try {
|
||||
const lease = await verifyBackendHandover();
|
||||
requireThat(
|
||||
lease.sha256 ===
|
||||
"09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609",
|
||||
"OPENOBSERVE_BACKEND_GENERATION_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 = "CACHED_IMAGE_FREEZE";
|
||||
const freeze = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "evidence/openobserve/image-freeze.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
for (const image of freeze.images) {
|
||||
const current = JSON.parse(
|
||||
(await run(["docker", "image", "inspect", image.target])).out,
|
||||
)[0];
|
||||
requireThat(
|
||||
current.Id === image.image_id &&
|
||||
current.Os === "linux" &&
|
||||
current.Architecture === "amd64",
|
||||
"OPENOBSERVE_CACHED_IMAGE_DRIFT",
|
||||
);
|
||||
}
|
||||
stage = "OPERATOR_KEY";
|
||||
const password = await readFile(
|
||||
resolve(root, ".local-preflight-key"),
|
||||
"utf8",
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{64}$/.test(password),
|
||||
"INVALID_PREFLIGHT_SESSION_KEY",
|
||||
);
|
||||
stage = "PREPARE_OWN_CREDENTIALS";
|
||||
await prepareOpenObserve(password);
|
||||
stage = "OPENOBSERVE_CERTIFICATE";
|
||||
if (
|
||||
!(await Bun.file(
|
||||
resolve(local, "pki/openobserve-gateway/server.pem"),
|
||||
).exists())
|
||||
)
|
||||
await issue(
|
||||
resolve(local, "operator/ca"),
|
||||
resolve(local, "pki/openobserve-gateway"),
|
||||
"openobserve-gateway",
|
||||
password,
|
||||
);
|
||||
stage = "COMPOSE_IMAGE_BINDINGS";
|
||||
let environment = await readFile(resolve(root, ".env"), "utf8");
|
||||
for (const image of freeze.images) {
|
||||
const key =
|
||||
image.name === "collector"
|
||||
? "VP7_COLLECTOR_IMAGE"
|
||||
: "VP7_OPENOBSERVE_IMAGE";
|
||||
const line = `${key}=${image.target}`;
|
||||
requireThat(
|
||||
!environment.includes(key + "=") ||
|
||||
environment.split("\n").includes(line),
|
||||
"OPENOBSERVE_ENV_IMAGE_CONFLICT",
|
||||
);
|
||||
if (!environment.split("\n").includes(line))
|
||||
environment += "\n" + line + "\n";
|
||||
}
|
||||
await privateWrite(resolve(root, ".env"), environment);
|
||||
stage = "GENERATE_CURRENT_TOPOLOGY";
|
||||
await writeTopology();
|
||||
stage = "COMPOSE_VALIDATE";
|
||||
await compose(["config", "--quiet"]);
|
||||
stage = "OPENOBSERVE_START";
|
||||
started = true;
|
||||
await compose(["up", "-d", "openobserve-gateway", "openobserve"]);
|
||||
stage = "OPENOBSERVE_AUTHENTICATED_BOOT";
|
||||
let ready = false;
|
||||
const deadline = Date.now() + 60_000;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const response = await openObserveRequest("/api/default/streams", {
|
||||
password,
|
||||
});
|
||||
if (response.status === 200) {
|
||||
ready = true;
|
||||
break;
|
||||
}
|
||||
} catch {}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(ready, "OPENOBSERVE_AUTHENTICATED_BOOT_TIMEOUT");
|
||||
stage = "PROVISION_NATIVE_SERVICE_ACCOUNTS";
|
||||
await provisionOpenObserve(password);
|
||||
stage = "QUERY_SERVICE_ACCOUNT";
|
||||
const query = await openObserveRequest("/api/default/streams", {
|
||||
password,
|
||||
account: "query",
|
||||
role: "grafana",
|
||||
});
|
||||
requireThat(query.status === 200, "OPENOBSERVE_QUERY_PRINCIPAL_REJECTED");
|
||||
stage = "COLLECTOR_CONFIG_VALIDATE";
|
||||
await compose(["up", "-d", "collector-gateway"]);
|
||||
await compose([
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"collector",
|
||||
"validate",
|
||||
"--config=/etc/otelcol/config.yaml",
|
||||
]);
|
||||
stage = "INITIAL_SOURCE_POSTGUARD";
|
||||
requireThat(
|
||||
(await verifyBackendHandover()).sha256 === lease.sha256,
|
||||
"OPENOBSERVE_BACKEND_GENERATION_CHANGED",
|
||||
);
|
||||
await writeFile(
|
||||
receipt,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_NATIVE_STORAGE_BOOTSTRAP_ONLY",
|
||||
stage,
|
||||
backend_sha256: lease.sha256,
|
||||
nativeOpenObserve: true,
|
||||
nativeCollectorConfig: true,
|
||||
nativeApplicationSignals: false,
|
||||
nativeGrafana: false,
|
||||
nativeBao: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_NATIVE_OPENOBSERVE_BOOTSTRAP_AND_COLLECTOR_CONFIG_ONLY");
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
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 outcomes = await Promise.allSettled([
|
||||
compose(
|
||||
[
|
||||
"stop",
|
||||
"collector",
|
||||
"collector-gateway",
|
||||
"openobserve",
|
||||
"openobserve-gateway",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
),
|
||||
]);
|
||||
const stopped =
|
||||
outcomes[0].status === "fulfilled" && outcomes[0].value.code === 0;
|
||||
console.log(
|
||||
stopped
|
||||
? "OWN_OPENOBSERVE_SESSION_STOPPED"
|
||||
: "OWN_OPENOBSERVE_STOP_REQUIRES_INSPECTION",
|
||||
);
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(async () => {
|
||||
const saved = JSON.parse(await readFile(receipt, "utf8"));
|
||||
saved.teardown = {
|
||||
stop_exit:
|
||||
outcomes[0].status === "fulfilled"
|
||||
? outcomes[0].value.code
|
||||
: null,
|
||||
};
|
||||
if (!stopped && !failed) saved.state = "FAILED_TEARDOWN";
|
||||
await writeFile(receipt, JSON.stringify(saved, null, 2) + "\n");
|
||||
}),
|
||||
]);
|
||||
if (!stopped && !failed)
|
||||
throw new Error("OPENOBSERVE_SESSION_STOP_FAILED");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { local, privateWrite, requireThat, run, safeFailure } from "./runtime";
|
||||
import { decrypt, encrypt, operatorPassword } from "./operator-crypto";
|
||||
import {
|
||||
createAccountProvisioner,
|
||||
createAccountWorkflow,
|
||||
validateStoredAccount,
|
||||
type Account,
|
||||
type Principal,
|
||||
} from "./openobserve-accounts";
|
||||
import { containerIP } from "./runtime-inspect";
|
||||
import { validateOpenObservePath } from "./openobserve-request-path";
|
||||
import { parseOpenObserveResponse } from "./openobserve-response";
|
||||
|
||||
const ownerPath = resolve(local, "operator/openobserve-owner.enc");
|
||||
const accountPath = (name: Principal) =>
|
||||
resolve(local, "operator", `openobserve-${name}.enc`);
|
||||
export async function prepareOpenObserve(password: string) {
|
||||
await mkdir(resolve(local, "config"), { recursive: true, mode: 0o700 });
|
||||
await mkdir(resolve(local, "data/openobserve"), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
await mkdir(resolve(local, "plugins"), { recursive: true, mode: 0o700 });
|
||||
if (await Bun.file(ownerPath).exists()) {
|
||||
decrypt<Account>(await readFile(ownerPath, "utf8"), password);
|
||||
requireThat(
|
||||
await Bun.file(resolve(local, "config/openobserve.env")).exists(),
|
||||
"OPENOBSERVE_PREPARE_INCOMPLETE",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const owner = {
|
||||
user: "vp7-owner@example.invalid",
|
||||
token: "Aa1!" + randomBytes(32).toString("hex"),
|
||||
};
|
||||
await writeFile(ownerPath, encrypt(owner, password), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
await writeFile(
|
||||
resolve(local, "config/openobserve.env"),
|
||||
`ZO_ROOT_USER_EMAIL=${owner.user}\nZO_ROOT_USER_PASSWORD=${owner.token}\n`,
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
// Compose validates every service's env_file even before Grafana is started; this placeholder contains no query credential.
|
||||
await writeFile(
|
||||
resolve(local, "config/grafana-query.env"),
|
||||
"# Dedicated query service account is provisioned before Grafana startup.\n",
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
}
|
||||
export async function savedAccount(name: Principal, password: string) {
|
||||
requireThat(
|
||||
name === "ingest" || name === "query",
|
||||
"OPENOBSERVE_ACCOUNT_INVALID_PRINCIPAL",
|
||||
);
|
||||
return validateStoredAccount(
|
||||
name,
|
||||
decrypt<unknown>(await readFile(accountPath(name), "utf8"), password),
|
||||
);
|
||||
}
|
||||
export async function openObserveRequest(
|
||||
path: string,
|
||||
options: {
|
||||
password: string;
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
account?: Principal;
|
||||
credentials?: Account;
|
||||
role?: "operator" | "collector" | "grafana";
|
||||
kind?:
|
||||
| "operator"
|
||||
| "trace_streams"
|
||||
| "worker_trace"
|
||||
| "trace_chain"
|
||||
| "correlated_logs"
|
||||
| "metric_http_requests"
|
||||
| "metric_jobs_processed"
|
||||
| "metric_http_p95"
|
||||
| "metric_queue_depth"
|
||||
| "metric_database_observer";
|
||||
},
|
||||
) {
|
||||
validateOpenObservePath(path);
|
||||
requireThat(
|
||||
(options.role !== "grafana" || options.account === "query") &&
|
||||
(options.role !== "collector" || options.account === "ingest"),
|
||||
"OPENOBSERVE_TRANSPORT_ACCOUNT_MISMATCH",
|
||||
);
|
||||
requireThat(
|
||||
!options.credentials || options.account,
|
||||
"OPENOBSERVE_CREDENTIALS_WITHOUT_PRINCIPAL",
|
||||
);
|
||||
const account = options.account
|
||||
? options.credentials
|
||||
? validateStoredAccount(options.account, options.credentials)
|
||||
: await savedAccount(options.account, options.password)
|
||||
: decrypt<Account>(await readFile(ownerPath, "utf8"), options.password);
|
||||
const role = options.role ?? "operator",
|
||||
ip = await containerIP("openobserve-gateway");
|
||||
const scratch = resolve(
|
||||
local,
|
||||
"operator",
|
||||
"openobserve-request-" + crypto.randomUUID(),
|
||||
);
|
||||
await mkdir(scratch, { recursive: false, mode: 0o700 });
|
||||
const kind = options.kind ?? "operator";
|
||||
requireThat(
|
||||
[
|
||||
"operator",
|
||||
"trace_streams",
|
||||
"worker_trace",
|
||||
"trace_chain",
|
||||
"correlated_logs",
|
||||
"metric_http_requests",
|
||||
"metric_jobs_processed",
|
||||
"metric_http_p95",
|
||||
"metric_queue_depth",
|
||||
"metric_database_observer",
|
||||
].includes(kind),
|
||||
"OPENOBSERVE_REQUEST_KIND_INVALID",
|
||||
);
|
||||
await writeFile(
|
||||
resolve(scratch, "request-meta.json"),
|
||||
JSON.stringify({
|
||||
kind,
|
||||
path,
|
||||
method: options.method ?? (options.body === undefined ? "GET" : "POST"),
|
||||
}),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
const headerPath = resolve(scratch, "headers"),
|
||||
responsePath = resolve(scratch, "response");
|
||||
await writeFile(
|
||||
headerPath,
|
||||
`Authorization: Basic ${Buffer.from(account.user + ":" + account.token).toString("base64")}\nContent-Type: application/json\n`,
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
await writeFile(responsePath, "", { flag: "wx", mode: 0o600 });
|
||||
const port = role === "collector" ? 5080 : 5082;
|
||||
const args = [
|
||||
"curl",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--connect-timeout",
|
||||
"2",
|
||||
"--max-time",
|
||||
"10",
|
||||
"--max-filesize",
|
||||
"8388608",
|
||||
"--cacert",
|
||||
resolve(local, "pki", role, "ca.crt"),
|
||||
"--cert",
|
||||
resolve(local, "pki", role, "cert.pem"),
|
||||
"--key",
|
||||
resolve(local, "pki", role, "key.pem"),
|
||||
"--resolve",
|
||||
`openobserve-gateway:${port}:${ip}`,
|
||||
"--header",
|
||||
"@" + headerPath,
|
||||
"--request",
|
||||
options.method ?? (options.body === undefined ? "GET" : "POST"),
|
||||
"--url",
|
||||
`https://openobserve-gateway:${port}${path}`,
|
||||
"--output",
|
||||
responsePath,
|
||||
"--write-out",
|
||||
"%{http_code}\n%{content_type}",
|
||||
];
|
||||
if (options.body !== undefined) args.push("--data-binary", "@-");
|
||||
const result = await run(args, {
|
||||
input:
|
||||
options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
allowFailure: true,
|
||||
});
|
||||
await Promise.allSettled([
|
||||
writeFile(
|
||||
resolve(scratch, "transport.json"),
|
||||
JSON.stringify({
|
||||
code: result.code,
|
||||
status: result.out,
|
||||
stderr: result.err,
|
||||
}),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
),
|
||||
]);
|
||||
// The native response, including a one-time token, is retained0600 before parsing/status guards.
|
||||
requireThat(result.code === 0, "OPENOBSERVE_REQUEST_TRANSPORT_FAILED");
|
||||
const [statusText, contentType] = result.out.split("\n"),
|
||||
status = Number(statusText);
|
||||
requireThat(
|
||||
Number.isInteger(status) && status >= 100 && status <= 599,
|
||||
"OPENOBSERVE_REQUEST_INVALID_STATUS",
|
||||
);
|
||||
const bytes = await readFile(responsePath);
|
||||
requireThat(bytes.length <= 8388608, "OPENOBSERVE_RESPONSE_TOO_LARGE");
|
||||
const text = bytes.toString("utf8");
|
||||
await Promise.allSettled([
|
||||
writeFile(
|
||||
resolve(scratch, "response-meta.json"),
|
||||
JSON.stringify({
|
||||
kind,
|
||||
status,
|
||||
content_type: contentType,
|
||||
bytes: bytes.length,
|
||||
body_shape: /^\s*[\[{]/.test(text) ? "json-looking" : "text",
|
||||
}),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
),
|
||||
]);
|
||||
return parseOpenObserveResponse(status, text);
|
||||
}
|
||||
export async function provisionOpenObserve(password: string) {
|
||||
const provision = createAccountProvisioner({
|
||||
create: (path, body) => openObserveRequest(path, { password, body }),
|
||||
save: async (name, account) => {
|
||||
await writeFile(accountPath(name), encrypt(account, password), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
},
|
||||
});
|
||||
const accounts = {} as Record<Principal, Account>;
|
||||
for (const name of ["ingest", "query"] as const)
|
||||
accounts[name] = (await Bun.file(accountPath(name)).exists())
|
||||
? await savedAccount(name, password)
|
||||
: await provision(name);
|
||||
const verify = createAccountWorkflow({
|
||||
positive: async (name, credentials) => {
|
||||
const result = await openObserveRequest("/api/default/streams", {
|
||||
password,
|
||||
account: name,
|
||||
credentials,
|
||||
role: name === "query" ? "grafana" : "operator",
|
||||
});
|
||||
requireThat(
|
||||
result.status !== 200 || Array.isArray((result.data as any)?.list),
|
||||
`OPENOBSERVE_CREDENTIAL_${name.toUpperCase()}_INVALID_NATIVE_RESPONSE`,
|
||||
);
|
||||
return result.status;
|
||||
},
|
||||
deny: async (name, credentials) => {
|
||||
const result = await openObserveRequest(
|
||||
`/api/default/service_accounts/vp7-${name}@example.invalid?rotateToken=true`,
|
||||
{ password, account: name, credentials, method: "PUT", body: {} },
|
||||
);
|
||||
return result.status;
|
||||
},
|
||||
publish: async (values) => {
|
||||
for (const name of ["ingest", "query"] as const) {
|
||||
const account = values[name];
|
||||
const authorization =
|
||||
"Basic " +
|
||||
Buffer.from(account.user + ":" + account.token).toString("base64");
|
||||
requireThat(
|
||||
!/[\r\n]/.test(authorization),
|
||||
"OPENOBSERVE_AUTH_CONTAINS_NEWLINE",
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "config", `openobserve_${name}_auth`),
|
||||
authorization,
|
||||
);
|
||||
if (name === "query") {
|
||||
requireThat(
|
||||
/^[A-Za-z0-9@._-]+$/.test(account.user) &&
|
||||
/^[A-Za-z0-9!#%+,.\/:;=?@^_~-]+$/.test(account.token),
|
||||
"OPENOBSERVE_QUERY_ENV_UNSAFE",
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "config/grafana-query.env"),
|
||||
`OO_QUERY_USER=${account.user}\nOO_QUERY_PASSWORD=${account.token}\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
const controls = await verify(accounts);
|
||||
console.log(
|
||||
"PASS_OWN_OPENOBSERVE_ACCOUNTS_CAPTURED_NATIVE_RIGHTS_REQUIRE_GATEWAY",
|
||||
);
|
||||
return controls;
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const action = Bun.argv[2];
|
||||
if (action === "prepare")
|
||||
await prepareOpenObserve(await operatorPassword());
|
||||
else if (action === "provision")
|
||||
await provisionOpenObserve(await operatorPassword());
|
||||
else throw new Error("OPENOBSERVE_ACTION_PREPARE_OR_PROVISION_REQUIRED");
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
randomBytes,
|
||||
scryptSync,
|
||||
} from "node:crypto";
|
||||
import { requireThat } from "./runtime";
|
||||
export function encrypt(value: unknown, password: string) {
|
||||
requireThat(password.length >= 20, "OPERATOR_PASSWORD_TOO_SHORT");
|
||||
const salt = randomBytes(16),
|
||||
iv = randomBytes(12),
|
||||
cipher = createCipheriv("aes-256-gcm", scryptSync(password, salt, 32), iv);
|
||||
const body = Buffer.concat([
|
||||
cipher.update(JSON.stringify(value), "utf8"),
|
||||
cipher.final(),
|
||||
]);
|
||||
return JSON.stringify({
|
||||
v: 1,
|
||||
salt: salt.toString("base64"),
|
||||
iv: iv.toString("base64"),
|
||||
tag: cipher.getAuthTag().toString("base64"),
|
||||
data: body.toString("base64"),
|
||||
});
|
||||
}
|
||||
export function decrypt<T>(value: string, password: string): T {
|
||||
try {
|
||||
const e = JSON.parse(value);
|
||||
requireThat(e.v === 1, "INVALID_ENVELOPE");
|
||||
const decipher = createDecipheriv(
|
||||
"aes-256-gcm",
|
||||
scryptSync(password, Buffer.from(e.salt, "base64"), 32),
|
||||
Buffer.from(e.iv, "base64"),
|
||||
);
|
||||
decipher.setAuthTag(Buffer.from(e.tag, "base64"));
|
||||
return JSON.parse(
|
||||
Buffer.concat([
|
||||
decipher.update(Buffer.from(e.data, "base64")),
|
||||
decipher.final(),
|
||||
]).toString(),
|
||||
);
|
||||
} catch {
|
||||
throw new Error("OPERATOR_DECRYPTION_FAILED");
|
||||
}
|
||||
}
|
||||
export async function operatorPassword() {
|
||||
if (Bun.env.VP7_OPERATOR_PASSWORD) {
|
||||
requireThat(
|
||||
Bun.env.VP7_OPERATOR_PASSWORD.length >= 20,
|
||||
"OPERATOR_PASSWORD_TOO_SHORT",
|
||||
);
|
||||
return Bun.env.VP7_OPERATOR_PASSWORD;
|
||||
}
|
||||
const proc = Bun.spawn(
|
||||
[
|
||||
"bash",
|
||||
"-c",
|
||||
'IFS= read -r -s -p "Operator passphrase (20+ chars): " value; printf "\\n" >&2; printf "%s" "$value"',
|
||||
],
|
||||
{ stdin: "inherit", stdout: "pipe", stderr: "inherit" },
|
||||
);
|
||||
const password = await new Response(proc.stdout).text();
|
||||
requireThat(
|
||||
(await proc.exited) === 0 && password.length >= 20,
|
||||
"OPERATOR_PASSWORD_TOO_SHORT",
|
||||
);
|
||||
return password;
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
readFile,
|
||||
readdir,
|
||||
stat,
|
||||
writeFile,
|
||||
mkdir,
|
||||
open,
|
||||
} from "node:fs/promises";
|
||||
import { resolve, relative } from "node:path";
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
import { verifyBackendHandover } from "./preflight-build";
|
||||
import { assertSameSnapshot } from "./checkpoint-guards";
|
||||
const hash = (bytes: Uint8Array) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
async function sourceFiles() {
|
||||
const files: string[] = [];
|
||||
async function walk(path: string) {
|
||||
for (const entry of await readdir(path, { withFileTypes: true })) {
|
||||
if (
|
||||
[
|
||||
".git",
|
||||
"node_modules",
|
||||
"__pycache__",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
".ruff_cache",
|
||||
".venv",
|
||||
"secrets",
|
||||
"volumes",
|
||||
"data",
|
||||
"backups",
|
||||
"dist",
|
||||
"build",
|
||||
"target",
|
||||
"bin",
|
||||
"obj",
|
||||
"coverage",
|
||||
"submission",
|
||||
].includes(entry.name) ||
|
||||
entry.name.startsWith(".local") ||
|
||||
(entry.name.startsWith(".env") && entry.name !== ".env.example") ||
|
||||
/\.(zip|key|pem|p12|pfx|jks|log|pyc|pyo)$/.test(entry.name)
|
||||
)
|
||||
continue;
|
||||
const target = resolve(path, entry.name);
|
||||
if (entry.isDirectory()) await walk(target);
|
||||
else if (entry.isFile()) {
|
||||
const name = relative(root, target);
|
||||
requireThat(!/[\r\n]/.test(name), "UNSAFE_ARCHIVE_ENTRY");
|
||||
files.push(name);
|
||||
} else throw new Error("NONREGULAR_SOURCE_ENTRY");
|
||||
}
|
||||
}
|
||||
await walk(root);
|
||||
return files.sort();
|
||||
}
|
||||
try {
|
||||
const handover = await verifyBackendHandover();
|
||||
const baseline = JSON.parse(
|
||||
await readFile(resolve(root, "PUBLIC-BASELINE.json"), "utf8"),
|
||||
);
|
||||
requireThat(
|
||||
/^[a-f0-9]{40}$/.test(baseline.original_head),
|
||||
"INVALID_PUBLIC_BASELINE",
|
||||
);
|
||||
let preserved = 0;
|
||||
for (const [path, expected] of Object.entries(baseline.files)) {
|
||||
requireThat(
|
||||
!path.startsWith("/") && !path.split("/").includes(".."),
|
||||
"INVALID_PUBLIC_BASELINE_PATH",
|
||||
);
|
||||
requireThat(
|
||||
hash(await readFile(resolve(root, path))) === expected,
|
||||
"PUBLIC_BASELINE_DRIFT",
|
||||
);
|
||||
preserved++;
|
||||
}
|
||||
const files = await sourceFiles(),
|
||||
source: Record<string, string> = {};
|
||||
for (const path of files) {
|
||||
if (path === "SOURCE-MANIFEST.json") continue;
|
||||
const bytes = await readFile(resolve(root, path));
|
||||
requireThat(bytes.length <= 20 * 1024 * 1024, "SOURCE_ARTIFACT_TOO_LARGE");
|
||||
source[path] = hash(bytes);
|
||||
}
|
||||
const manifest = {
|
||||
state: "SOURCE_CHECKPOINT_NATIVE_GATES_PENDING",
|
||||
grade_awarded: false,
|
||||
backend_checked_at: handover.receipt.checkedAt,
|
||||
preserved_public_files: preserved,
|
||||
files: source,
|
||||
};
|
||||
for (const [path, expected] of Object.entries(baseline.files))
|
||||
requireThat(source[path] === expected, "PUBLIC_BASELINE_DRIFT");
|
||||
const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2) + "\n");
|
||||
await writeFile(resolve(root, "SOURCE-MANIFEST.json"), manifestBytes);
|
||||
const entries = await sourceFiles(),
|
||||
expected = new Map<string, string>(Object.entries(source));
|
||||
expected.set("SOURCE-MANIFEST.json", hash(manifestBytes));
|
||||
const second: Record<string, string> = {};
|
||||
for (const path of entries)
|
||||
if (path !== "SOURCE-MANIFEST.json")
|
||||
second[path] = hash(await readFile(resolve(root, path)));
|
||||
assertSameSnapshot(source, second);
|
||||
requireThat(
|
||||
hash(await readFile(resolve(root, "SOURCE-MANIFEST.json"))) ===
|
||||
expected.get("SOURCE-MANIFEST.json"),
|
||||
"SOURCE_SNAPSHOT_CHANGED",
|
||||
);
|
||||
// Verify every relative bind path's delivered config/entrypoint. Runtime .local paths are generated by prepare.
|
||||
const topology = JSON.parse(
|
||||
await readFile(resolve(root, "compose.yaml"), "utf8"),
|
||||
);
|
||||
let binds = 0;
|
||||
for (const service of Object.values(topology.services) as any[])
|
||||
for (const mount of service.volumes ?? []) {
|
||||
if (mount.type !== "bind" || mount.source.startsWith("./.local/"))
|
||||
continue;
|
||||
const prefix = mount.source.replace(/^\.\//, "");
|
||||
requireThat(
|
||||
expected.has(prefix) ||
|
||||
entries.some((path) => path.startsWith(prefix + "/")),
|
||||
"ARCHIVE_CONFIG_BIND_MISSING",
|
||||
);
|
||||
binds++;
|
||||
}
|
||||
const directory = resolve(root, "submission");
|
||||
await mkdir(directory, { recursive: true });
|
||||
const stamp = new Date().toISOString().replace(/[^0-9]/g, "");
|
||||
const archive = resolve(directory, "vp7-source-checkpoint-" + stamp + ".zip"),
|
||||
receiptPath = archive + ".json";
|
||||
const claim = await open(receiptPath, "wx", 0o600);
|
||||
await claim.writeFile('{"state":"RUNNING"}\n');
|
||||
await claim.close();
|
||||
await run(["zip", "-q", "-X", archive, "-@"], {
|
||||
input: entries.join("\n") + "\n",
|
||||
});
|
||||
await run(["unzip", "-tqq", archive]);
|
||||
const actual = (await run(["unzip", "-Z", "-1", archive])).out
|
||||
.trim()
|
||||
.split("\n")
|
||||
.sort();
|
||||
requireThat(
|
||||
JSON.stringify(actual) === JSON.stringify(entries),
|
||||
"ARCHIVE_ENTRY_SET_MISMATCH",
|
||||
);
|
||||
for (const path of entries) {
|
||||
const child = Bun.spawn(["unzip", "-p", archive, path], {
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
});
|
||||
const [bytes, stderr, exit] = await Promise.all([
|
||||
new Response(child.stdout).arrayBuffer(),
|
||||
new Response(child.stderr).text(),
|
||||
child.exited,
|
||||
]);
|
||||
requireThat(
|
||||
exit === 0 && hash(new Uint8Array(bytes)) === expected.get(path),
|
||||
"ARCHIVE_FILE_HASH_MISMATCH",
|
||||
);
|
||||
requireThat(
|
||||
hash(await readFile(resolve(root, path))) === expected.get(path),
|
||||
"SOURCE_CHANGED_DURING_ARCHIVE",
|
||||
);
|
||||
}
|
||||
requireThat(
|
||||
JSON.stringify(await sourceFiles()) === JSON.stringify(entries),
|
||||
"SOURCE_SNAPSHOT_CHANGED",
|
||||
);
|
||||
await handover.verify();
|
||||
const size = (await stat(archive)).size;
|
||||
await writeFile(
|
||||
receiptPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS_SOURCE_CHECKPOINT_ONLY",
|
||||
archive: relative(root, archive),
|
||||
bytes: size,
|
||||
sha256: hash(await readFile(archive)),
|
||||
files: entries.length,
|
||||
preserved_public_files: preserved,
|
||||
delivered_bind_sources: binds,
|
||||
every_file_byte_equal: true,
|
||||
zip_crc: true,
|
||||
backend_checked_at: handover.receipt.checkedAt,
|
||||
native_security_complete: false,
|
||||
native_telemetry_complete: false,
|
||||
grade_awarded: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log(
|
||||
"PASS_CHECKPOINT_ZIP_CRC_ALL_BYTES_PUBLIC_BASELINE_AND_CONFIG_BINDS",
|
||||
);
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import { mkdir, readFile, chmod, copyFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { run, privateWrite, requireThat } from "./runtime";
|
||||
import { validateLeaf } from "./security-guards";
|
||||
export function caConfig(base: string) {
|
||||
return `[ca]\ndefault_ca=CA\n[CA]\ndatabase=${base}/index\nnew_certs_dir=${base}/issued\ncertificate=${base}/ca.crt\nprivate_key=${base}/ca.key\nserial=${base}/serial\ncrlnumber=${base}/crlnumber\ndefault_md=sha256\ndefault_days=2\ndefault_crl_days=1\nunique_subject=no\npolicy=policy\n[policy]\ncommonName=supplied\n`;
|
||||
}
|
||||
export async function createCA(base: string, passphrase: string) {
|
||||
requireThat(passphrase.length >= 20, "OPERATOR_PASSWORD_TOO_SHORT");
|
||||
await mkdir(resolve(base, "issued"), { recursive: true, mode: 0o700 });
|
||||
await privateWrite(resolve(base, "index"), "");
|
||||
await privateWrite(resolve(base, "serial"), "1000\n");
|
||||
await privateWrite(resolve(base, "crlnumber"), "1000\n");
|
||||
await privateWrite(resolve(base, "ca.cnf"), caConfig(base));
|
||||
await run(
|
||||
[
|
||||
"openssl",
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"rsa:3072",
|
||||
"-sha256",
|
||||
"-days",
|
||||
"30",
|
||||
"-subj",
|
||||
"/CN=VP7 private lab CA",
|
||||
"-addext",
|
||||
"basicConstraints=critical,CA:TRUE,pathlen:0",
|
||||
"-addext",
|
||||
"keyUsage=critical,keyCertSign,cRLSign",
|
||||
"-keyout",
|
||||
resolve(base, "ca.key"),
|
||||
"-out",
|
||||
resolve(base, "ca.crt"),
|
||||
"-passout",
|
||||
"stdin",
|
||||
],
|
||||
{ input: passphrase + "\n" },
|
||||
);
|
||||
await chmod(resolve(base, "ca.key"), 0o600);
|
||||
await refreshCRL(base, passphrase);
|
||||
}
|
||||
export async function refreshCRL(base: string, passphrase: string) {
|
||||
await run(
|
||||
[
|
||||
"openssl",
|
||||
"ca",
|
||||
"-batch",
|
||||
"-config",
|
||||
resolve(base, "ca.cnf"),
|
||||
"-gencrl",
|
||||
"-out",
|
||||
resolve(base, "ca.crl"),
|
||||
"-passin",
|
||||
"stdin",
|
||||
],
|
||||
{ input: passphrase + "\n" },
|
||||
);
|
||||
}
|
||||
export async function issue(
|
||||
base: string,
|
||||
destination: string,
|
||||
identity: string,
|
||||
passphrase: string,
|
||||
dates?: { start: string; end: string },
|
||||
) {
|
||||
requireThat(
|
||||
/^[a-z0-9-]{1,48}$/.test(identity),
|
||||
"INVALID_CERTIFICATE_IDENTITY",
|
||||
);
|
||||
await mkdir(destination, { recursive: true, mode: 0o700 });
|
||||
const extensions = resolve(destination, "leaf.cnf");
|
||||
await privateWrite(
|
||||
extensions,
|
||||
`[leaf]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=DNS:${identity}${["lb", "openbao", "grafana"].includes(identity) ? ",DNS:localhost,IP:127.0.0.1" : ""}\nauthorityKeyIdentifier=keyid,issuer\nsubjectKeyIdentifier=hash\n`,
|
||||
);
|
||||
await run([
|
||||
"openssl",
|
||||
"req",
|
||||
"-new",
|
||||
"-newkey",
|
||||
"rsa:2048",
|
||||
"-noenc",
|
||||
"-subj",
|
||||
`/CN=${identity}`,
|
||||
"-keyout",
|
||||
resolve(destination, "key.pem"),
|
||||
"-out",
|
||||
resolve(destination, "request.csr"),
|
||||
]);
|
||||
await run(
|
||||
[
|
||||
"openssl",
|
||||
"ca",
|
||||
"-batch",
|
||||
"-notext",
|
||||
"-config",
|
||||
resolve(base, "ca.cnf"),
|
||||
"-extensions",
|
||||
"leaf",
|
||||
"-extfile",
|
||||
extensions,
|
||||
"-in",
|
||||
resolve(destination, "request.csr"),
|
||||
"-out",
|
||||
resolve(destination, "cert.pem"),
|
||||
"-passin",
|
||||
"stdin",
|
||||
...(dates ? ["-startdate", dates.start, "-enddate", dates.end] : []),
|
||||
],
|
||||
{ input: passphrase + "\n" },
|
||||
);
|
||||
const cert = await readFile(resolve(destination, "cert.pem"), "utf8"),
|
||||
key = await readFile(resolve(destination, "key.pem"), "utf8"),
|
||||
ca = await readFile(resolve(base, "ca.crt"), "utf8");
|
||||
if (!dates) validateLeaf(cert, key, ca, identity);
|
||||
await privateWrite(resolve(destination, "server.pem"), cert + key);
|
||||
await copyFile(resolve(base, "ca.crt"), resolve(destination, "ca.crt"));
|
||||
await copyFile(resolve(base, "ca.crl"), resolve(destination, "ca.crl"));
|
||||
for (const file of ["key.pem", "server.pem", "request.csr", "leaf.cnf"])
|
||||
await chmod(resolve(destination, file), 0o600);
|
||||
}
|
||||
export async function revoke(base: string, cert: string, passphrase: string) {
|
||||
await run(
|
||||
[
|
||||
"openssl",
|
||||
"ca",
|
||||
"-batch",
|
||||
"-config",
|
||||
resolve(base, "ca.cnf"),
|
||||
"-revoke",
|
||||
cert,
|
||||
"-passin",
|
||||
"stdin",
|
||||
],
|
||||
{ input: passphrase + "\n" },
|
||||
);
|
||||
await refreshCRL(base, passphrase);
|
||||
}
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Official root entrypoint drops to postgres after preparing its data directory.
|
||||
install -m 600 -o postgres -g postgres /source-tls/key.pem /run/tls/key.pem
|
||||
install -m 644 -o postgres -g postgres /source-tls/cert.pem /run/tls/cert.pem
|
||||
install -m 644 -o postgres -g postgres /source-tls/ca.crt /run/tls/ca.crt
|
||||
install -m 644 -o postgres -g postgres /source-tls/ca.crl /run/tls/ca.crl
|
||||
exec /usr/local/bin/docker-entrypoint.sh postgres -c listen_addresses='*' -c ssl=on -c ssl_min_protocol_version=TLSv1.2 -c ssl_cert_file=/run/tls/cert.pem -c ssl_key_file=/run/tls/key.pem -c ssl_ca_file=/run/tls/ca.crt -c ssl_crl_file=/run/tls/ca.crl -c hba_file=/config/pg_hba.conf -c password_encryption=scram-sha-256 -c log_statement=none -c log_connections=off -c log_disconnections=off
|
||||
@@ -0,0 +1,162 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, run, requireThat, safeFailure } from "./runtime";
|
||||
import { pinHandover } from "./checkpoint-guards";
|
||||
export async function verifyBackendHandover() {
|
||||
return pinHandover({
|
||||
readReceipt: () => readFile(resolve(root, "BACKEND-READY.json")),
|
||||
readSource: (path) => readFile(resolve(root, "backend", path)),
|
||||
});
|
||||
}
|
||||
export async function preflightBuild() {
|
||||
const lease = await verifyBackendHandover();
|
||||
const { count, receipt } = lease;
|
||||
const helperHash = createHash("sha256")
|
||||
.update(await readFile(resolve(root, "scripts/s3-control.go")))
|
||||
.digest("hex");
|
||||
await mkdir(resolve(local, "bin"), { recursive: true, mode: 0o700 });
|
||||
await mkdir(resolve(root, ".local-build-cache"), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/preflight-source-handover.json"),
|
||||
lease.bytes,
|
||||
);
|
||||
const frozen: any = {};
|
||||
for (const [name, source] of [["runtime", "mtuci-vp5:local"]]) {
|
||||
const image = JSON.parse(
|
||||
(await run(["docker", "image", "inspect", source])).out,
|
||||
)[0];
|
||||
requireThat(
|
||||
/^sha256:[a-f0-9]{64}$/.test(image.Id),
|
||||
"INVALID_CACHED_IMAGE_ID",
|
||||
);
|
||||
const alias = "mtuci-vp7-preflight-" + name + ":" + image.Id.slice(7, 23);
|
||||
await run(["docker", "image", "tag", image.Id, alias]);
|
||||
const check = JSON.parse(
|
||||
(await run(["docker", "image", "inspect", alias])).out,
|
||||
)[0];
|
||||
requireThat(check.Id === image.Id, "CACHED_IMAGE_FREEZE_MISMATCH");
|
||||
frozen[name] = { source, id: image.Id, alias };
|
||||
}
|
||||
const compiler = "/home/rey/.local/share/mise/installs/go/1.27.2/bin/go";
|
||||
const env = {
|
||||
GOTOOLCHAIN: "local",
|
||||
GOPROXY: "off",
|
||||
GOSUMDB: "off",
|
||||
GOFLAGS: "-mod=readonly",
|
||||
CGO_ENABLED: "0",
|
||||
GOMODCACHE: "/home/rey/go/pkg/mod",
|
||||
GOCACHE: resolve(root, ".local-build-cache"),
|
||||
GOMAXPROCS: "2",
|
||||
};
|
||||
const version = await run([compiler, "version"], { env });
|
||||
requireThat(
|
||||
version.out.trim() === "go version go1.27.2 linux/amd64",
|
||||
"UNEXPECTED_PREFLIGHT_COMPILER",
|
||||
);
|
||||
for (const [name, source] of [
|
||||
["app", "./cmd/app"],
|
||||
["worker", "./cmd/worker"],
|
||||
["s3-control", resolve(root, "scripts/s3-control.go")],
|
||||
])
|
||||
await run(
|
||||
[
|
||||
compiler,
|
||||
"build",
|
||||
"-trimpath",
|
||||
"-o",
|
||||
resolve(local, "bin", name),
|
||||
source,
|
||||
],
|
||||
{ env, cwd: resolve(root, "backend") },
|
||||
);
|
||||
await lease.verify();
|
||||
requireThat(
|
||||
createHash("sha256")
|
||||
.update(await readFile(resolve(root, "scripts/s3-control.go")))
|
||||
.digest("hex") === helperHash,
|
||||
"HELPER_SOURCE_CHANGED",
|
||||
);
|
||||
const binaries: any = {};
|
||||
for (const name of ["app", "worker", "s3-control"])
|
||||
binaries[name] = createHash("sha256")
|
||||
.update(await readFile(resolve(local, "bin", name)))
|
||||
.digest("hex");
|
||||
const dockerfile = resolve(local, "Dockerfile.preflight");
|
||||
await writeFile(
|
||||
dockerfile,
|
||||
`FROM ${frozen.runtime.alias}\nCOPY app /app\nCOPY worker /worker\nCOPY s3-control /s3-control\nUSER 10001:10001\nENTRYPOINT []\nCMD ["/app"]\n`,
|
||||
);
|
||||
// The build context is exactly the three verified public-source binaries, never the .local parent or credentials.
|
||||
await run([
|
||||
"docker",
|
||||
"build",
|
||||
"--pull=false",
|
||||
"--network",
|
||||
"none",
|
||||
"--file",
|
||||
dockerfile,
|
||||
"--tag",
|
||||
"mtuci-vp7-security-app:local",
|
||||
resolve(local, "bin"),
|
||||
]);
|
||||
const installed = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--network",
|
||||
"none",
|
||||
"--entrypoint",
|
||||
"/usr/bin/sha256sum",
|
||||
"mtuci-vp7-security-app:local",
|
||||
"/app",
|
||||
"/worker",
|
||||
"/s3-control",
|
||||
]);
|
||||
for (const name of ["app", "worker", "s3-control"])
|
||||
requireThat(
|
||||
installed.out.includes(binaries[name] + " /" + name),
|
||||
"INSTALLED_PREFLIGHT_BINARY_HASH_MISMATCH",
|
||||
);
|
||||
await lease.verify();
|
||||
requireThat(
|
||||
createHash("sha256")
|
||||
.update(await readFile(resolve(root, "scripts/s3-control.go")))
|
||||
.digest("hex") === helperHash,
|
||||
"HELPER_SOURCE_CHANGED",
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/preflight-build.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
scope:
|
||||
"checked7 source, cached VP5 runtime only; no Bao/telemetry acceptance",
|
||||
module_fetch:
|
||||
"GOPROXY=off GOSUMDB=off GOFLAGS=-mod=readonly; existing native cache",
|
||||
image_build_network: "none",
|
||||
source_files_verified: count,
|
||||
backend_checked_at: receipt.checkedAt,
|
||||
source_handover_sha256: lease.sha256,
|
||||
s3_control_source_sha256: helperHash,
|
||||
images: frozen,
|
||||
compiler: version.out.trim(),
|
||||
binaries,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_EXACT7_PREFLIGHT_BINARIES_BUILT_OFFLINE_WITH_FROZEN_CACHE");
|
||||
return frozen.runtime.alias as string;
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await preflightBuild();
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import { readFile, mkdir, rename, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
requireThat,
|
||||
privateWrite,
|
||||
safeFailure,
|
||||
} from "./runtime";
|
||||
import { bootstrap } from "./bootstrap";
|
||||
import { decrypt } from "./operator-crypto";
|
||||
import { preflightBuild, verifyBackendHandover } from "./preflight-build";
|
||||
import { assertAcceptedGeneration } from "./checkpoint-guards";
|
||||
import { provisionDB } from "./db-provision";
|
||||
import { provisionS3 } from "./s3-provision";
|
||||
import { waitReady } from "../student-tests/wait";
|
||||
import { postgresTransport } from "../student-tests/postgres-transport";
|
||||
import { auditWorkerPrivileges } from "../student-tests/privileges";
|
||||
import { auditMatrix } from "../student-tests/matrix";
|
||||
import { certificateLifetime } from "../student-tests/extended";
|
||||
import { containerID } from "./runtime-inspect";
|
||||
import { freshnessExpiry } from "../student-tests/freshness-runtime";
|
||||
import { checkSource } from "./check-source";
|
||||
import { prepareProbePKI } from "../student-tests/probe-pki";
|
||||
async function atomicTimestamp(path: string) {
|
||||
const temporary = path + "." + crypto.randomUUID();
|
||||
await privateWrite(temporary, new Date().toISOString() + "\n");
|
||||
await rename(temporary, path);
|
||||
}
|
||||
async function main() {
|
||||
let stage = "BOOTSTRAP_LOCAL";
|
||||
const sessionKey = resolve(root, ".local-preflight-key");
|
||||
if (!(await Bun.file(sessionKey).exists()))
|
||||
await writeFile(sessionKey, randomBytes(32).toString("hex"), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
const password = await readFile(sessionKey, "utf8");
|
||||
requireThat(/^[a-f0-9]{64}$/.test(password), "INVALID_PREFLIGHT_SESSION_KEY");
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
await mkdir(resolve(root, "evidence/preflight"), { recursive: true });
|
||||
try {
|
||||
if (!Bun.argv.includes("--resume")) await bootstrap(password);
|
||||
else
|
||||
requireThat(
|
||||
JSON.parse(
|
||||
await readFile(resolve(local, "bootstrap-claim.json"), "utf8"),
|
||||
).state === "COMPLETE",
|
||||
"PREFLIGHT_RESUME_UNOWNED",
|
||||
);
|
||||
stage = "CHECKED_CACHED_BUILD";
|
||||
await preflightBuild();
|
||||
const sourceBytes = await readFile(
|
||||
resolve(root, "evidence/security/preflight-source-handover.json"),
|
||||
),
|
||||
buildReceipt = JSON.parse(
|
||||
await readFile(
|
||||
resolve(root, "evidence/security/preflight-build.json"),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const acceptedGeneration = {
|
||||
backend_checked_at: buildReceipt.backend_checked_at,
|
||||
source_handover_sha256: buildReceipt.source_handover_sha256,
|
||||
source_files_verified: buildReceipt.source_files_verified,
|
||||
binaries: {
|
||||
app: buildReceipt.binaries.app,
|
||||
worker: buildReceipt.binaries.worker,
|
||||
},
|
||||
source_handover_text: sourceBytes.toString(),
|
||||
build_receipt: buildReceipt,
|
||||
};
|
||||
assertAcceptedGeneration(acceptedGeneration, sourceBytes, buildReceipt);
|
||||
const runLease = await verifyBackendHandover();
|
||||
requireThat(
|
||||
runLease.sha256 === acceptedGeneration.source_handover_sha256,
|
||||
"ACCEPTED_GENERATION_MISMATCH",
|
||||
);
|
||||
await import("./generate-agent-configs");
|
||||
stage = "NATIVE_COMPOSE_PREFLIGHT";
|
||||
await compose(["config", "--quiet"]);
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"postgres",
|
||||
"broker-gateway",
|
||||
"broker",
|
||||
"s3-gateway",
|
||||
"s3",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"worker-gateway",
|
||||
"lb",
|
||||
]);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const r = await compose(
|
||||
[
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"pg_isready",
|
||||
"-h",
|
||||
"127.0.0.1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
if (r.code === 0) break;
|
||||
requireThat(i < 59, "PREFLIGHT_PG_NOT_READY");
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
stage = "DB_ROLE_PROVISION";
|
||||
await provisionDB(password);
|
||||
const secrets = decrypt<any>(
|
||||
await readFile(resolve(local, "operator/services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "operator/migration-url"),
|
||||
`postgresql://operator:${secrets.dbOperator}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt&sslcert=/pki/cert.pem&sslkey=/pki/key.pem`,
|
||||
);
|
||||
stage = "NATIVE_MIGRATIONS";
|
||||
await compose(["run", "--rm", "--no-deps", "migrate"]);
|
||||
await provisionDB(password, true);
|
||||
stage = "NATIVE_S3_SCOPED_BOOTSTRAP";
|
||||
await provisionS3(password);
|
||||
// Explicit operator preflight provider, never represented as OpenBao delivery.
|
||||
for (const name of ["api1", "api2", "worker"]) {
|
||||
const role = name === "worker" ? "worker" : "api",
|
||||
suffix = role === "api" ? "Api" : "Worker";
|
||||
await privateWrite(
|
||||
resolve(local, "rendered", name, "database_url"),
|
||||
`postgresql://${role}@127.0.0.1:15432/messenger?sslmode=disable`,
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "rendered", name, "cache_url"),
|
||||
`redis://${role}:${secrets["broker" + suffix]}@127.0.0.1:16379/0`,
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "rendered", name, "s3.json"),
|
||||
JSON.stringify({
|
||||
Endpoint: "127.0.0.1:19000",
|
||||
Access: secrets["s3" + suffix + "Access"],
|
||||
Secret: secrets["s3" + suffix + "Secret"],
|
||||
Bucket: "messenger-attachments",
|
||||
}),
|
||||
);
|
||||
if (role === "worker")
|
||||
await privateWrite(
|
||||
resolve(local, "rendered", name, "publisher_url"),
|
||||
`redis://publisher:${secrets.brokerPublisher}@127.0.0.1:16379/0`,
|
||||
);
|
||||
await atomicTimestamp(resolve(local, "rendered", name, "freshness"));
|
||||
}
|
||||
let writing = false;
|
||||
heartbeat = setInterval(() => {
|
||||
if (writing) return;
|
||||
writing = true;
|
||||
Promise.all(
|
||||
["api1", "api2", "worker"].map((name) =>
|
||||
atomicTimestamp(resolve(local, "rendered", name, "freshness")),
|
||||
),
|
||||
).finally(() => {
|
||||
writing = false;
|
||||
});
|
||||
}, 1000);
|
||||
stage = "API_WORKER_START";
|
||||
await compose(["up", "-d", "--no-deps", "api1", "api2", "worker"]);
|
||||
await waitReady();
|
||||
const env = {
|
||||
BASE_URL: "https://localhost:18443",
|
||||
CA_FILE: resolve(local, "pki/lb/ca.crt"),
|
||||
};
|
||||
stage = "PUBLIC_SOURCE_CHECK";
|
||||
await checkSource();
|
||||
for (const target of ["test", "test-security"]) {
|
||||
stage = "PUBLIC_" + target.toUpperCase().replaceAll("-", "_");
|
||||
const r = await run(["make", target], { env });
|
||||
await writeFile(
|
||||
resolve(root, "evidence/preflight/public-" + target + ".txt"),
|
||||
r.out + r.err,
|
||||
);
|
||||
console.log(
|
||||
"PASS_PREFLIGHT_" + target.toUpperCase().replaceAll("-", "_"),
|
||||
);
|
||||
}
|
||||
stage = "POSTGRES_TRANSPORT";
|
||||
await prepareProbePKI(password);
|
||||
await postgresTransport();
|
||||
stage = "TLS_CORE_BOUNDARIES";
|
||||
await auditMatrix("cached");
|
||||
stage = "WORKER_SCOPE";
|
||||
await auditWorkerPrivileges(password);
|
||||
stage = "CERTIFICATE_LIFETIME";
|
||||
await certificateLifetime(password, "cached");
|
||||
stage = "FRESHNESS_EXPIRY";
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
heartbeat = undefined;
|
||||
await freshnessExpiry();
|
||||
for (const name of ["api1", "api2", "worker"])
|
||||
await atomicTimestamp(resolve(local, "rendered", name, "freshness"));
|
||||
heartbeat = setInterval(() => {
|
||||
Promise.all(
|
||||
["api1", "api2", "worker"].map((name) =>
|
||||
atomicTimestamp(resolve(local, "rendered", name, "freshness")),
|
||||
),
|
||||
).catch(() => {
|
||||
console.error("PREFLIGHT_HEARTBEAT_WRITE_FAILED");
|
||||
});
|
||||
}, 1000);
|
||||
await compose(["up", "-d", "--no-deps", "api1", "api2", "worker"]);
|
||||
await waitReady();
|
||||
stage = "ACTUAL_STOP";
|
||||
const started = Date.now();
|
||||
await compose(["stop", "api1", "api2", "worker"]);
|
||||
const elapsed = (Date.now() - started) / 1000;
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
const state = JSON.parse(
|
||||
(await run(["docker", "inspect", await containerID(service)])).out,
|
||||
)[0];
|
||||
requireThat(!state.State.Running, "PREFLIGHT_PROCESS_STOP_FAILED");
|
||||
}
|
||||
requireThat(elapsed < 15, "PREFLIGHT_PROCESS_STOP_EXCEEDED_SUPERVISOR");
|
||||
await runLease.verify();
|
||||
await writeFile(
|
||||
resolve(root, "evidence/preflight/summary.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "PASS",
|
||||
accepted_generation: acceptedGeneration,
|
||||
provider: "operator scoped files + explicit heartbeat (not OpenBao)",
|
||||
pulls: false,
|
||||
https_api_pipeline: true,
|
||||
core_mtls: true,
|
||||
least_privilege: true,
|
||||
certificate_lifetime: true,
|
||||
stop_seconds: elapsed,
|
||||
openbao_acceptance: false,
|
||||
telemetry_acceptance: false,
|
||||
grade5_acceptance: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_CACHED_PREFLIGHT_NO_BAO_OR_TELEMETRY_ACCEPTANCE");
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(() =>
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics/preflight-error.json"),
|
||||
JSON.stringify({
|
||||
stage,
|
||||
message: error instanceof Error ? error.message : "UNKNOWN",
|
||||
stack: error instanceof Error ? error.stack : "",
|
||||
}),
|
||||
),
|
||||
),
|
||||
Promise.resolve().then(() =>
|
||||
writeFile(
|
||||
resolve(root, "evidence/preflight/summary.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
state: "FAILED",
|
||||
stage,
|
||||
provider: "operator preflight only",
|
||||
openbao_acceptance: false,
|
||||
telemetry_acceptance: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
),
|
||||
),
|
||||
]);
|
||||
console.error("PREFLIGHT_STAGE_" + stage);
|
||||
throw error;
|
||||
} finally {
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
}
|
||||
}
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
await main();
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { requireThat, project } from "./runtime";
|
||||
export function publicLBEndpoint(inspection: any): {
|
||||
host: string;
|
||||
port: number;
|
||||
servername: string;
|
||||
} {
|
||||
requireThat(
|
||||
inspection?.Config?.Labels?.["com.docker.compose.project"] === project &&
|
||||
inspection?.Config?.Labels?.["com.docker.compose.service"] === "lb" &&
|
||||
inspection?.State?.Running === true,
|
||||
"LB_RESOURCE_GUARD_FAILED",
|
||||
);
|
||||
const bindings = inspection?.NetworkSettings?.Ports?.["8443/tcp"];
|
||||
requireThat(
|
||||
Array.isArray(bindings) && bindings.length === 1,
|
||||
"LB_PUBLIC_TLS_BINDING_MISSING",
|
||||
);
|
||||
const binding = bindings[0];
|
||||
requireThat(
|
||||
binding.HostIp === "127.0.0.1" &&
|
||||
typeof binding.HostPort === "string" &&
|
||||
/^[0-9]{1,5}$/.test(binding.HostPort),
|
||||
"LB_PUBLIC_TLS_BINDING_UNSAFE",
|
||||
);
|
||||
const port = Number(binding.HostPort);
|
||||
requireThat(port >= 1 && port <= 65535, "LB_PUBLIC_TLS_PORT_INVALID");
|
||||
return { host: "127.0.0.1", port, servername: "localhost" };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { run, requireThat } from "./runtime";
|
||||
import { containerID } from "./runtime-inspect";
|
||||
const gateways = [
|
||||
"lb",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"worker-gateway",
|
||||
"broker-gateway",
|
||||
"s3-gateway",
|
||||
"collector-gateway",
|
||||
"openobserve-gateway",
|
||||
"grafana-gateway",
|
||||
];
|
||||
export async function reloadGateway(service: string) {
|
||||
requireThat(gateways.includes(service), "INVALID_GATEWAY_TARGET");
|
||||
const id = 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.State.Running === true,
|
||||
"GATEWAY_NOT_OWNED_RUNNING",
|
||||
);
|
||||
// Native HAProxy master-worker reload preserves the network namespace used by sidecars.
|
||||
// hard-stop-after2s drains old TLS connections so revoked clients cannot keep a pool alive forever.
|
||||
await run(["docker", "kill", "--signal", "USR2", id]);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { type ReplicaBaseline, type ReplicaService } from "./failover-proof";
|
||||
export type ReplicaState = {
|
||||
id: string;
|
||||
running: boolean;
|
||||
project: string;
|
||||
service: string;
|
||||
started: string;
|
||||
};
|
||||
export function createReplicaSnapshot(ports: {
|
||||
inspect: (service: ReplicaService) => Promise<ReplicaState>;
|
||||
command: (args: string[]) => Promise<string>;
|
||||
}) {
|
||||
if (
|
||||
typeof ports?.inspect !== "function" ||
|
||||
typeof ports.command !== "function"
|
||||
)
|
||||
throw Error("REPLICA_SNAPSHOT_PORTS_REQUIRED");
|
||||
return async (): Promise<ReplicaBaseline> => {
|
||||
const baseline = {} as ReplicaBaseline;
|
||||
for (const service of ["api1", "api2"] as const) {
|
||||
const before = await ports.inspect(service);
|
||||
if (
|
||||
!before.running ||
|
||||
before.project !== "mtuci-vp7-security" ||
|
||||
before.service !== service ||
|
||||
!/^[a-f0-9]{64}$/.test(before.id)
|
||||
)
|
||||
throw Error("FAILOVER_BASELINE_NOT_OWN_RUNNING_REPLICA");
|
||||
const alias = (
|
||||
await ports.command([
|
||||
"docker",
|
||||
"exec",
|
||||
before.id,
|
||||
"/bin/cat",
|
||||
"/tmp/messenger-instance-id",
|
||||
])
|
||||
).trim();
|
||||
if (
|
||||
!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(
|
||||
alias,
|
||||
)
|
||||
)
|
||||
throw Error("INVALID_REPLICA_ALIAS");
|
||||
const after = await ports.inspect(service);
|
||||
if (
|
||||
!after.running ||
|
||||
after.id !== before.id ||
|
||||
after.started !== before.started ||
|
||||
after.project !== before.project ||
|
||||
after.service !== before.service
|
||||
)
|
||||
throw Error("FAILOVER_REPLICA_CHANGED_DURING_READ");
|
||||
baseline[service] = { container: before.id, alias };
|
||||
}
|
||||
return baseline;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { rename, readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, compose, run, requireThat, safeFailure } from "./runtime";
|
||||
try {
|
||||
const claim = JSON.parse(
|
||||
await readFile(resolve(local, "bootstrap-claim.json"), "utf8"),
|
||||
);
|
||||
requireThat(claim.state === "COMPLETE", "TEST_BOOTSTRAP_NOT_OWNED");
|
||||
const containers = await compose(["ps", "-a", "-q"]);
|
||||
for (const id of containers.out.trim().split(/\s+/).filter(Boolean)) {
|
||||
const info = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
requireThat(
|
||||
info.Config.Labels["com.docker.compose.project"] === "mtuci-vp7-security",
|
||||
"CLEANUP_PROJECT_MISMATCH",
|
||||
);
|
||||
}
|
||||
await compose(["--profile", "*", "down", "--remove-orphans"]);
|
||||
const archive = resolve(root, ".local-failed-" + Date.now());
|
||||
await rename(local, archive);
|
||||
console.log("PASS_OWNED_FAILED_TEST_STATE_PRIVATELY_ARCHIVED");
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec bun "$HERE/hooks.ts" restart
|
||||
@@ -0,0 +1,342 @@
|
||||
import { readFile, copyFile, mkdir, open, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
root,
|
||||
local,
|
||||
compose,
|
||||
run,
|
||||
privateWrite,
|
||||
requireThat,
|
||||
} from "./runtime";
|
||||
import { decrypt, encrypt } from "./operator-crypto";
|
||||
import { unlock } from "./openbao-operator";
|
||||
import { bao } from "./bao-client";
|
||||
import { issue, revoke } from "./pki";
|
||||
import { roles } from "./topology";
|
||||
import { reloadGateway } from "./reload-gateway";
|
||||
import { provisionS3 } from "./s3-provision";
|
||||
import { containerIP, containerID } from "./runtime-inspect";
|
||||
import { tlsProbe, expectDenied } from "../student-tests/transport";
|
||||
import { HTTP } from "../student-tests/http";
|
||||
export async function workerCompromise(password: string) {
|
||||
const claim = await open(
|
||||
resolve(local, "operator", "worker-compromise-claim.json"),
|
||||
"wx",
|
||||
0o600,
|
||||
);
|
||||
await claim.writeFile('{"state":"RUNNING"}');
|
||||
await claim.close();
|
||||
const http = new HTTP(),
|
||||
actor = await http.user("compromise"),
|
||||
peer = await http.user("peer");
|
||||
const chat = (
|
||||
await http.call("POST", "/api/v1/chats", 201, {
|
||||
actor: actor.token,
|
||||
body: {
|
||||
title: "Worker recovery experiment",
|
||||
member_ids: [actor.id, peer.id],
|
||||
},
|
||||
})
|
||||
).json;
|
||||
await compose(["stop", "worker"]);
|
||||
const fixture = new Uint8Array(
|
||||
await readFile(resolve(root, "tests/fixtures/sample.png")),
|
||||
),
|
||||
pending = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const accepted = await http.call(
|
||||
"POST",
|
||||
`/api/v1/chats/${chat.id}/attachments?filename=probe.png`,
|
||||
202,
|
||||
{
|
||||
actor: actor.token,
|
||||
raw: fixture,
|
||||
headers: { "Content-Type": "image/png" },
|
||||
},
|
||||
);
|
||||
requireThat(
|
||||
accepted.json.status === "queued",
|
||||
"RESEARCH_NOT_DURABLY_QUEUED",
|
||||
);
|
||||
pending.push({ id: accepted.json.id, sha256: accepted.json.sha256 });
|
||||
}
|
||||
const beforeLogin = await bao("/auth/cert/login", {
|
||||
role: "worker",
|
||||
body: { name: "worker" },
|
||||
}),
|
||||
oldToken = beforeLogin.data.auth.client_token;
|
||||
const operator = await unlock(password),
|
||||
rootToken = operator.root_token;
|
||||
const checkpoint = resolve(local, "operator/worker-compromise-state.enc");
|
||||
await privateWrite(
|
||||
checkpoint,
|
||||
encrypt(
|
||||
{ phase: "QUEUED_BEFORE_REVOCATION", pending, peer, oldToken },
|
||||
password,
|
||||
),
|
||||
);
|
||||
await compose(["stop", "worker-agent"]);
|
||||
const retired = resolve(local, "pki", "retired-worker");
|
||||
await mkdir(retired, { recursive: true, mode: 0o700 });
|
||||
for (const name of ["cert.pem", "key.pem", "ca.crt"])
|
||||
await copyFile(resolve(local, "pki/worker", name), resolve(retired, name));
|
||||
const ca = resolve(local, "operator/ca");
|
||||
await revoke(ca, resolve(retired, "cert.pem"), password);
|
||||
for (const role of roles)
|
||||
await copyFile(
|
||||
resolve(ca, "ca.crl"),
|
||||
resolve(local, "pki", role, "ca.crl"),
|
||||
);
|
||||
await bao("/auth/cert/crls/lab", {
|
||||
token: rootToken,
|
||||
body: { crl: await readFile(resolve(ca, "ca.crl"), "utf8") },
|
||||
});
|
||||
const accessors = await bao("/auth/token/accessors", {
|
||||
method: "LIST",
|
||||
token: rootToken,
|
||||
});
|
||||
let tokensRevoked = 0;
|
||||
for (const accessor of accessors.data.data.keys) {
|
||||
const entry = await bao("/auth/token/lookup-accessor", {
|
||||
token: rootToken,
|
||||
body: { accessor },
|
||||
});
|
||||
if (entry.data.data.policies?.includes("worker")) {
|
||||
await bao("/auth/token/revoke-accessor", {
|
||||
token: rootToken,
|
||||
body: { accessor },
|
||||
});
|
||||
tokensRevoked++;
|
||||
}
|
||||
}
|
||||
requireThat(tokensRevoked > 0, "RESEARCH_NO_WORKER_TOKEN_REVOKED");
|
||||
await bao("/kv/data/worker", {
|
||||
role: "retired-worker",
|
||||
token: oldToken,
|
||||
expected: [403],
|
||||
});
|
||||
await bao("/auth/cert/login", {
|
||||
role: "retired-worker",
|
||||
body: { name: "worker" },
|
||||
expected: [400, 403],
|
||||
});
|
||||
await privateWrite(
|
||||
checkpoint,
|
||||
encrypt(
|
||||
{
|
||||
phase: "IDENTITIES_REVOKED",
|
||||
pending,
|
||||
peer,
|
||||
oldToken,
|
||||
tokensRevoked,
|
||||
oldTokenDenied: true,
|
||||
},
|
||||
password,
|
||||
),
|
||||
);
|
||||
await compose([
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"install",
|
||||
"-m",
|
||||
"644",
|
||||
"-o",
|
||||
"postgres",
|
||||
"-g",
|
||||
"postgres",
|
||||
"/source-tls/ca.crl",
|
||||
"/run/tls/ca.crl",
|
||||
]);
|
||||
const reloaded = await compose([
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-X",
|
||||
"-t",
|
||||
"-A",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-c",
|
||||
"SELECT pg_reload_conf()",
|
||||
]);
|
||||
requireThat(reloaded.out.trim() === "t", "RESEARCH_PG_CRL_RELOAD_FAILED");
|
||||
for (const service of ["broker-gateway", "s3-gateway", "collector-gateway"])
|
||||
await reloadGateway(service);
|
||||
await Bun.sleep(2500);
|
||||
const brokerIP = await containerIP("broker-gateway");
|
||||
const revokedTLS = await expectDenied(
|
||||
() =>
|
||||
tlsProbe(
|
||||
brokerIP,
|
||||
6379,
|
||||
"broker-gateway",
|
||||
"retired-worker",
|
||||
"*1\r\n$4\r\nPING\r\n",
|
||||
),
|
||||
"client",
|
||||
);
|
||||
return finishWorkerRotation(password, {
|
||||
pending,
|
||||
tokensRevoked,
|
||||
revokedTLS,
|
||||
oldTokenDenied: true,
|
||||
verificationScope: "original peer Bearer API readback",
|
||||
verifyRecovered: async (item) => {
|
||||
const metadata = await http.ready(peer.token, item.id);
|
||||
requireThat(
|
||||
metadata.sha256 === item.sha256,
|
||||
"RESEARCH_ORIGINAL_SHA_CHANGED",
|
||||
);
|
||||
const content = await http.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + item.id + "/content",
|
||||
200,
|
||||
{ actor: peer.token },
|
||||
);
|
||||
requireThat(
|
||||
Buffer.from(content.bytes).equals(Buffer.from(fixture)),
|
||||
"RESEARCH_ORIGINAL_BYTES_CHANGED",
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
export async function finishWorkerRotation(
|
||||
password: string,
|
||||
proof: {
|
||||
pending: { id: string; sha256: string }[];
|
||||
tokensRevoked: number;
|
||||
revokedTLS: string;
|
||||
oldTokenDenied: boolean;
|
||||
verificationScope: string;
|
||||
verifyRecovered: (item: { id: string; sha256: string }) => Promise<void>;
|
||||
},
|
||||
) {
|
||||
const { pending, tokensRevoked, revokedTLS } = proof,
|
||||
rootToken = (await unlock(password)).root_token,
|
||||
ca = resolve(local, "operator/ca");
|
||||
requireThat(
|
||||
pending.length === 3 &&
|
||||
tokensRevoked > 0 &&
|
||||
proof.oldTokenDenied &&
|
||||
revokedTLS === "ERR_SSL_SSLV3_ALERT_CERTIFICATE_REVOKED",
|
||||
"ROTATION_PARTIAL_PROOF_REQUIRED",
|
||||
);
|
||||
const servicesPath = resolve(local, "operator/services.enc"),
|
||||
secrets = decrypt<any>(await readFile(servicesPath, "utf8"), password),
|
||||
oldS3Secret = secrets.s3WorkerSecret;
|
||||
await privateWrite(
|
||||
resolve(local, "operator/worker-compromise-before-secret.enc"),
|
||||
encrypt({ pending, oldS3Secret, services: secrets }, password),
|
||||
);
|
||||
secrets.s3WorkerSecret = randomBytes(32).toString("hex");
|
||||
await privateWrite(servicesPath, encrypt(secrets, password));
|
||||
await provisionS3(password);
|
||||
const retiredSecret = resolve(local, "operator", "retired-s3.json");
|
||||
await privateWrite(
|
||||
retiredSecret,
|
||||
JSON.stringify({
|
||||
Endpoint: "127.0.0.1:19000",
|
||||
Access: secrets.s3WorkerAccess,
|
||||
Secret: oldS3Secret,
|
||||
Bucket: "messenger-attachments",
|
||||
}),
|
||||
);
|
||||
// Use a currently permitted prefix, so ordinary worker ACL denial cannot masquerade as secret revocation.
|
||||
const workerNamespace = await containerID("worker-gateway");
|
||||
// New leaf is installed below before the stale-secret request: otherwise a revoked TLS cert could mask this result.
|
||||
const current = await bao("/kv/data/worker", { token: rootToken });
|
||||
const version = current.data.data.metadata.version;
|
||||
requireThat(
|
||||
Number.isSafeInteger(version) && version >= 1,
|
||||
"INVALID_KV_CAS_VERSION",
|
||||
);
|
||||
const replacement = {
|
||||
...current.data.data.data,
|
||||
s3_json: JSON.stringify({
|
||||
Endpoint: "127.0.0.1:19000",
|
||||
Access: secrets.s3WorkerAccess,
|
||||
Secret: secrets.s3WorkerSecret,
|
||||
Bucket: "messenger-attachments",
|
||||
}),
|
||||
};
|
||||
await bao("/kv/data/worker", {
|
||||
token: rootToken,
|
||||
body: { options: { cas: version }, data: replacement },
|
||||
});
|
||||
await issue(ca, resolve(local, "pki/worker"), "worker", password);
|
||||
await reloadGateway("worker-gateway");
|
||||
const stale = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + workerNamespace,
|
||||
"--mount",
|
||||
`type=bind,source=${retiredSecret},target=/run/operator/s3.json,readonly`,
|
||||
"--entrypoint",
|
||||
"/s3-control",
|
||||
"mtuci-vp7-security-app:local",
|
||||
"-action",
|
||||
"prove-stale",
|
||||
"-config",
|
||||
"/run/operator/s3.json",
|
||||
]);
|
||||
requireThat(
|
||||
stale.out.trim() === "PASS_RETIRED_S3_SECRET_DENIED_ALLOWED_PREFIX_WRITE",
|
||||
"RESEARCH_OLD_SECRET_NOT_DENIED",
|
||||
);
|
||||
await compose(["up", "-d", "worker-agent"]);
|
||||
let rendered = false;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
try {
|
||||
const s = JSON.parse(
|
||||
await readFile(resolve(local, "rendered/worker/s3.json"), "utf8"),
|
||||
);
|
||||
rendered = s.Secret === secrets.s3WorkerSecret;
|
||||
if (rendered) break;
|
||||
} catch {}
|
||||
await Bun.sleep(500);
|
||||
}
|
||||
requireThat(rendered, "RESEARCH_ROTATED_SECRET_NOT_RENDERED");
|
||||
await compose(["up", "-d", "worker"]);
|
||||
const started = Date.now();
|
||||
for (const item of pending) await proof.verifyRecovered(item);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/worker-compromise.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
track: 1,
|
||||
hypothesis:
|
||||
"Scoped worker compromise cannot read business credentials/data or administer dependencies; revoked identity can be replaced while durable queued jobs survive",
|
||||
method:
|
||||
"three real uploads while worker stopped; native cert CRL, token revocation, S3 secret rotation, leaf issuance, native gateway reload, agent render and worker restart",
|
||||
queued: pending.length,
|
||||
recovered: pending.length,
|
||||
originals_byte_equal: true,
|
||||
tokens_revoked: tokensRevoked,
|
||||
old_certificate_new_connection_denial: revokedTLS,
|
||||
old_token_new_request_denied: proof.oldTokenDenied,
|
||||
recovery_verification_scope: proof.verificationScope,
|
||||
secret_rotated: true,
|
||||
new_leaf_without_image_rebuild: true,
|
||||
recovery_seconds_after_worker_start: (Date.now() - started) / 1000,
|
||||
capacity_benchmark: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
await privateWrite(
|
||||
resolve(local, "operator", "worker-compromise-claim.json"),
|
||||
'{"state":"COMPLETE"}',
|
||||
);
|
||||
console.log("PASS_WORKER_COMPROMISE_REVOKE_ROTATE_RECOVER_DURABLE_JOBS");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { compose, run, requireThat } from "./runtime";
|
||||
export async function containerID(service: string) {
|
||||
const id = (await compose(["ps", "-a", "-q", service])).out.trim();
|
||||
requireThat(/^[a-f0-9]{12,64}$/.test(id), "SERVICE_CONTAINER_NOT_FOUND");
|
||||
return id;
|
||||
}
|
||||
export async function containerIP(service: string) {
|
||||
const id = await containerID(service);
|
||||
const info = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
||||
const networks = Object.values(info.NetworkSettings.Networks) as any[];
|
||||
requireThat(
|
||||
networks.length === 1 && /^\d+\.\d+\.\d+\.\d+$/.test(networks[0].IPAddress),
|
||||
"INVALID_SERVICE_NETWORK",
|
||||
);
|
||||
return networks[0].IPAddress as string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export type RuntimeMode = "canonical" | "checked-cache";
|
||||
export function createRuntimePreparation(ports: {
|
||||
build: () => Promise<void>;
|
||||
verifyCache: () => Promise<void>;
|
||||
}) {
|
||||
if (
|
||||
typeof ports?.build !== "function" ||
|
||||
typeof ports?.verifyCache !== "function"
|
||||
)
|
||||
throw new Error("RUNTIME_PREPARATION_PORTS_REQUIRED");
|
||||
return async (mode: RuntimeMode) => {
|
||||
if (mode !== "canonical" && mode !== "checked-cache")
|
||||
throw new Error("INVALID_RUNTIME_MODE");
|
||||
if (mode === "canonical") await ports.build();
|
||||
else await ports.verifyCache();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { mkdir, chmod, writeFile } from "node:fs/promises";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { createCommandRunner } from "./command-runner";
|
||||
export const root = resolve(import.meta.dir, "..");
|
||||
export const local = resolve(root, ".local");
|
||||
export const project = "mtuci-vp7-security";
|
||||
export function requireThat(value: unknown, code: string): asserts value {
|
||||
if (!value) throw new Error(code);
|
||||
}
|
||||
export async function privateWrite(path: string, content: string | Uint8Array) {
|
||||
await mkdir(resolve(path, ".."), { recursive: true, mode: 0o700 });
|
||||
await writeFile(path, content, { mode: 0o600 });
|
||||
await chmod(path, 0o600);
|
||||
}
|
||||
export const run = createCommandRunner({
|
||||
execute: async (args, options) => {
|
||||
const process = Bun.spawn(args, {
|
||||
cwd: options.cwd ?? root,
|
||||
env: { ...Bun.env, ...options.env },
|
||||
stdin: options.input === undefined ? "ignore" : "pipe",
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
});
|
||||
if (
|
||||
options.input !== undefined &&
|
||||
process.stdin &&
|
||||
typeof process.stdin !== "number"
|
||||
) {
|
||||
process.stdin.write(options.input);
|
||||
process.stdin.end();
|
||||
}
|
||||
const [out, err, code] = await Promise.all([
|
||||
new Response(process.stdout).text(),
|
||||
new Response(process.stderr).text(),
|
||||
process.exited,
|
||||
]);
|
||||
return { out, err, code };
|
||||
},
|
||||
unique: async (record) => {
|
||||
await mkdir(resolve(local, "diagnostics"), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
await writeFile(
|
||||
resolve(local, "diagnostics", "command-" + crypto.randomUUID() + ".json"),
|
||||
JSON.stringify(record),
|
||||
{ mode: 0o600, flag: "wx" },
|
||||
);
|
||||
},
|
||||
last: (record) =>
|
||||
privateWrite(
|
||||
resolve(local, "diagnostics", "last-command.json"),
|
||||
JSON.stringify(record),
|
||||
),
|
||||
});
|
||||
export function composeArgs(args: string[]) {
|
||||
return [
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-directory",
|
||||
root,
|
||||
"--env-file",
|
||||
resolve(root, ".env"),
|
||||
"-f",
|
||||
resolve(root, "compose.yaml"),
|
||||
"-p",
|
||||
project,
|
||||
...args,
|
||||
];
|
||||
}
|
||||
export async function compose(
|
||||
args: string[],
|
||||
options: Parameters<typeof run>[1] = {},
|
||||
) {
|
||||
return run(composeArgs(args), options);
|
||||
}
|
||||
export function safeFailure(error: unknown) {
|
||||
const code = error instanceof Error ? error.message : "";
|
||||
try {
|
||||
mkdirSync(resolve(local, "diagnostics"), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
resolve(local, "diagnostics", "last-error.json"),
|
||||
JSON.stringify({
|
||||
message: code,
|
||||
stack: error instanceof Error ? error.stack : "",
|
||||
}),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
} catch {}
|
||||
console.error(
|
||||
/^[A-Z][A-Za-z0-9_:-]{0,240}$/.test(code)
|
||||
? code
|
||||
: "OPERATION_FAILED_DETAILS_PRIVATE",
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// Operator-only test/bootstrap utility. Uses the pinned application's native minio-go SDK and SigV4 signer.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v7/pkg/signer"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type credential struct{ Endpoint, Access, Secret, Bucket string }
|
||||
type inputs struct{ Root, API, Worker credential }
|
||||
|
||||
var receiptDir string
|
||||
|
||||
func receipt(stage string) (*os.File, error) {
|
||||
if receiptDir == "" {
|
||||
return nil, fmt.Errorf("operator receipt directory required")
|
||||
}
|
||||
var nonce [12]byte
|
||||
if _, e := rand.Read(nonce[:]); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
f, e := os.OpenFile(filepath.Join(receiptDir, hex.EncodeToString(nonce[:])+".json"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = json.NewEncoder(f).Encode(map[string]any{"state": "RUNNING", "stage": stage}); e != nil {
|
||||
_ = f.Close()
|
||||
return nil, e
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
func finishReceipt(f *os.File, value any) error {
|
||||
if _, e := f.Seek(0, 0); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := f.Truncate(0); e != nil {
|
||||
return e
|
||||
}
|
||||
return json.NewEncoder(f).Encode(value)
|
||||
}
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "S3_CONTROL_OPERATION_FAILED")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func client(c credential, anonymous bool) *minio.Client {
|
||||
cred := credentials.NewStaticV4(c.Access, c.Secret, "")
|
||||
if anonymous {
|
||||
cred = credentials.NewStaticV4("", "", "")
|
||||
}
|
||||
v, e := minio.New(c.Endpoint, &minio.Options{Creds: cred, Region: "us-east-1", Secure: false})
|
||||
must(e)
|
||||
return v
|
||||
}
|
||||
func admin(ctx context.Context, c credential, path string, value any) error {
|
||||
record, e := receipt(path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer func() { _ = record.Close() }()
|
||||
body, e := json.Marshal(value)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
request, e := http.NewRequestWithContext(ctx, http.MethodPut, "http://"+c.Endpoint+"/rustfs/admin/v3/"+path, bytes.NewReader(body))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
request.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum[:]))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
signed := signer.SignV4(*request, c.Access, c.Secret, "", "us-east-1")
|
||||
response, e := (&http.Client{Timeout: 5 * time.Second}).Do(signed)
|
||||
if e != nil {
|
||||
_ = finishReceipt(record, map[string]any{"state": "UNCERTAIN", "stage": path, "error": e.Error()})
|
||||
return e
|
||||
}
|
||||
defer response.Body.Close()
|
||||
raw, readErr := io.ReadAll(io.LimitReader(response.Body, 65537))
|
||||
receiptErr := finishReceipt(record, map[string]any{"state": "RESPONSE", "stage": path, "http_status": response.StatusCode, "response_body": raw, "body_read_error": readErr != nil})
|
||||
if response.StatusCode != 200 && response.StatusCode != 204 {
|
||||
return fmt.Errorf("admin rejected")
|
||||
}
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
if len(raw) > 65536 {
|
||||
return fmt.Errorf("admin response too large")
|
||||
}
|
||||
return receiptErr
|
||||
}
|
||||
func policy(c credential, role string) any {
|
||||
object := func(actions []string, prefixes ...string) any {
|
||||
resources := []string{}
|
||||
for _, prefix := range prefixes {
|
||||
resources = append(resources, "arn:aws:s3:::"+c.Bucket+"/"+prefix+"/*")
|
||||
}
|
||||
return map[string]any{"Effect": "Allow", "Action": actions, "Resource": resources}
|
||||
}
|
||||
bucketActions := []string{"s3:GetBucketLocation"}
|
||||
if role == "api" {
|
||||
bucketActions = append(bucketActions, "s3:ListBucket")
|
||||
}
|
||||
statements := []any{map[string]any{"Effect": "Allow", "Action": bucketActions, "Resource": []string{"arn:aws:s3:::" + c.Bucket}}}
|
||||
if role == "api" {
|
||||
statements = append(statements, object([]string{"s3:PutObject", "s3:GetObject", "s3:DeleteObject"}, "staging"), object([]string{"s3:GetObject"}, "originals", "variants"))
|
||||
} else {
|
||||
statements = append(statements, object([]string{"s3:GetObject", "s3:DeleteObject"}, "staging"), object([]string{"s3:GetObject", "s3:PutObject"}, "originals", "variants"))
|
||||
}
|
||||
return map[string]any{"Version": "2012-10-17", "Statement": statements}
|
||||
}
|
||||
func bootstrap(ctx context.Context, c inputs) {
|
||||
root := client(c.Root, false)
|
||||
exists, e := root.BucketExists(ctx, c.Root.Bucket)
|
||||
must(e)
|
||||
if !exists {
|
||||
must(root.MakeBucket(ctx, c.Root.Bucket, minio.MakeBucketOptions{Region: "us-east-1"}))
|
||||
}
|
||||
for _, item := range []struct {
|
||||
role string
|
||||
c credential
|
||||
}{{"api", c.API}, {"worker", c.Worker}} {
|
||||
name := "vp7-" + item.role
|
||||
must(admin(ctx, c.Root, "add-canned-policy?name="+name, policy(item.c, item.role)))
|
||||
must(admin(ctx, c.Root, "add-user?accessKey="+url.QueryEscape(item.c.Access), map[string]string{"secretKey": item.c.Secret, "status": "enabled"}))
|
||||
must(admin(ctx, c.Root, "set-user-or-group-policy?policyName="+name+"&userOrGroup="+url.QueryEscape(item.c.Access)+"&isGroup=false", nil))
|
||||
}
|
||||
}
|
||||
func denied(err error) bool { return err != nil && minio.ToErrorResponse(err).Code == "AccessDenied" }
|
||||
func proof(ctx context.Context, c credential) {
|
||||
s := client(c, false)
|
||||
key := "variants/security-probe/" + fmt.Sprint(time.Now().UnixNano())
|
||||
payload := "worker-scope-probe"
|
||||
_, e := s.PutObject(ctx, c.Bucket, key, strings.NewReader(payload), int64(len(payload)), minio.PutObjectOptions{DisableMultipart: true})
|
||||
must(e)
|
||||
obj, e := s.GetObject(ctx, c.Bucket, key, minio.GetObjectOptions{})
|
||||
must(e)
|
||||
data, e := io.ReadAll(io.LimitReader(obj, 100))
|
||||
must(e)
|
||||
must(obj.Close())
|
||||
if string(data) != payload {
|
||||
must(fmt.Errorf("wrong object"))
|
||||
}
|
||||
_, e = s.PutObject(ctx, c.Bucket, "forbidden/"+key, strings.NewReader(payload), int64(len(payload)), minio.PutObjectOptions{DisableMultipart: true})
|
||||
if !denied(e) {
|
||||
must(fmt.Errorf("forbidden prefix accepted"))
|
||||
}
|
||||
if !denied(s.MakeBucket(ctx, "vp7-worker-forbidden", minio.MakeBucketOptions{})) {
|
||||
must(fmt.Errorf("bucket admin accepted"))
|
||||
}
|
||||
a := client(c, true)
|
||||
o, e := a.GetObject(ctx, c.Bucket, key, minio.GetObjectOptions{})
|
||||
if e == nil {
|
||||
_, e = o.Stat()
|
||||
_ = o.Close()
|
||||
}
|
||||
if !denied(e) {
|
||||
must(fmt.Errorf("anonymous object accepted"))
|
||||
}
|
||||
fmt.Println("PASS_WORKER_S3_ALLOWED_VARIANT_DENIED_PREFIX_ADMIN_ANONYMOUS")
|
||||
}
|
||||
func stale(ctx context.Context, c credential) {
|
||||
s := client(c, false)
|
||||
_, e := s.PutObject(ctx, c.Bucket, "variants/rotation-secret-probe", strings.NewReader("retired-secret"), 14, minio.PutObjectOptions{DisableMultipart: true})
|
||||
if e == nil {
|
||||
must(fmt.Errorf("retired secret still accepted"))
|
||||
}
|
||||
code := minio.ToErrorResponse(e).Code
|
||||
if code != "SignatureDoesNotMatch" && code != "InvalidAccessKeyId" && code != "AccessDenied" {
|
||||
must(fmt.Errorf("retired secret failed for unrelated reason"))
|
||||
}
|
||||
fmt.Println("PASS_RETIRED_S3_SECRET_DENIED_ALLOWED_PREFIX_WRITE")
|
||||
}
|
||||
func main() {
|
||||
action := flag.String("action", "", "bootstrap, prove-worker or prove-stale")
|
||||
path := flag.String("config", "", "operator-only configuration path")
|
||||
flag.StringVar(&receiptDir, "receipt-dir", "", "private operator response directory")
|
||||
flag.Parse()
|
||||
raw, e := os.ReadFile(*path)
|
||||
must(e)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
switch *action {
|
||||
case "bootstrap":
|
||||
var config inputs
|
||||
must(json.Unmarshal(raw, &config))
|
||||
record, e := receipt("bootstrap")
|
||||
must(e)
|
||||
bootstrap(ctx, config)
|
||||
must(finishReceipt(record, map[string]any{"state": "COMPLETE", "stage": "bootstrap"}))
|
||||
must(record.Close())
|
||||
fmt.Println("PASS_S3_SEPARATE_PREFIX_SCOPED_PRINCIPALS")
|
||||
case "prove-worker":
|
||||
var config credential
|
||||
must(json.Unmarshal(raw, &config))
|
||||
proof(ctx, config)
|
||||
case "prove-stale":
|
||||
var config credential
|
||||
must(json.Unmarshal(raw, &config))
|
||||
stale(ctx, config)
|
||||
default:
|
||||
must(fmt.Errorf("unsupported action"))
|
||||
}
|
||||
}
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Only this stateful operator process receives root credentials; values stay out of Compose/env inspection.
|
||||
set -a
|
||||
. /config/s3.env
|
||||
set +a
|
||||
exec /usr/bin/rustfs server --address 127.0.0.1:19000 /data
|
||||
@@ -0,0 +1,55 @@
|
||||
import { readFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { local, root, privateWrite, run, requireThat } from "./runtime";
|
||||
import { decrypt } from "./operator-crypto";
|
||||
import { containerID } from "./runtime-inspect";
|
||||
export async function provisionS3(password: string) {
|
||||
const secrets = decrypt<any>(
|
||||
await readFile(resolve(local, "operator", "services.enc"), "utf8"),
|
||||
password,
|
||||
);
|
||||
const cred = (Access: string, Secret: string) => ({
|
||||
Endpoint: "127.0.0.1:19000",
|
||||
Access,
|
||||
Secret,
|
||||
Bucket: "messenger-attachments",
|
||||
});
|
||||
const config = {
|
||||
Root: cred(secrets.s3RootAccess, secrets.s3RootSecret),
|
||||
API: cred(secrets.s3ApiAccess, secrets.s3ApiSecret),
|
||||
Worker: cred(secrets.s3WorkerAccess, secrets.s3WorkerSecret),
|
||||
};
|
||||
const file = resolve(local, "operator", "s3-bootstrap.json");
|
||||
await privateWrite(file, JSON.stringify(config));
|
||||
const receipts = resolve(local, "operator", "s3-receipts");
|
||||
await mkdir(receipts, { recursive: true, mode: 0o700 });
|
||||
const namespace = await containerID("s3-gateway");
|
||||
const result = await run([
|
||||
"docker",
|
||||
"run",
|
||||
"--pull=never",
|
||||
"--rm",
|
||||
"--user",
|
||||
`${process.getuid?.()}:${process.getgid?.()}`,
|
||||
"--network",
|
||||
"container:" + namespace,
|
||||
"--mount",
|
||||
`type=bind,source=${file},target=/run/operator/s3.json,readonly`,
|
||||
"--mount",
|
||||
`type=bind,source=${receipts},target=/run/operator/receipts`,
|
||||
"--entrypoint",
|
||||
"/s3-control",
|
||||
"mtuci-vp7-security-app:local",
|
||||
"-action",
|
||||
"bootstrap",
|
||||
"-config",
|
||||
"/run/operator/s3.json",
|
||||
"-receipt-dir",
|
||||
"/run/operator/receipts",
|
||||
]);
|
||||
requireThat(
|
||||
result.out.trim() === "PASS_S3_SEPARATE_PREFIX_SCOPED_PRINCIPALS",
|
||||
"S3_BOOTSTRAP_INVALID_RECEIPT",
|
||||
);
|
||||
console.log(result.out.trim());
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
export const sealedServices = ["api1", "api2", "worker"] as const;
|
||||
export type SealedService = (typeof sealedServices)[number];
|
||||
export type ProcessState = { id: string; running: boolean; restarts: number };
|
||||
export type CauseEvent = { event: string; milliseconds: number };
|
||||
export type SealedBaseline = {
|
||||
baseline: Record<SealedService, ProcessState>;
|
||||
freshness: Record<SealedService, number>;
|
||||
started: number;
|
||||
};
|
||||
export type SealedPorts = {
|
||||
inspect: (
|
||||
service: SealedService,
|
||||
expectedId: string | null,
|
||||
) => Promise<ProcessState>;
|
||||
readFreshness: (service: SealedService) => Promise<string>;
|
||||
readEvents: (id: string, since: number) => Promise<CauseEvent[]>;
|
||||
retainBaseline: (value: SealedBaseline) => Promise<void>;
|
||||
seal: () => Promise<void>;
|
||||
now: () => number;
|
||||
sleep: (milliseconds: number) => Promise<void>;
|
||||
};
|
||||
export type SealLimits = {
|
||||
maxAgeMilliseconds: number;
|
||||
deadlineMilliseconds: number;
|
||||
pollMilliseconds: number;
|
||||
};
|
||||
export function createSealedShutdown(ports: SealedPorts, limits: SealLimits) {
|
||||
for (const key of [
|
||||
"inspect",
|
||||
"readFreshness",
|
||||
"readEvents",
|
||||
"retainBaseline",
|
||||
"seal",
|
||||
"now",
|
||||
"sleep",
|
||||
] as const)
|
||||
if (typeof ports?.[key] !== "function")
|
||||
throw Error("SEALED_PORTS_REQUIRED");
|
||||
if (
|
||||
!Object.values(limits).every((x) => Number.isSafeInteger(x) && x > 0) ||
|
||||
limits.pollMilliseconds > limits.deadlineMilliseconds
|
||||
)
|
||||
throw Error("SEALED_LIMITS_INVALID");
|
||||
return async () => {
|
||||
const baseline = {} as Record<SealedService, ProcessState>,
|
||||
freshness = {} as Record<SealedService, number>;
|
||||
const now = () => {
|
||||
const value = ports.now();
|
||||
if (!Number.isFinite(value) || value < 0)
|
||||
throw Error("SEALED_CLOCK_INVALID");
|
||||
return value;
|
||||
};
|
||||
for (const service of sealedServices) {
|
||||
const state = await ports.inspect(service, null);
|
||||
if (!state.running) throw Error("SEALED_BASELINE_NOT_RUNNING");
|
||||
if (
|
||||
!/^[a-f0-9]{12,64}$/.test(state.id) ||
|
||||
!Number.isSafeInteger(state.restarts) ||
|
||||
state.restarts < 0
|
||||
)
|
||||
throw Error("SEALED_BASELINE_INVALID");
|
||||
baseline[service] = state;
|
||||
freshness[service] = Date.parse(
|
||||
(await ports.readFreshness(service)).trim(),
|
||||
);
|
||||
}
|
||||
const started = now();
|
||||
for (const service of sealedServices) {
|
||||
const age = started - freshness[service];
|
||||
if (!Number.isFinite(age) || age < 0 || age > limits.maxAgeMilliseconds)
|
||||
throw Error("SEALED_BASELINE_NOT_FRESH");
|
||||
}
|
||||
await ports.retainBaseline({ baseline, freshness, started });
|
||||
const dispatch = now();
|
||||
for (const service of sealedServices) {
|
||||
const age = dispatch - freshness[service];
|
||||
if (!Number.isFinite(age) || age < 0 || age > limits.maxAgeMilliseconds)
|
||||
throw Error("SEALED_BASELINE_NOT_FRESH");
|
||||
}
|
||||
await ports.seal();
|
||||
const sealedAt = now();
|
||||
const observed: Partial<
|
||||
Record<
|
||||
SealedService,
|
||||
{
|
||||
id: string;
|
||||
event: string;
|
||||
seconds: number;
|
||||
running: boolean;
|
||||
restarts: number;
|
||||
cause_milliseconds: number;
|
||||
}
|
||||
>
|
||||
> = {};
|
||||
while (now() - started < limits.deadlineMilliseconds) {
|
||||
for (const service of sealedServices) {
|
||||
if (observed[service]) continue;
|
||||
const base = baseline[service],
|
||||
state = await ports.inspect(service, base.id);
|
||||
if (state.id !== base.id) throw Error("SEALED_CONTAINER_CHANGED");
|
||||
const at = now();
|
||||
if (at < sealedAt) throw Error("SEALED_CLOCK_INVALID");
|
||||
const events = await ports.readEvents(base.id, sealedAt),
|
||||
cause = events.find(
|
||||
(e) =>
|
||||
e.event === "secret_freshness_failed" &&
|
||||
Number.isFinite(e.milliseconds) &&
|
||||
e.milliseconds >= sealedAt &&
|
||||
e.milliseconds <= at,
|
||||
);
|
||||
if (cause && (!state.running || state.restarts > base.restarts))
|
||||
observed[service] = {
|
||||
id: base.id,
|
||||
event: "secret_freshness_failed",
|
||||
seconds: (at - started) / 1000,
|
||||
running: state.running,
|
||||
restarts: state.restarts,
|
||||
cause_milliseconds: cause.milliseconds,
|
||||
};
|
||||
}
|
||||
if (sealedServices.every((s) => observed[s]))
|
||||
return { started, sealedAt, baseline, freshness, observed };
|
||||
await ports.sleep(limits.pollMilliseconds);
|
||||
}
|
||||
throw Error("SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
X509Certificate,
|
||||
createPrivateKey,
|
||||
createPublicKey,
|
||||
timingSafeEqual,
|
||||
} from "node:crypto";
|
||||
import { requireThat } from "./runtime";
|
||||
export function validAge(age: number, maximum: number): number {
|
||||
requireThat(
|
||||
Number.isFinite(age) &&
|
||||
age >= 0 &&
|
||||
Number.isFinite(maximum) &&
|
||||
maximum >= 0 &&
|
||||
age <= maximum,
|
||||
"INVALID_EVIDENCE_AGE",
|
||||
);
|
||||
return age;
|
||||
}
|
||||
export function allowedIdentity(
|
||||
identity: string,
|
||||
allowed: readonly string[],
|
||||
): string {
|
||||
requireThat(allowed.includes(identity), "FORBIDDEN_CERTIFICATE_ROLE");
|
||||
return identity;
|
||||
}
|
||||
export function requireTLSURL(address: string, hostname: string): URL {
|
||||
const u = new URL(address);
|
||||
requireThat(
|
||||
u.protocol === "https:" &&
|
||||
u.hostname === hostname &&
|
||||
!u.username &&
|
||||
!u.password,
|
||||
"INVALID_TLS_ENDPOINT",
|
||||
);
|
||||
return u;
|
||||
}
|
||||
export function validateLeaf(
|
||||
certPEM: string,
|
||||
keyPEM: string,
|
||||
caPEM: string,
|
||||
hostname: string,
|
||||
now = Date.now(),
|
||||
) {
|
||||
const cert = new X509Certificate(certPEM),
|
||||
ca = new X509Certificate(caPEM);
|
||||
for (const c of [cert, ca])
|
||||
requireThat(
|
||||
Number.isFinite(Date.parse(c.validFrom)) &&
|
||||
Date.parse(c.validFrom) <= now &&
|
||||
now < Date.parse(c.validTo),
|
||||
"CERTIFICATE_LIFETIME_INVALID",
|
||||
);
|
||||
requireThat(
|
||||
ca.ca && !cert.ca && cert.verify(ca.publicKey),
|
||||
"CERTIFICATE_CA_INVALID",
|
||||
);
|
||||
requireThat(
|
||||
cert.checkHost(hostname, { subject: "never" }) === hostname,
|
||||
"CERTIFICATE_SAN_INVALID",
|
||||
);
|
||||
const publicKey = createPublicKey(createPrivateKey(keyPEM)).export({
|
||||
format: "der",
|
||||
type: "spki",
|
||||
}),
|
||||
expected = cert.publicKey.export({ format: "der", type: "spki" });
|
||||
requireThat(
|
||||
publicKey.length === expected.length &&
|
||||
timingSafeEqual(publicKey, expected),
|
||||
"CERTIFICATE_KEY_MISMATCH",
|
||||
);
|
||||
return {
|
||||
serial: cert.serialNumber,
|
||||
fingerprint: cert.fingerprint256,
|
||||
expires: cert.validTo,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
export type LoginObservation = {
|
||||
status: number;
|
||||
alias: string;
|
||||
actorCorrect: boolean;
|
||||
retryAfter: string | null;
|
||||
errorCode: string | null;
|
||||
};
|
||||
export type Replica = "api1" | "api2";
|
||||
export function createSharedLoginCase(ports: {
|
||||
request: (
|
||||
replica: Replica,
|
||||
kind: "main" | "control",
|
||||
) => Promise<LoginObservation>;
|
||||
now: () => number;
|
||||
}) {
|
||||
if (typeof ports?.request !== "function" || typeof ports?.now !== "function")
|
||||
throw Error("LOGIN_CASE_PORTS_REQUIRED");
|
||||
return async (expectedAliases: Record<Replica, string>) => {
|
||||
if (
|
||||
expectedAliases.api1 === expectedAliases.api2 ||
|
||||
!Object.values(expectedAliases).every((s) => /^[a-f0-9-]{36}$/.test(s))
|
||||
)
|
||||
throw Error("LOGIN_BASELINE_INVALID");
|
||||
const started = ports.now(),
|
||||
rows: { replica: Replica; result: LoginObservation }[] = [];
|
||||
for (let i = 0; i < 10; i++)
|
||||
rows.push(
|
||||
...(await Promise.all(
|
||||
(["api1", "api2"] as const).map(async (replica) => ({
|
||||
replica,
|
||||
result: await ports.request(replica, "main"),
|
||||
})),
|
||||
)),
|
||||
);
|
||||
const accepted = rows.filter((r) => r.result.status === 201).length,
|
||||
denied = rows.filter((r) => r.result.status === 429).length;
|
||||
const elapsedMilliseconds = ports.now() - started;
|
||||
if (
|
||||
!Number.isFinite(started) ||
|
||||
!Number.isFinite(elapsedMilliseconds) ||
|
||||
elapsedMilliseconds < 0 ||
|
||||
elapsedMilliseconds >= 60000
|
||||
)
|
||||
throw Error("LOGIN_CASE_WINDOW_EXPIRED");
|
||||
for (const { replica, result } of rows) {
|
||||
if (result.alias !== expectedAliases[replica])
|
||||
throw Error("LOGIN_INSTANCE_MISMATCH");
|
||||
if (result.status !== 201 && result.status !== 429)
|
||||
throw Error("LOGIN_STATUS_UNEXPECTED");
|
||||
if (result.status === 201 && !result.actorCorrect)
|
||||
throw Error("LOGIN_SUCCESS_ACTOR_MISMATCH");
|
||||
if (result.status === 429) {
|
||||
if (
|
||||
!/^[1-9][0-9]*$/.test(result.retryAfter ?? "") ||
|
||||
Number(result.retryAfter) > 60
|
||||
)
|
||||
throw Error("LOGIN_RETRY_AFTER_INVALID");
|
||||
if (result.errorCode !== "rate_limited")
|
||||
throw Error("LOGIN_REJECTION_BODY_INVALID");
|
||||
}
|
||||
}
|
||||
if (
|
||||
accepted !== 10 ||
|
||||
denied !== 10 ||
|
||||
!(["api1", "api2"] as const).every((replica) =>
|
||||
rows.some((r) => r.replica === replica && r.result.status === 429),
|
||||
)
|
||||
)
|
||||
throw Error("SHARED_LIMIT_NOT_PROVED");
|
||||
const controls = await Promise.all(
|
||||
(["api1", "api2"] as const).map((replica) =>
|
||||
ports.request(replica, "control"),
|
||||
),
|
||||
);
|
||||
if (
|
||||
!controls.every(
|
||||
(r, i) =>
|
||||
r.status === 201 &&
|
||||
r.actorCorrect &&
|
||||
r.alias === expectedAliases[i === 0 ? "api1" : "api2"],
|
||||
)
|
||||
)
|
||||
throw Error("LOGIN_CONTROL_FAILED");
|
||||
return {
|
||||
requests: rows.length,
|
||||
accepted,
|
||||
denied,
|
||||
controls: controls.length,
|
||||
elapsedMilliseconds,
|
||||
};
|
||||
};
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec bun "$HERE/hooks.ts" stop-one
|
||||
@@ -0,0 +1,83 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root } from "./runtime";
|
||||
const metrics = [
|
||||
["Requests / second", "sum(rate(http_requests[1m]))"],
|
||||
[
|
||||
"HTTP p50 seconds",
|
||||
"histogram_quantile(0.50,sum by (le)(rate(http_duration_bucket[1m])))",
|
||||
],
|
||||
[
|
||||
"HTTP p99 seconds",
|
||||
"histogram_quantile(0.99,sum by (le)(rate(http_duration_bucket[1m])))",
|
||||
],
|
||||
[
|
||||
"HTTP server error ratio",
|
||||
'(sum(rate(http_requests{status_class="5xx"}[1m])) or vector(0)) / clamp_min(sum(rate(http_requests[1m])),0.001)',
|
||||
],
|
||||
[
|
||||
"HTTP p95 seconds",
|
||||
"histogram_quantile(0.95,sum by (le)(rate(http_duration_bucket[1m])))",
|
||||
],
|
||||
["Jobs by outcome", "sum by (outcome)(rate(jobs_processed[1m]))"],
|
||||
[
|
||||
"Job duration p95 seconds",
|
||||
"histogram_quantile(0.95,sum by(le)(rate(job_duration_bucket[1m])))",
|
||||
],
|
||||
[
|
||||
"Time to ready p95 seconds",
|
||||
"histogram_quantile(0.95,sum by(le)(rate(time_to_ready_bucket[1m])))",
|
||||
],
|
||||
["Oldest unfinished job seconds", "max(queue_oldest_age_seconds)"],
|
||||
["Unfinished jobs", "max(queue_depth)"],
|
||||
["Worker busy", "sum(worker_busy)"],
|
||||
[
|
||||
"Worker capacity",
|
||||
"sum((worker_capacity and (timestamp(worker_capacity) > time()-10)))",
|
||||
],
|
||||
[
|
||||
"Database observer up",
|
||||
"min((database_observer_up and (timestamp(database_observer_up) > time()-10)))",
|
||||
],
|
||||
["Database pool used", "sum(db_pool_used)"],
|
||||
["Database pending acquires", "sum(db_pool_pending_acquires)"],
|
||||
[
|
||||
"Database pool capacity",
|
||||
"sum((db_pool_capacity and (timestamp(db_pool_capacity)>time()-10)))",
|
||||
],
|
||||
[
|
||||
"Ready within 10 seconds",
|
||||
"max(ready_slo_timely_10s) / clamp_min(max(ready_slo_matured_10s),1)",
|
||||
],
|
||||
[
|
||||
"Ready within 30 seconds",
|
||||
"max(ready_slo_timely_30s) / clamp_min(max(ready_slo_matured_30s),1)",
|
||||
],
|
||||
[
|
||||
"Ready within 300 seconds",
|
||||
"max(ready_slo_timely_300s) / clamp_min(max(ready_slo_matured_300s),1)",
|
||||
],
|
||||
];
|
||||
const dashboard = {
|
||||
uid: "messenger-security",
|
||||
title: "Messenger lab7 security and pipeline",
|
||||
schemaVersion: 39,
|
||||
version: 1,
|
||||
editable: false,
|
||||
time: { from: "now-15m", to: "now" },
|
||||
refresh: "5s",
|
||||
panels: metrics.map(([title, expr], i) => ({
|
||||
id: i + 1,
|
||||
title,
|
||||
type: "timeseries",
|
||||
datasource: { type: "prometheus", uid: "prometheus" },
|
||||
gridPos: { x: (i % 2) * 12, y: Math.floor(i / 2) * 8, w: 12, h: 8 },
|
||||
targets: [{ refId: "A", expr }],
|
||||
fieldConfig: { defaults: {}, overrides: [] },
|
||||
options: { legend: { displayMode: "list", placement: "bottom" } },
|
||||
})),
|
||||
};
|
||||
await writeFile(
|
||||
resolve(root, "infra/grafana/dashboards/messenger.json"),
|
||||
JSON.stringify(dashboard, null, 2) + "\n",
|
||||
);
|
||||
@@ -0,0 +1,111 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, copyFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { bootstrap } from "./bootstrap";
|
||||
import { createCA, issue } from "./pki";
|
||||
import { local, root, compose, requireThat, safeFailure } from "./runtime";
|
||||
import { provisionDB } from "./db-provision";
|
||||
import { postgresTransport } from "../student-tests/postgres-transport";
|
||||
import { run } from "./runtime";
|
||||
import { images } from "./topology";
|
||||
try {
|
||||
const password = randomBytes(32).toString("hex"); // Deliberately process-only: disposable test stand, manual mode uses operator's hidden prompt.
|
||||
await bootstrap(password);
|
||||
await createCA(resolve(local, "operator", "foreign-ca"), password);
|
||||
await issue(
|
||||
resolve(local, "operator", "foreign-ca"),
|
||||
resolve(local, "pki", "foreign-lb"),
|
||||
"lb",
|
||||
password,
|
||||
);
|
||||
await compose(["config", "--quiet"]);
|
||||
// Validate every generated gateway with the installed native parser before any service starts.
|
||||
for (const service of [
|
||||
"lb",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"worker-gateway",
|
||||
"broker-gateway",
|
||||
"s3-gateway",
|
||||
"collector-gateway",
|
||||
"openobserve-gateway",
|
||||
"grafana-gateway",
|
||||
])
|
||||
await compose([
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
service,
|
||||
"haproxy",
|
||||
"-c",
|
||||
"-f",
|
||||
"/usr/local/etc/haproxy/haproxy.cfg",
|
||||
]);
|
||||
await compose([
|
||||
"up",
|
||||
"-d",
|
||||
"postgres",
|
||||
"broker-gateway",
|
||||
"broker",
|
||||
"worker-gateway",
|
||||
]);
|
||||
for (let attempt = 0; attempt < 30; attempt++) {
|
||||
const ready = await compose(
|
||||
[
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"pg_isready",
|
||||
"-h",
|
||||
"127.0.0.1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
if (ready.code === 0) break;
|
||||
requireThat(attempt < 29, "POSTGRES_STARTUP_TIMEOUT");
|
||||
await Bun.sleep(1000);
|
||||
}
|
||||
await provisionDB(password);
|
||||
await postgresTransport();
|
||||
console.log("PASS_BASE_TRANSPORT_TESTS_NO_NEW_IMAGES");
|
||||
await writeFile(
|
||||
resolve(local, "test-session-ready.json"),
|
||||
JSON.stringify({
|
||||
state: "WAITING_EXISTING_IMAGES_ONLY",
|
||||
pid: process.pid,
|
||||
password_persisted: false,
|
||||
}),
|
||||
);
|
||||
// No pulls occur here. Root owns download approval and source handover; continue only when both arrive.
|
||||
for (let attempt = 0; attempt < 3600; attempt++) {
|
||||
const available = await run(
|
||||
[
|
||||
"docker",
|
||||
"image",
|
||||
"inspect",
|
||||
images.bao,
|
||||
images.collector,
|
||||
images.openobserve,
|
||||
images.grafana,
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
if (
|
||||
available.code === 0 &&
|
||||
(await Bun.file(resolve(root, "BACKEND-READY.json")).exists())
|
||||
) {
|
||||
const ready = await import("./acceptance-session");
|
||||
await ready.acceptanceSession(password);
|
||||
console.log("PASS_SECURITY_SESSION_COMPLETE");
|
||||
process.exit(0);
|
||||
}
|
||||
await Bun.sleep(10_000);
|
||||
}
|
||||
throw new Error("AWAITING_ROOT_IMAGES_AND_CHECKED_BACKEND");
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
import { resolve } from "node:path";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { root, local } from "./runtime";
|
||||
import { openobserveQueryPolicy } from "./openobserve-query-policy";
|
||||
export const images = {
|
||||
haproxy:
|
||||
"haproxy:3.2-alpine@sha256:1c3568e520453cc8ba98c39501febcf450429c80e6cc27ecad779961d76e597c",
|
||||
postgres:
|
||||
"postgres:18.6@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336",
|
||||
broker:
|
||||
"valkey/valkey:9@sha256:418652cfb58ef879d4978c33553735d7147016032d5aefaa14c828e611eb9dfd",
|
||||
s3: "rustfs/rustfs:1.0.0-rc.1@sha256:f53d700fc16809070326f6ab3fb565d48e722364a7bd5a12e47d0a5abe079ce6",
|
||||
bao: "openbao/openbao:2.7.2@sha256:a78eb12a9fc7a3ebb4bec1724e2bdd6a28e33394820641d061166919a3f1866b",
|
||||
collector:
|
||||
"otel/opentelemetry-collector-k8s:0.163.2@sha256:a65df9129a5b3f99ee4434c5e53aee1965ff0129eda6a2da75ea917165b7fa6b",
|
||||
openobserve:
|
||||
"public.ecr.aws/zinclabs/openobserve:v1.1.2@sha256:26618f379c86b253c0d91624c487dd14b71293699845ecbc8457c94dca14819f",
|
||||
grafana:
|
||||
"grafana/grafana@sha256:1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e",
|
||||
};
|
||||
export const roles = [
|
||||
"lb",
|
||||
"api",
|
||||
"worker",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"postgres",
|
||||
"broker-gateway",
|
||||
"s3-gateway",
|
||||
"collector-gateway",
|
||||
"collector",
|
||||
"openobserve-gateway",
|
||||
"grafana",
|
||||
"openbao",
|
||||
"operator",
|
||||
"forbidden",
|
||||
];
|
||||
const base = {
|
||||
restart: "unless-stopped",
|
||||
read_only: true,
|
||||
cap_drop: ["ALL"],
|
||||
security_opt: ["no-new-privileges:true"],
|
||||
pids_limit: 128,
|
||||
cpu_shares: 128,
|
||||
cpus: 0.5,
|
||||
mem_limit: "128m",
|
||||
tmpfs: ["/tmp:size=16777216,mode=1777"],
|
||||
logging: {
|
||||
driver: "json-file",
|
||||
options: { "max-size": "2m", "max-file": "2" },
|
||||
},
|
||||
};
|
||||
const runUser = "${LOCAL_UID:?run bootstrap}:${LOCAL_GID:?run bootstrap}";
|
||||
const ro = (src: string, dst: string) => ({
|
||||
type: "bind",
|
||||
source: src,
|
||||
target: dst,
|
||||
read_only: true,
|
||||
bind: { create_host_path: false },
|
||||
});
|
||||
const rw = (src: string, dst: string) => ({
|
||||
type: "bind",
|
||||
source: src,
|
||||
target: dst,
|
||||
bind: { create_host_path: false },
|
||||
});
|
||||
const pki = (role: string) => ro(`./.local/pki/${role}`, "/pki");
|
||||
function gateway(role: string, configName = role) {
|
||||
return {
|
||||
...base,
|
||||
image: images.haproxy,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
networks: ["private"],
|
||||
volumes: [
|
||||
pki(role),
|
||||
ro(`./config/${configName}.cfg`, "/usr/local/etc/haproxy/haproxy.cfg"),
|
||||
],
|
||||
command: [
|
||||
"haproxy",
|
||||
"-W",
|
||||
"-db",
|
||||
"-f",
|
||||
"/usr/local/etc/haproxy/haproxy.cfg",
|
||||
],
|
||||
};
|
||||
}
|
||||
const global = `global\n maxconn 256\n nbthread 1\n hard-stop-after 2s\n ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets\n ssl-default-server-options ssl-min-ver TLSv1.2\ndefaults\n mode tcp\n timeout connect 2s\n timeout client 30s\n timeout server 30s\nresolvers docker\n nameserver dns 127.0.0.11:53\n resolve_retries 3\n timeout resolve 1s\n timeout retry 1s\n hold valid 1s\n`;
|
||||
function incoming(
|
||||
name: string,
|
||||
port: number,
|
||||
upstream: number,
|
||||
allowed: string[],
|
||||
publicTLS = false,
|
||||
) {
|
||||
return `\nlisten ${name}\n bind :${port} ssl crt /pki/server.pem${publicTLS ? "" : " ca-file /pki/ca.crt crl-file /pki/ca.crl verify required"}\n${publicTLS ? "" : ` tcp-request content reject unless { ssl_c_s_dn(CN) -m str ${allowed.join(" ")} }\n`} server local 127.0.0.1:${upstream}\n`;
|
||||
}
|
||||
function outgoing(
|
||||
name: string,
|
||||
localPort: number,
|
||||
host: string,
|
||||
port: number,
|
||||
alpn = "",
|
||||
) {
|
||||
return `\nlisten ${name}\n bind 127.0.0.1:${localPort}\n server remote ${host}:${port} ssl verify required ca-file /pki/ca.crt crt /pki/server.pem crl-file /pki/ca.crl verifyhost ${host} sni str(${host})${alpn ? " alpn " + alpn : ""} resolvers docker init-addr none\n`;
|
||||
}
|
||||
export function gatewayConfigs() {
|
||||
const out: Record<string, string> = {};
|
||||
for (const role of ["api1-gateway", "api2-gateway", "worker"])
|
||||
out[role] =
|
||||
global +
|
||||
(role === "worker" ? "" : incoming("api", 8443, 8080, ["lb"])) +
|
||||
outgoing("postgres", 15432, "postgres", 5432, "postgresql") +
|
||||
outgoing("broker", 16379, "broker-gateway", 6379) +
|
||||
outgoing("s3", 19000, "s3-gateway", 9000) +
|
||||
outgoing("otel", 14318, "collector-gateway", 4318);
|
||||
// API gateways use the api client identity outbound, while their inbound server certificate SAN remains replica-specific.
|
||||
out["broker-gateway"] =
|
||||
global + incoming("broker", 6379, 16379, ["api", "worker", "operator"]);
|
||||
out["s3-gateway"] =
|
||||
global + incoming("s3", 9000, 19000, ["api", "worker", "operator"]);
|
||||
out["collector-gateway"] =
|
||||
global +
|
||||
incoming("otlp", 4318, 14318, ["api", "worker", "operator"]) +
|
||||
outgoing("openobserve", 15080, "openobserve-gateway", 5080);
|
||||
out["openobserve-gateway"] =
|
||||
global.replace(" maxconn 256", " maxconn 16\n tune.bufsize 131072") +
|
||||
incoming("ingest", 5080, 15080, ["collector", "operator"])
|
||||
.replace(" bind :5080", " mode http\n bind :5080")
|
||||
.replace(
|
||||
" server local",
|
||||
` acl collector ssl_c_s_dn(CN) -m str collector\n acl ingest path /api/default/v1/logs /api/default/v1/metrics /api/default/v1/traces\n acl post method POST\n http-request deny status 403 if collector !ingest\n http-request deny status 403 if collector !post\n server local`,
|
||||
) +
|
||||
incoming("query", 5082, 15080, ["grafana", "operator"])
|
||||
.replace(" bind :5082", " mode http\n bind :5082")
|
||||
.replace(" server local", openobserveQueryPolicy + " server local");
|
||||
out.grafana =
|
||||
global +
|
||||
incoming("grafana", 3443, 3000, [], true) +
|
||||
outgoing("openobserve", 15080, "openobserve-gateway", 5082);
|
||||
out.lb =
|
||||
global +
|
||||
`\nfrontend public\n mode http\n bind :8443 ssl crt /pki/server.pem\n http-response set-header Strict-Transport-Security max-age=86400\n default_backend apis\nbackend apis\n mode http\n balance roundrobin\n option httpchk\n http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost\n http-check expect status 200\n default-server inter 500ms fall 2 rise 2\n server api1 api1-gateway:8443 check ssl verify required ca-file /pki/ca.crt crt /pki/server.pem crl-file /pki/ca.crl verifyhost api1-gateway sni str(api1-gateway) resolvers docker init-addr none\n server api2 api2-gateway:8443 check ssl verify required ca-file /pki/ca.crt crt /pki/server.pem crl-file /pki/ca.crl verifyhost api2-gateway sni str(api2-gateway) resolvers docker init-addr none\n`;
|
||||
return out;
|
||||
}
|
||||
export function manifest() {
|
||||
const services: Record<string, any> = {};
|
||||
for (const name of [
|
||||
"lb",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"broker-gateway",
|
||||
"s3-gateway",
|
||||
"collector-gateway",
|
||||
"openobserve-gateway",
|
||||
"grafana",
|
||||
])
|
||||
services[name === "grafana" ? "grafana-gateway" : name] = gateway(name);
|
||||
services["worker-gateway"] = gateway("worker");
|
||||
services.lb.ports = ["127.0.0.1:${HTTPS_PORT:-18443}:8443"];
|
||||
services.lb.networks = ["private", "edge"];
|
||||
services["grafana-gateway"].ports = ["127.0.0.1:${GRAFANA_PORT:-18447}:3443"];
|
||||
services["grafana-gateway"].networks = ["private", "edge"];
|
||||
// Replica gateways need server SAN and a separate scoped outbound client identity.
|
||||
for (const role of ["api1-gateway", "api2-gateway"])
|
||||
services[role].volumes.push(ro("./.local/pki/api", "/client-pki"));
|
||||
services["collector-gateway"].volumes.push(
|
||||
ro("./.local/pki/collector", "/client-pki"),
|
||||
);
|
||||
services.postgres = {
|
||||
...base,
|
||||
image: images.postgres,
|
||||
pull_policy: "never",
|
||||
read_only: true,
|
||||
cap_drop: ["ALL"],
|
||||
cap_add: ["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETGID", "SETUID"],
|
||||
mem_limit: "512m",
|
||||
cpus: 1,
|
||||
networks: ["private"],
|
||||
environment: {
|
||||
POSTGRES_USER: "operator",
|
||||
POSTGRES_DB: "messenger",
|
||||
POSTGRES_PASSWORD_FILE: "/bootstrap/db-password",
|
||||
},
|
||||
volumes: [
|
||||
rw("./.local/data/postgres", "/var/lib/postgresql"),
|
||||
ro("./.local/pki/postgres", "/source-tls"),
|
||||
ro("./.local/operator/db-password", "/bootstrap/db-password"),
|
||||
ro("./config/pg_hba.conf", "/config/pg_hba.conf"),
|
||||
ro("./scripts/postgres-entrypoint.sh", "/config/entrypoint.sh"),
|
||||
],
|
||||
entrypoint: ["/bin/sh", "/config/entrypoint.sh"],
|
||||
tmpfs: [
|
||||
"/run/tls:size=1048576,mode=0755",
|
||||
"/var/run/postgresql:size=1048576,mode=0777",
|
||||
"/tmp:size=16777216,mode=1777",
|
||||
],
|
||||
healthcheck: {
|
||||
test: ["CMD-SHELL", "pg_isready -U operator -d messenger"],
|
||||
interval: "2s",
|
||||
timeout: "2s",
|
||||
retries: 30,
|
||||
},
|
||||
};
|
||||
services.broker = {
|
||||
...base,
|
||||
image: images.broker,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
network_mode: "service:broker-gateway",
|
||||
volumes: [
|
||||
rw("./.local/data/broker", "/data"),
|
||||
ro("./.local/config/valkey.conf", "/config/valkey.conf"),
|
||||
ro("./.local/config/users.acl", "/config/users.acl"),
|
||||
],
|
||||
command: ["valkey-server", "/config/valkey.conf"],
|
||||
mem_limit: "256m",
|
||||
};
|
||||
services.s3 = {
|
||||
...base,
|
||||
image: images.s3,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
network_mode: "service:s3-gateway",
|
||||
volumes: [
|
||||
rw("./.local/data/s3", "/data"),
|
||||
rw("./.local/data/s3-logs", "/logs"),
|
||||
ro("./.local/config/s3.env", "/config/s3.env"),
|
||||
ro("./scripts/s3-entrypoint.sh", "/config/entrypoint.sh"),
|
||||
],
|
||||
entrypoint: ["/bin/sh", "/config/entrypoint.sh"],
|
||||
mem_limit: "512m",
|
||||
cpus: 1,
|
||||
};
|
||||
services.openbao = {
|
||||
...base,
|
||||
image: images.bao,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
networks: ["private"],
|
||||
ports: ["127.0.0.1:${BAO_PORT:-18445}:8200"],
|
||||
volumes: [
|
||||
pki("openbao"),
|
||||
rw("./.local/data/bao", "/bao/data"),
|
||||
ro("./infra/openbao/server.hcl", "/bao/config/server.hcl"),
|
||||
],
|
||||
environment: {
|
||||
BAO_ADDR: "https://openbao:8200",
|
||||
BAO_CACERT: "/pki/ca.crt",
|
||||
SKIP_SETCAP: "true",
|
||||
},
|
||||
entrypoint: ["bao"],
|
||||
command: ["server", "-config=/bao/config/server.hcl"],
|
||||
mem_limit: "256m",
|
||||
healthcheck: {
|
||||
test: ["CMD", "bao", "status", "-format=json"],
|
||||
interval: "2s",
|
||||
timeout: "2s",
|
||||
retries: 30,
|
||||
},
|
||||
};
|
||||
for (const service of ["api1", "api2", "worker"]) {
|
||||
const role = service === "worker" ? "worker" : "api",
|
||||
gate = service === "worker" ? "worker-gateway" : service + "-gateway";
|
||||
services[service + "-agent"] = {
|
||||
...base,
|
||||
image: images.bao,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
network_mode: `service:${gate}`,
|
||||
volumes: [
|
||||
pki(role),
|
||||
ro(`./infra/openbao/${role}-agent.hcl`, "/config/agent.hcl"),
|
||||
rw(`./.local/rendered/${service}`, "/run/app"),
|
||||
],
|
||||
environment: { SKIP_SETCAP: "true" },
|
||||
entrypoint: ["bao"],
|
||||
command: ["agent", "-config=/config/agent.hcl"],
|
||||
depends_on: { openbao: { condition: "service_healthy" } },
|
||||
healthcheck: {
|
||||
test: [
|
||||
"CMD-SHELL",
|
||||
"test -s /run/app/database_url && test -s /run/app/cache_url && test -s /run/app/s3.json",
|
||||
],
|
||||
interval: "2s",
|
||||
timeout: "1s",
|
||||
retries: 30,
|
||||
},
|
||||
mem_limit: "96m",
|
||||
};
|
||||
services[service] = {
|
||||
...base,
|
||||
image: "mtuci-vp7-security-app:local",
|
||||
pull_policy: "never",
|
||||
build: { context: ".", dockerfile: "Dockerfile" },
|
||||
user: runUser,
|
||||
network_mode: `service:${gate}`,
|
||||
volumes: [ro(`./.local/rendered/${service}`, "/run/app")],
|
||||
environment: {
|
||||
APP_HOST: "127.0.0.1",
|
||||
APP_PORT: "8080",
|
||||
APP_ENV: "lab",
|
||||
DATABASE_URL_FILE: "/run/app/database_url",
|
||||
CACHE_URL_FILE: "/run/app/cache_url",
|
||||
S3_CONFIG_FILE: "/run/app/s3.json",
|
||||
SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}",
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:14318",
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf",
|
||||
OTEL_SERVICE_NAME:
|
||||
service === "worker" ? "messenger-worker" : "messenger-api",
|
||||
OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=lab",
|
||||
PG_MAX_CONNS: "4",
|
||||
WORKER_MAX_ATTEMPTS: "5",
|
||||
},
|
||||
depends_on: { [service + "-agent"]: { condition: "service_healthy" } },
|
||||
command: service === "worker" ? ["/worker"] : ["/app"],
|
||||
mem_limit: service === "worker" ? "2048m" : "256m",
|
||||
cpus: service === "worker" ? 1 : 0.5,
|
||||
stop_grace_period: "15s",
|
||||
};
|
||||
}
|
||||
for (const name of ["api1", "api2", "worker"]) {
|
||||
services[name].environment.SECRET_FRESHNESS_FILE = "/run/app/freshness";
|
||||
services[name].environment.SECRET_MAX_AGE_SECONDS = "120";
|
||||
services[name].environment.GOMEMLIMIT = "1536MiB";
|
||||
services[name].mem_limit = "2048m";
|
||||
}
|
||||
services.worker.environment.BROKER_PUBLISH_URL_FILE =
|
||||
"/run/app/publisher_url";
|
||||
for (const name of ["api1", "api2", "worker"])
|
||||
services[name + "-agent"].healthcheck.test = [
|
||||
"CMD-SHELL",
|
||||
"test -s /run/app/database_url && test -s /run/app/cache_url && test -s /run/app/s3.json && test -s /run/app/freshness" +
|
||||
(name === "worker" ? " && test -s /run/app/publisher_url" : ""),
|
||||
];
|
||||
services.collector = {
|
||||
...base,
|
||||
image: `${"${"}VP7_COLLECTOR_IMAGE:-${images.collector}}`,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
network_mode: "service:collector-gateway",
|
||||
volumes: [
|
||||
ro("./infra/otel/collector.yaml", "/etc/otelcol/config.yaml"),
|
||||
rw("./.local/data/collector", "/data"),
|
||||
ro(
|
||||
"./.local/config/openobserve_ingest_auth",
|
||||
"/run/secrets/openobserve_ingest_auth",
|
||||
),
|
||||
],
|
||||
command: ["--config=/etc/otelcol/config.yaml"],
|
||||
mem_limit: "256m",
|
||||
};
|
||||
services.openobserve = {
|
||||
...base,
|
||||
image: `${"${"}VP7_OPENOBSERVE_IMAGE:-${images.openobserve}}`,
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
network_mode: "service:openobserve-gateway",
|
||||
environment: {
|
||||
ZO_LOCAL_MODE: "true",
|
||||
ZO_LOCAL_MODE_STORAGE: "disk",
|
||||
ZO_DATA_DIR: "/data/",
|
||||
ZO_HTTP_ADDR: "127.0.0.1",
|
||||
ZO_HTTP_PORT: "15080",
|
||||
ZO_GRPC_ADDR: "127.0.0.1",
|
||||
ZO_TELEMETRY: "false",
|
||||
ZO_MEMORY_CACHE_ENABLED: "false",
|
||||
ZO_MEM_TABLE_MAX_SIZE: "128",
|
||||
ZO_MAX_FILE_SIZE_IN_MEMORY: "16",
|
||||
ZO_MEMORY_CACHE_DATAFUSION_MAX_SIZE: "256",
|
||||
ZO_QUERY_TIMEOUT: "8",
|
||||
ZO_HTTP_WORKER_NUM: "2",
|
||||
ZO_SERVICE_ACCOUNT_ENABLED: "true",
|
||||
},
|
||||
env_file: ["./.local/config/openobserve.env"],
|
||||
volumes: [rw("./.local/data/openobserve", "/data")],
|
||||
mem_limit: "1024m",
|
||||
cpus: 1,
|
||||
};
|
||||
services.grafana = {
|
||||
...base,
|
||||
image: "${VP7_GRAFANA_IMAGE:-" + images.grafana + "}",
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
network_mode: "service:grafana-gateway",
|
||||
environment: {
|
||||
GF_SERVER_HTTP_ADDR: "127.0.0.1",
|
||||
GF_SERVER_HTTP_PORT: "3000",
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "false",
|
||||
GF_USERS_ALLOW_SIGN_UP: "false",
|
||||
GF_SECURITY_ADMIN_USER: "operator",
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: "/run/admin/password",
|
||||
GF_SECURITY_SECRET_KEY__FILE: "/run/admin/secret-key",
|
||||
GF_SECURITY_COOKIE_SECURE: "true",
|
||||
GF_ANALYTICS_REPORTING_ENABLED: "false",
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: "false",
|
||||
GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false",
|
||||
GF_LOG_MODE: "console",
|
||||
GF_LOG_LEVEL: "warn",
|
||||
GF_DATAPROXY_TIMEOUT: "10",
|
||||
GF_DATAPROXY_RESPONSE_LIMIT: "8388608",
|
||||
GF_DATAPROXY_MAX_CONNS_PER_HOST: "8",
|
||||
GF_PLUGINS_ALLOW_LOADING_UNSIGNED_PLUGINS: "openobserve",
|
||||
GF_PLUGINS_PREINSTALL_DISABLED: "true",
|
||||
GF_PLUGINS_PUBLIC_KEY_RETRIEVAL_DISABLED: "true",
|
||||
},
|
||||
env_file: ["./.local/config/grafana-query.env"],
|
||||
volumes: [
|
||||
rw("./.local/data/grafana", "/var/lib/grafana"),
|
||||
ro("./.local/operator/grafana-password", "/run/admin/password"),
|
||||
ro("./.local/operator/grafana-secret-key", "/run/admin/secret-key"),
|
||||
ro("./infra/grafana/provisioning", "/etc/grafana/provisioning"),
|
||||
ro("./infra/grafana/dashboards", "/var/lib/grafana/dashboards"),
|
||||
ro("./.local/plugins", "/var/lib/grafana/plugins"),
|
||||
],
|
||||
mem_limit: "256m",
|
||||
};
|
||||
services.migrate = {
|
||||
...base,
|
||||
image: "mtuci-vp7-security-app:local",
|
||||
pull_policy: "never",
|
||||
user: runUser,
|
||||
profiles: ["tools"],
|
||||
networks: ["private"],
|
||||
volumes: [
|
||||
pki("operator"),
|
||||
ro("./.local/operator/migration-url", "/run/operator/database_url"),
|
||||
],
|
||||
environment: { DATABASE_URL_FILE: "/run/operator/database_url" },
|
||||
command: ["/app", "-migrate"],
|
||||
restart: "no",
|
||||
mem_limit: "256m",
|
||||
};
|
||||
services.openbao.networks = ["private", "edge"];
|
||||
return {
|
||||
name: "mtuci-vp7-security",
|
||||
services,
|
||||
networks: { private: { internal: true }, edge: { internal: false } },
|
||||
};
|
||||
}
|
||||
export async function writeTopology() {
|
||||
await mkdir(resolve(root, "config"), { recursive: true });
|
||||
for (const [name, config] of Object.entries(gatewayConfigs())) {
|
||||
let value = config;
|
||||
if (["api1-gateway", "api2-gateway", "collector-gateway"].includes(name))
|
||||
value = value.replaceAll(
|
||||
"crt /pki/server.pem crl-file",
|
||||
"crt /client-pki/server.pem crl-file",
|
||||
);
|
||||
await writeFile(resolve(root, "config", name + ".cfg"), value);
|
||||
}
|
||||
await writeFile(
|
||||
resolve(root, "compose.yaml"),
|
||||
JSON.stringify(manifest(), null, 2) + "\n",
|
||||
);
|
||||
}
|
||||
if (import.meta.main) await writeTopology();
|
||||
@@ -0,0 +1,44 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, compose, safeFailure } from "./runtime";
|
||||
try {
|
||||
const results = [];
|
||||
for (const service of [
|
||||
"lb",
|
||||
"api1-gateway",
|
||||
"api2-gateway",
|
||||
"worker-gateway",
|
||||
"broker-gateway",
|
||||
"s3-gateway",
|
||||
"collector-gateway",
|
||||
"openobserve-gateway",
|
||||
"grafana-gateway",
|
||||
]) {
|
||||
const result = await compose([
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
service,
|
||||
"haproxy",
|
||||
"-c",
|
||||
"-f",
|
||||
"/usr/local/etc/haproxy/haproxy.cfg",
|
||||
]);
|
||||
results.push({ service, exit: result.code });
|
||||
}
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/gateway-parser.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
native: "HAProxy3.2.26 cached pinned digest",
|
||||
scope: "configuration parser only, not upstream/runtime acceptance",
|
||||
results,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log("PASS_NATIVE_PARSER_ALL_CURRENT_GATEWAYS");
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, run, requireThat, safeFailure } from "./runtime";
|
||||
try {
|
||||
const evidenceDirectory = resolve(
|
||||
root,
|
||||
Bun.argv.includes("--grafana")
|
||||
? "evidence/grafana/source"
|
||||
: Bun.argv.includes("--openobserve")
|
||||
? "evidence/openobserve/source"
|
||||
: "evidence/security",
|
||||
);
|
||||
await mkdir(evidenceDirectory, { recursive: true });
|
||||
const checks = [
|
||||
["typecheck", ["run", "check"]],
|
||||
["unit", ["run", "test:unit"]],
|
||||
["format", ["run", "format:check"]],
|
||||
] as const;
|
||||
const results = await Promise.all(
|
||||
checks.map(async ([name, args]) => {
|
||||
const result = await run([process.execPath, ...args], {
|
||||
allowFailure: true,
|
||||
});
|
||||
await writeFile(
|
||||
resolve(evidenceDirectory, "source-" + name + ".txt"),
|
||||
result.out + result.err,
|
||||
);
|
||||
console.log(JSON.stringify({ check: name, exit: result.code }));
|
||||
return { check: name, exit: result.code };
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
resolve(evidenceDirectory, "source-checks.json"),
|
||||
JSON.stringify({ results }, null, 2) + "\n",
|
||||
);
|
||||
requireThat(
|
||||
results.every((result) => result.exit === 0),
|
||||
"SOURCE_CHECKS_FAILED",
|
||||
);
|
||||
} catch (error) {
|
||||
safeFailure(error);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
export function workerACL(password: string) {
|
||||
const hash = createHash("sha256").update(password).digest("hex");
|
||||
return `user worker on #${hash} ~attachment-jobs &* -@all +ping +hello +client|setinfo +xgroup|create +xreadgroup +xautoclaim +xack +xdel +xlen +xinfo|stream +xpending`;
|
||||
}
|
||||
export function publisherACL(password: string) {
|
||||
const hash = createHash("sha256").update(password).digest("hex");
|
||||
return `user publisher on #${hash} ~attachment-jobs &* -@all +ping +hello +client|setinfo +xadd`;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { root, local, run, requireThat, safeFailure } from "./runtime";
|
||||
import { writeTopology } from "./topology";
|
||||
try {
|
||||
await mkdir(local, { recursive: true, mode: 0o700 });
|
||||
await writeTopology();
|
||||
await import("./generate-agent-configs");
|
||||
const tests = await run(
|
||||
[
|
||||
process.execPath,
|
||||
"test",
|
||||
"student-tests/security-guards.test.ts",
|
||||
"student-tests/pki.test.ts",
|
||||
],
|
||||
{ allowFailure: true },
|
||||
);
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/offline-tests.txt"),
|
||||
tests.out + tests.err,
|
||||
);
|
||||
requireThat(tests.code === 0, "OFFLINE_TESTS_FAILED");
|
||||
const evidence = JSON.parse(
|
||||
await readFile(resolve(root, "evidence/security/red-green.json"), "utf8"),
|
||||
);
|
||||
evidence.green = { exit_code: tests.code, output: "offline-tests.txt" };
|
||||
await writeFile(
|
||||
resolve(root, "evidence/security/red-green.json"),
|
||||
JSON.stringify(evidence, null, 2) + "\n",
|
||||
);
|
||||
console.log("PASS_OFFLINE_GUARDS_AND_REAL_OPENSSL_PKI");
|
||||
} catch (e) {
|
||||
safeFailure(e);
|
||||
}
|
||||
Reference in New Issue
Block a user