import { mkdir, readFile, writeFile } from "node:fs/promises"; import { resolve } from "node:path"; import { createHash } from "node:crypto"; import { root, local, run, compose, requireThat, privateWrite, } from "../scripts/runtime"; import { createSharedLoginCase, type Replica, } from "../scripts/shared-login-case"; import { snapshotReplicas } from "../scripts/hooks"; import { containerIP } from "../scripts/runtime-inspect"; import { encrypt } from "../scripts/operator-crypto"; import { HTTP, syntheticUserIdentity } from "./http"; export async function sharedLoginRuntime( password: string, operationId: string, ) { requireThat(/^[a-f0-9-]{36}$/.test(operationId), "LOGIN_OPERATION_INVALID"); const directory = resolve( local, "operator", "login-functional-" + operationId, ); await mkdir(directory, { mode: 0o700 }); const bucket = (username: string) => createHash("sha256").update(username).digest().readUInt16BE(0) % 4096; const readBucket = async (value: number) => JSON.parse( ( await compose([ "exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-U", "operator", "-d", "messenger", "-c", `SELECT json_build_object('bucket',bucket,'attempts',attempts,'expired',started_at<=clock_timestamp()-interval '60 seconds') FROM login_limits WHERE bucket=${value}`, ]) ).out, ); const selectIdentity = async (excluded: number | null) => { for (let i = 0; i < 16; i++) { const identity = syntheticUserIdentity( "Bounded shared login", crypto.randomUUID(), ), value = bucket(identity.username), state = await readBucket(value); if ( value !== excluded && (state.expired === true || state.attempts === 0) ) return { ...identity, bucket: value, password: "Functional-" + crypto.randomUUID(), id: "", }; } throw Error("LOGIN_UNUSED_BUCKET_UNAVAILABLE"); }; const main = await selectIdentity(null), control = await selectIdentity(main.bucket), http = new HTTP(); const save = () => privateWrite( resolve(directory, "identities.enc"), encrypt({ main, control }, password), ); await save(); for (const identity of [main, control]) { const r = await http.call("POST", "/api/v1/users", 201, { body: { username: identity.username, display_name: identity.display_name, password: identity.password, }, }); requireThat( typeof r.json?.id === "string" && /^[a-f0-9-]{36}$/.test(r.json.id), "LOGIN_REGISTERED_USER_INVALID", ); identity.id = r.json.id; await save(); } const baseline = await snapshotReplicas(), ips = { api1: await containerIP("api1-gateway"), api2: await containerIP("api2-gateway"), }; const headers = { main: resolve(directory, "main.headers"), control: resolve(directory, "control.headers"), }; for (const [kind, identity] of [ ["main", main], ["control", control], ] as const) await privateWrite( headers[kind], "Authorization: Basic " + Buffer.from(identity.username + ":" + identity.password).toString( "base64", ) + "\n", ); let counter = 0; const observations: { replica: Replica; status: number; instance: string; retry_after: string | null; }[] = []; const result = await createSharedLoginCase({ now: Date.now, request: async (replica, kind) => { const index = counter++, bodyPath = resolve(directory, "response-" + index + ".json"), headerPath = resolve(directory, "response-" + index + ".headers"); await privateWrite(bodyPath, ""); await privateWrite(headerPath, ""); const hostname = replica + "-gateway", response = await run([ "curl", "--silent", "--show-error", "--noproxy", "*", "--max-time", "5", "--max-filesize", "65536", "--cacert", resolve(local, "pki/lb/ca.crt"), "--cert", resolve(local, "pki/lb/cert.pem"), "--key", resolve(local, "pki/lb/key.pem"), "--resolve", hostname + ":8443:" + ips[replica], "--header", "@" + headers[kind], "--request", "POST", "--dump-header", headerPath, "--output", bodyPath, "--write-out", "%{http_code}", "https://" + hostname + ":8443/api/v1/auth/sessions", ]); requireThat(/^\d{3}$/.test(response.out), "LOGIN_HTTP_STATUS_INVALID"); const status = Number(response.out), raw = await readFile(bodyPath), lines = (await readFile(headerPath, "utf8")).split(/\r?\n/); requireThat(raw.length <= 65536, "LOGIN_HTTP_BODY_TOO_LARGE"); const get = (name: string) => { const matches = lines.filter((line) => line.toLowerCase().startsWith(name + ":"), ); requireThat(matches.length <= 1, "LOGIN_DUPLICATE_RESPONSE_HEADER"); return matches[0]?.slice(name.length + 1).trim() ?? null; }; requireThat( get("content-type")?.startsWith("application/json"), "LOGIN_HTTP_CONTENT_TYPE_INVALID", ); const body = JSON.parse(raw.toString()), alias = get("x-instance-id") ?? "", retryAfter = get("retry-after"), identity = kind === "main" ? main : control; observations.push({ replica, status, instance: alias, retry_after: retryAfter, }); return { status, alias, retryAfter, actorCorrect: body.user?.id === identity.id, errorCode: typeof body.error?.code === "string" ? body.error.code : null, }; }, })({ api1: baseline.api1.alias, api2: baseline.api2.alias }); const after = await snapshotReplicas(); requireThat( JSON.stringify(after) === JSON.stringify(baseline), "LOGIN_REPLICA_CHANGED", ); const persistedMain = await readBucket(main.bucket), persistedControl = await readBucket(control.bucket); requireThat( persistedMain.attempts === 10 && persistedMain.expired === false && persistedControl.attempts === 2 && persistedControl.expired === false, "LOGIN_NATIVE_COUNTER_MISMATCH", ); const path = "evidence/security/shared-login-" + operationId + ".json"; await writeFile( resolve(root, path), JSON.stringify( { state: "PASS_SHARED_HTTP_LOGIN_LIMIT", operation_id: operationId, ...result, observations, replicas: baseline, main_bucket: { bucket: main.bucket, attempts: persistedMain.attempts }, control_bucket: { bucket: control.bucket, attempts: persistedControl.attempts, }, max_inflight: 2, request_budget: 22, full_service_dos_measured: false, kdf_budget_reference: "ARGON-BUDGET.md", credentials: "encrypted private operator capture; response files private", }, null, 2, ) + "\n", { flag: "wx", mode: 0o644 }, ); console.log( "PASS_SHARED_HTTP_10_OF_20_LIMIT_BOTH_REPLICAS_RETRY_AFTER_AND_CONTROLS", ); return path; }