forked from mtusi2026/mtusi2026lab3
Prepare verified laboratory 3 implementation and evidence
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import { mkdir, writeFile, chmod, access } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const root = resolve(import.meta.dir, '..');
|
||||
const local = resolve(root, '.local');
|
||||
const files = ['pg_password', 'database_url', 'cache_url', 'valkey.conf'];
|
||||
const present = await Promise.all(files.map(async name => {try {await access(resolve(local, name));return true;} catch {return false;}}));
|
||||
if (present.some(Boolean)) {
|
||||
if (!present.every(Boolean)) throw new Error('Incomplete local configuration; preserve it and investigate before bootstrap');
|
||||
console.log('Local configuration exists');
|
||||
} else {
|
||||
await mkdir(local, { recursive: true, mode: 0o700 });
|
||||
const pg = crypto.randomUUID().replaceAll('-', '') + crypto.randomUUID().replaceAll('-', '');
|
||||
const cache = crypto.randomUUID().replaceAll('-', '');
|
||||
const values = [pg, `postgres://messenger:${pg}@postgres:5432/messenger?sslmode=disable`, `redis://:${cache}@valkey:6379/0`, `bind 0.0.0.0\nprotected-mode yes\nrequirepass ${cache}\nappendonly yes\nappendfsync always\ndir /data\n`];
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const destination = resolve(local, files[i]);
|
||||
await writeFile(destination, values[i] + '\n', { mode: 0o600, flag: 'wx' });
|
||||
await chmod(destination, 0o644); // Compose secrets must be readable by nonroot containers; parent is 0700.
|
||||
}
|
||||
console.log('Created local synthetic stand credentials');
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
exec docker compose --project-directory "$ROOT" -f "$ROOT/compose.yaml" -p vp-lab3-medvedev "$@"
|
||||
@@ -0,0 +1,166 @@
|
||||
export function settings(
|
||||
lab: number,
|
||||
env: Record<string, string | undefined> = {},
|
||||
) {
|
||||
if (lab !== 3 && lab !== 4)
|
||||
throw new Error("Only labs3 and4 use this runtime");
|
||||
const cluster = env.VP_CLUSTER ?? `vp-lab${lab}-medvedev`,
|
||||
port = Number(env.PUBLIC_PORT ?? 28200 + lab);
|
||||
if (!new RegExp(`^vp-lab${lab}-(medvedev|r-[a-f0-9]{8})$`).test(cluster))
|
||||
throw new Error("Unapproved cluster name");
|
||||
if (!Number.isInteger(port) || port < 1024 || port > 65535)
|
||||
throw new Error("Invalid public port");
|
||||
return { lab, cluster, port, namespace: "messenger" };
|
||||
}
|
||||
export function assertOwned(receipt: any, actual: any, expected: any): void {
|
||||
if (
|
||||
!receipt ||
|
||||
receipt.lab !== expected.lab ||
|
||||
receipt.cluster !== expected.cluster ||
|
||||
!receipt.container ||
|
||||
receipt.container !== actual.container ||
|
||||
!receipt.namespaceUID ||
|
||||
receipt.namespaceUID !== actual.namespaceUID
|
||||
)
|
||||
throw new Error("Cluster or namespace ownership guard failed");
|
||||
}
|
||||
export function guardedOperator(
|
||||
expected: any,
|
||||
ports: {
|
||||
receipt: () => Promise<any>;
|
||||
actual: () => Promise<any>;
|
||||
dispatch: (action: string) => Promise<any>;
|
||||
},
|
||||
) {
|
||||
return {
|
||||
async run(action: string) {
|
||||
const [receipt, actual] = await Promise.all([
|
||||
ports.receipt(),
|
||||
ports.actual(),
|
||||
]);
|
||||
assertOwned(receipt, actual, expected);
|
||||
return ports.dispatch(action);
|
||||
},
|
||||
};
|
||||
}
|
||||
export function pinnedConfigID(image: any, source: string): string {
|
||||
const [tagged, digest] = source.split("@");
|
||||
const repository = tagged.replace(/:[^/:]+$/, "");
|
||||
if (
|
||||
!digest ||
|
||||
!image?.Id ||
|
||||
!image.RepoDigests?.some(
|
||||
(ref: string) =>
|
||||
ref.replace(/^docker\.io\//, "").replace(/^library\//, "") ===
|
||||
repository + "@" + digest,
|
||||
)
|
||||
)
|
||||
throw new Error("Pinned manifest identity differs");
|
||||
return image.Id;
|
||||
}
|
||||
export function assertScopedArgs(args: string[]): void {
|
||||
const end = args.indexOf("--"),
|
||||
flags = end < 0 ? args : args.slice(0, end);
|
||||
if (end >= 0 && args[0] !== "exec")
|
||||
throw new Error("Only exec accepts an application command delimiter");
|
||||
if (
|
||||
flags.some((x) =>
|
||||
/^(-A$|-n|-s|--(?:all-namespaces|namespace|context|kubeconfig|server|token|user|cluster|as|as-group|raw)(?:=|$))/.test(
|
||||
x,
|
||||
),
|
||||
)
|
||||
)
|
||||
throw new Error("Target override rejected");
|
||||
const allowed =
|
||||
/^(pods?|deployments?|deploy|jobs?|services?|svc|persistentvolumeclaims?|pvc|configmaps?|events?)(\/[^,]+)?$/;
|
||||
if (
|
||||
![
|
||||
"get",
|
||||
"exec",
|
||||
"logs",
|
||||
"rollout",
|
||||
"scale",
|
||||
"annotate",
|
||||
"wait",
|
||||
"top",
|
||||
].includes(args[0])
|
||||
)
|
||||
throw new Error("Unsupported scoped verb");
|
||||
const resource =
|
||||
args[0] === "rollout"
|
||||
? args[2]
|
||||
: ["wait", "exec"].includes(args[0])
|
||||
? flags.find((x) => allowed.test(x))
|
||||
: args[1];
|
||||
if (!resource || !resource.split(",").every((x) => allowed.test(x)))
|
||||
throw new Error("Only approved namespaced resources are supported");
|
||||
if (
|
||||
flags.some(
|
||||
(x) =>
|
||||
(!x.startsWith("-") && x.includes("/") && !allowed.test(x)) ||
|
||||
/^(?:-f|--filename|-k|--kustomize)(?:=|$)/.test(x),
|
||||
)
|
||||
)
|
||||
throw new Error("Additional resource override rejected");
|
||||
}
|
||||
export function assertNoGame(code: number) {
|
||||
if (code !== 1)
|
||||
throw new Error(
|
||||
"Measurement requires an inactive game with confirmed status",
|
||||
);
|
||||
}
|
||||
export function assertPartialClaim(receipt: any, server: any, expected: any) {
|
||||
if (
|
||||
receipt?.state !== "claimed" ||
|
||||
receipt.lab !== expected.lab ||
|
||||
receipt.cluster !== expected.cluster ||
|
||||
!receipt.nonce ||
|
||||
server.owner !== receipt.nonce ||
|
||||
!server.container ||
|
||||
(receipt.container && receipt.container !== server.container)
|
||||
)
|
||||
throw new Error("Partial cluster claim differs");
|
||||
}
|
||||
export function assertNoRunningContainers(
|
||||
containers: any[],
|
||||
podUID: string,
|
||||
): void {
|
||||
if (containers.some((c) => c.labels?.["io.kubernetes.pod.uid"] === podUID))
|
||||
throw new Error("A victim Pod process is still running");
|
||||
}
|
||||
export async function withCleanup<T>(ports: {
|
||||
perform: () => Promise<T>;
|
||||
cleanup: () => Promise<void>;
|
||||
}): Promise<T> {
|
||||
let result!: T;
|
||||
let failure: unknown;
|
||||
let failed = false;
|
||||
try {
|
||||
result = await ports.perform();
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
failed = true;
|
||||
}
|
||||
try {
|
||||
await ports.cleanup();
|
||||
} catch (error) {
|
||||
if (failed)
|
||||
throw new AggregateError(
|
||||
[failure, error],
|
||||
(failure instanceof Error ? failure.message : "Operation failed") +
|
||||
"; cleanup failed",
|
||||
{ cause: failure },
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
if (failed) throw failure;
|
||||
return result;
|
||||
}
|
||||
export function assertImageBudget(
|
||||
lab: number,
|
||||
mib: number,
|
||||
soft: string,
|
||||
): void {
|
||||
if (lab === 4 && (mib !== 2048 || soft !== "1536MiB"))
|
||||
throw new Error("Lab4 requires its verified 2Gi/1536MiB decoder budget");
|
||||
}
|
||||
+1179
File diff suppressed because it is too large
Load Diff
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
exec bun --no-env-file scripts/k3s.ts kubectl "$@"
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
if [ "${VP_RUNTIME:-k3s}" = k3s ]; then exec bun --no-env-file scripts/k3s.ts restart; fi
|
||||
mkdir -p evidence
|
||||
ids=(); while IFS= read -r id; do ids+=("$id"); done < <(./scripts/compose.sh ps -q postgres valkey api)
|
||||
test "${#ids[@]}" -ge 4
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.StartedAt}}' "${ids[@]}" >evidence/restart-before.txt
|
||||
./scripts/compose.sh restart postgres valkey api lb
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.StartedAt}}' "${ids[@]}" >evidence/restart-after.txt
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
if [ "${VP_RUNTIME:-k3s}" = k3s ]; then exec bun --no-env-file scripts/k3s.ts stop-one; fi
|
||||
: "${TARGET_INSTANCE_ID:?public resilience test must provide target instance}"
|
||||
[[ "$TARGET_INSTANCE_ID" =~ ^[a-zA-Z0-9._-]+$ ]]
|
||||
ids=(); while IFS= read -r id; do ids+=("$id"); done < <(./scripts/compose.sh ps -q api)
|
||||
test "${#ids[@]}" -ge 2
|
||||
for id in "${ids[@]}"; do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
mkdir -p evidence
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.Running}}' "$id" >evidence/stop-one-before.txt
|
||||
docker stop --time 8 "$id" >/dev/null
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.Running}}' "$id" >evidence/stop-one-after.txt
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo 'Target is not a running replica in this Compose project' >&2
|
||||
exit 1
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
exec bun --no-env-file scripts/k3s.ts up
|
||||
Reference in New Issue
Block a user