Files
mtusi2026lab7/student-tests/replica-snapshot.test.ts

99 lines
2.9 KiB
TypeScript

import { expect, test } from "bun:test";
import {
createReplicaSnapshot,
type ReplicaState,
} from "../scripts/replica-snapshot";
const aliases = [
"33333333-3333-4333-8333-333333333333",
"44444444-4444-4444-8444-444444444444",
];
function fixture() {
const commands: string[][] = [],
reads: Record<string, number> = {};
const state = (service: string): ReplicaState => ({
id: (service === "api1" ? "a" : "b").repeat(64),
running: true,
project: "mtuci-vp7-security",
service,
started: "2026-11-16T11:00:00Z",
});
return {
commands,
reads,
state,
ports: {
inspect: async (service: "api1" | "api2") => {
reads[service] = (reads[service] ?? 0) + 1;
return state(service);
},
command: async (args: string[]) => {
commands.push(args);
if (args[1] === "cp") throw Error("DOCKER_CP_TMPFS_NOT_VISIBLE");
return aliases[args[2] === "a".repeat(64) ? 0 : 1];
},
},
};
}
test("read each current UUID through exec in the verified immutable container, without filesystem copy", async () => {
const f = fixture(),
actual = await createReplicaSnapshot(f.ports)();
expect(actual.api1).toEqual({ container: "a".repeat(64), alias: aliases[0] });
expect(f.commands).toEqual(
["a", "b"].map((c) => [
"docker",
"exec",
c.repeat(64),
"/bin/cat",
"/tmp/messenger-instance-id",
]),
);
});
test("reject process restart while reading the alias", async () => {
const f = fixture();
f.ports.inspect = async (service) => ({
...f.state(service),
started:
++f.reads[service] > 1 ? "2026-11-16T11:01:00Z" : "2026-11-16T11:00:00Z",
});
f.reads.api1 = 0;
await expect(createReplicaSnapshot(f.ports)()).rejects.toThrow(
"FAILOVER_REPLICA_CHANGED_DURING_READ",
);
});
test("reject malformed UUID before any stop operation", async () => {
const f = fixture();
f.ports.command = async () => "not-a-uuid";
await expect(createReplicaSnapshot(f.ports)()).rejects.toThrow(
"INVALID_REPLICA_ALIAS",
);
});
test("reject foreign ownership before any command", async () => {
const f = fixture();
f.ports.inspect = async (service) => ({
...f.state(service),
project: "foreign",
});
await expect(createReplicaSnapshot(f.ports)()).rejects.toThrow(
"FAILOVER_BASELINE_NOT_OWN_RUNNING_REPLICA",
);
expect(f.commands).toEqual([]);
});
test("propagate native exec failure without substituting a stale alias", async () => {
const f = fixture(),
error = Error("FIXTURE_EXEC_FAILURE");
f.ports.command = async () => {
throw error;
};
let actual;
try {
await createReplicaSnapshot(f.ports)();
} catch (e) {
actual = e;
}
expect(actual).toBe(error);
});
test("require explicit ports without process defaults", () =>
expect(() => createReplicaSnapshot({} as never)).toThrow(
"REPLICA_SNAPSHOT_PORTS_REQUIRED",
));