forked from mtusi2026/mtusi2026lab7
59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
export type ReplicaService = "api1" | "api2";
|
|
export type ReplicaBaseline = Record<
|
|
ReplicaService,
|
|
{ container: string; alias: string }
|
|
>;
|
|
export type FailoverProof = {
|
|
operation_id: string;
|
|
attempt_id: string;
|
|
service: ReplicaService;
|
|
target_alias: string;
|
|
container: string;
|
|
before_running: boolean;
|
|
running: boolean;
|
|
volumes_removed: boolean;
|
|
};
|
|
export function failoverReceiptPath(operation: string, attempt: string) {
|
|
if (
|
|
![operation, attempt].every((x) =>
|
|
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(x),
|
|
)
|
|
)
|
|
throw Error("FAILOVER_OPERATION_INVALID");
|
|
return "evidence/security/failover-" + operation + "-" + attempt + ".json";
|
|
}
|
|
export function createFailoverReader(ports: {
|
|
read: (path: string) => Promise<unknown>;
|
|
}) {
|
|
if (typeof ports?.read !== "function")
|
|
throw Error("FAILOVER_READ_PORT_REQUIRED");
|
|
return async (
|
|
operation: string,
|
|
attempt: string,
|
|
baseline: ReplicaBaseline,
|
|
) => {
|
|
const path = failoverReceiptPath(operation, attempt),
|
|
raw = await ports.read(path);
|
|
if (!raw || typeof raw !== "object") throw Error("FAILOVER_PROOF_INVALID");
|
|
const proof = raw as FailoverProof;
|
|
if (proof.operation_id !== operation || proof.attempt_id !== attempt)
|
|
throw Error("FAILOVER_WRONG_OPERATION");
|
|
if (proof.service !== "api1" && proof.service !== "api2")
|
|
throw Error("FAILOVER_SERVICE_INVALID");
|
|
const expected = baseline[proof.service];
|
|
if (
|
|
!expected ||
|
|
proof.container !== expected.container ||
|
|
proof.target_alias !== expected.alias
|
|
)
|
|
throw Error("FAILOVER_TARGET_MISMATCH");
|
|
if (
|
|
proof.before_running !== true ||
|
|
proof.running !== false ||
|
|
proof.volumes_removed !== false
|
|
)
|
|
throw Error("FAILOVER_STOP_NOT_PROVED");
|
|
return { path, proof };
|
|
};
|
|
}
|