forked from mtusi2026/mtusi2026lab7
Prepare verified laboratory 7 implementation and evidence
This commit is contained in:
@@ -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 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user