Files
mtusi2026lab7/student-tests/http.ts

134 lines
4.0 KiB
TypeScript

import { readFile, mkdir, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { local, requireThat } from "../scripts/runtime";
export function syntheticUserIdentity(label: string, nonce: string) {
return {
username: "s7_" + nonce.replaceAll("-", "").slice(0, 24),
display_name: label,
};
}
type HTTPOutcome = {
method: string;
path: string;
expected: number;
status: number;
content_type: string;
body_base64: string;
};
export async function assertHTTPStatus(
outcome: HTTPOutcome,
retain: (value: HTTPOutcome) => Promise<void>,
) {
if (outcome.status !== outcome.expected)
await Promise.allSettled([Promise.resolve().then(() => retain(outcome))]);
requireThat(
outcome.status === outcome.expected,
"HTTP_" +
outcome.method +
"_" +
outcome.expected +
"_GOT_" +
outcome.status,
);
}
export class HTTP {
readonly base = "https://localhost:18443";
async call(
method: string,
path: string,
expected: number,
options: {
actor?: string;
body?: unknown;
raw?: Uint8Array;
headers?: Record<string, string>;
} = {},
) {
const headers: Record<string, string> = { ...options.headers };
if (options.actor) headers.Authorization = "Bearer " + options.actor;
let body: string | Uint8Array<ArrayBuffer> | undefined = options.raw
? new Uint8Array(options.raw)
: undefined;
if (options.body !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(options.body);
}
const response = await fetch(this.base + path, {
method,
headers,
body,
redirect: "error",
tls: {
ca: await readFile(resolve(local, "pki/lb/ca.crt"), "utf8"),
rejectUnauthorized: true,
},
signal: AbortSignal.timeout(10_000),
});
const bytes = new Uint8Array(await response.arrayBuffer());
await assertHTTPStatus(
{
method,
path,
expected,
status: response.status,
content_type: response.headers.get("content-type") ?? "",
body_base64: Buffer.from(bytes).toString("base64"),
},
async (outcome) => {
const directory = resolve(local, "diagnostics");
await mkdir(directory, { recursive: true, mode: 0o700 });
await writeFile(
resolve(directory, "http-failure-" + crypto.randomUUID() + ".json"),
JSON.stringify(outcome),
{ flag: "wx", mode: 0o600 },
);
},
);
requireThat(
bytes.length <= 16 * 1024 * 1024,
"HTTP_TEST_RESPONSE_TOO_LARGE",
);
let json: any;
try {
json = bytes.length ? JSON.parse(new TextDecoder().decode(bytes)) : null;
} catch {}
return { status: response.status, headers: response.headers, bytes, json };
}
async user(label: string) {
const password = "Synthetic-" + crypto.randomUUID(),
identity = syntheticUserIdentity(label, crypto.randomUUID()),
username = identity.username;
const registered = await this.call("POST", "/api/v1/users", 201, {
body: { ...identity, password },
});
const session = await this.call("POST", "/api/v1/auth/sessions", 201, {
headers: {
Authorization:
"Basic " + Buffer.from(username + ":" + password).toString("base64"),
},
});
requireThat(
session.json.user.id === registered.json.id,
"HTTP_SESSION_ACTOR_MISMATCH",
);
return {
id: registered.json.id,
token: session.json.token,
password,
username,
};
}
async ready(actor: string, id: string, budget = 60_000) {
const deadline = Date.now() + budget;
while (Date.now() < deadline) {
const result = await this.call("GET", "/api/v1/attachments/" + id, 200, {
actor,
});
requireThat(result.json.status !== "failed", "ATTACHMENT_FAILED");
if (result.json.status === "ready") return result.json;
await Bun.sleep(250);
}
throw new Error("ATTACHMENT_READY_TIMEOUT");
}
}