Files
mtusi2026lab7/student-tests/grafana-response-boundary.ts

326 lines
8.9 KiB
TypeScript

import { createServer } from "node:net";
import { gzipSync } from "node:zlib";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { createHash } from "node:crypto";
import { root, local, run, requireThat, safeFailure } from "../scripts/runtime";
import { containerID } from "../scripts/runtime-inspect";
async function main() {
requireThat(
root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115",
"RESPONSE_FIXTURE_REMOTE_REQUIRED",
);
const claim = crypto.randomUUID(),
dir = resolve(local, "response-framing-" + claim);
await mkdir(dir, { mode: 0o700 });
const receipt = resolve(
root,
"evidence/grafana/response-framing-" + claim + ".json",
);
await writeFile(
receipt,
JSON.stringify({ state: "RUNNING", stage: "SOURCE_GUARD" }),
{ flag: "wx", mode: 0o600 },
);
const sourcePath = resolve(root, "config/openobserve-gateway.cfg"),
source = await readFile(sourcePath, "utf8");
const info = JSON.parse(
(await run(["docker", "inspect", await containerID("openobserve-gateway")]))
.out,
)[0];
requireThat(
info.Config.Labels["com.docker.compose.project"] === "mtuci-vp7-security" &&
info.Config.Labels["com.docker.compose.service"] ===
"openobserve-gateway",
"RESPONSE_FIXTURE_IMAGE_OWNER_INVALID",
);
const cfg = source
.replace("bind :5080 ssl", "bind 127.0.0.1:29577 ssl")
.replace("bind :5082 ssl", "bind 127.0.0.1:29578 ssl")
.replaceAll(
"server local 127.0.0.1:15080",
"server synthetic 127.0.0.1:29579",
);
requireThat(
cfg !== source &&
!cfg.includes("server local") &&
cfg.includes("bind 127.0.0.1:29578 ssl"),
"RESPONSE_FIXTURE_UPSTREAM_NOT_ISOLATED",
);
const cfgPath = resolve(dir, "fixture.cfg");
await writeFile(cfgPath, cfg, { flag: "wx", mode: 0o600 });
const sized = (n: number) => Buffer.from('{"v":"' + "x".repeat(n - 8) + '"}'),
small = Buffer.from('{"ok":true}'),
cap = 8388608;
requireThat(
sized(cap).length === cap,
"RESPONSE_FIXTURE_BYTE_ORACLE_INVALID",
);
const cases = [
{
name: "small",
body: small,
headers: ["Content-Length: " + small.length],
status: 200,
},
{
name: "exact_cap",
body: sized(cap),
headers: ["Content-Length: " + cap],
status: 200,
},
{
name: "cap_plus_one",
body: sized(cap + 1),
headers: ["Content-Length: " + (cap + 1)],
status: 502,
},
{
name: "gzip",
body: gzipSync(small),
headers: [
"Content-Length: " + gzipSync(small).length,
"Content-Encoding: gzip",
],
status: 502,
},
{
name: "identity_encoding",
body: small,
headers: [
"Content-Length: " + small.length,
"Content-Encoding: identity",
],
status: 502,
},
{
name: "chunked",
body: Buffer.from(
small.length.toString(16) + "\r\n" + small + "\r\n0\r\n\r\n",
),
headers: ["Transfer-Encoding: chunked"],
status: 502,
},
{ name: "eof", body: small, headers: [], status: 502 },
{
name: "duplicate_equal_normalized",
body: small,
headers: [
"Content-Length: " + small.length,
"Content-Length: " + small.length,
],
status: 200,
},
{
name: "leading_zero_normalized",
body: small,
headers: ["Content-Length: 000" + small.length],
status: 200,
},
];
const upstream: { name: string; identity_encoding: boolean }[] = [];
const server = createServer((socket) => {
let input = "";
socket.on("error", () => {});
socket.on("data", (data) => {
input += data.toString();
if (!input.includes("\r\n\r\n")) return;
socket.removeAllListeners("data");
const name = /fixture=([a-z_]+)/.exec(input)?.[1],
c = cases.find((c) => c.name === name) ?? cases[0];
upstream.push({
name: c.name,
identity_encoding: /\r\naccept-encoding:\s*identity\r\n/i.test(input),
});
socket.end(
Buffer.concat([
Buffer.from(
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/json\r\n" +
c.headers.join("\r\n") +
"\r\n\r\n",
),
c.body,
]),
);
});
});
await new Promise<void>((ok, fail) => {
server.once("error", fail);
server.listen(29579, "127.0.0.1", ok);
});
let id = "",
primary: unknown,
stop: number | null = null;
const results = [];
try {
const common = [
"docker",
"run",
"--pull=never",
"--network",
"host",
"--read-only",
"--cap-drop",
"ALL",
"--user",
`${process.getuid!()}:${process.getgid!()}`,
"--label",
"mtuci.vp7.response-claim=" + claim,
"--volume",
cfgPath + ":/fixture.cfg:ro",
"--volume",
resolve(local, "pki/openobserve-gateway") + ":/pki:ro",
"--entrypoint",
"haproxy",
];
await run([...common, info.Image, "-c", "-f", "/fixture.cfg"]);
id = (
await run([
...common.slice(0, 2),
"--detach",
...common.slice(2),
info.Image,
"-W",
"-db",
"-f",
"/fixture.cfg",
])
).out.trim();
requireThat(/^[a-f0-9]{64}$/.test(id), "RESPONSE_FIXTURE_ID_MISSING");
const request = async (name: string) => {
const path = resolve(dir, name + "-" + crypto.randomUUID() + ".body");
await writeFile(path, "", { flag: "wx", mode: 0o600 });
const result = await run(
[
"curl",
"--silent",
"--show-error",
"--noproxy",
"*",
"--max-time",
"10",
"--cacert",
resolve(local, "pki/grafana/ca.crt"),
"--cert",
resolve(local, "pki/grafana/cert.pem"),
"--key",
resolve(local, "pki/grafana/key.pem"),
"--resolve",
"openobserve-gateway:29578:127.0.0.1",
"--header",
"Accept-Encoding: gzip",
"--output",
path,
"--write-out",
"%{http_code}",
"https://openobserve-gateway:29578/api/default/streams?fixture=" +
name,
],
{ allowFailure: true },
);
return {
code: result.code,
status: Number(result.out),
body: await readFile(path),
};
};
let ready = false;
for (let attempt = 0; attempt < 30; attempt++) {
const r = await request("small");
if (r.status === 200) {
ready = true;
break;
}
await Bun.sleep(100);
}
requireThat(ready, "RESPONSE_FIXTURE_NOT_READY");
for (const c of cases) {
const response = await request(c.name),
marker =
response.body.toString() === '{"error":"query_response_boundary"}';
const pass =
response.code === 0 &&
response.status === c.status &&
response.body.length <= cap &&
(c.status !== 200 || response.body.equals(c.body)) &&
upstream
.filter((r) => r.name === c.name)
.every((r) => r.identity_encoding);
results.push({
name: c.name,
status: response.status,
bytes: response.body.length,
marker,
pass,
});
}
requireThat(
(await readFile(sourcePath, "utf8")) === source,
"RESPONSE_FIXTURE_SOURCE_CHANGED",
);
requireThat(
results.every((r) => r.pass),
"RESPONSE_FRAMING_NATIVE_FAILED",
);
} catch (error) {
primary = error;
} finally {
try {
if (id) {
const current = JSON.parse(
(await run(["docker", "inspect", id])).out,
)[0];
requireThat(
current.Id === id &&
current.Image === info.Image &&
current.Config.Labels["mtuci.vp7.response-claim"] === claim,
"RESPONSE_FIXTURE_STOP_OWNER_MISMATCH",
);
stop = (
await run(["docker", "stop", "--time", "3", id], {
allowFailure: true,
})
).code;
}
} catch (error) {
primary ??= error;
}
server.close();
try {
await writeFile(
receipt,
JSON.stringify(
{
state:
!primary && stop === 0
? "PASS_NATIVE_MTLS_RESPONSE_FRAMING_8MIB"
: "FAILED",
config_sha256: createHash("sha256").update(source).digest("hex"),
image: info.Image,
results,
upstream,
stop_exit: stop,
producer_started: false,
native_bao: false,
},
null,
2,
) + "\n",
);
} catch (error) {
primary ??= error;
}
}
console.log("RESPONSE_FRAMING_RECEIPT " + receipt);
if (primary) throw primary;
requireThat(stop === 0, "RESPONSE_FIXTURE_STOP_FAILED");
}
if (import.meta.main) {
try {
await main();
} catch (error) {
safeFailure(error);
}
}