Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Own server: updates check the image, keep the bot box passing, and record each step

milind-soni35699fc75786
diff --git a/connector/e2e/run.sh b/connector/e2e/run.sh
index c12d7ebef7..ffa7d00a66 100644
--- a/connector/e2e/run.sh
+++ b/connector/e2e/run.sh
@@ -2,7 +2,8 @@
# The connector end to end on a stock Ubuntu 24.04 host with Docker and AppArmor on, installed as a person installs it:
# a fake Admin (connector/test/fake-admin.ts) mints a one-time code; install.sh checks the host, installs the profiles,
# starts the connector and enrols; then start (the box passes every check), update to another digest, an unclean kill
-# started again, an update forced to fail rolled back (image and data), and uninstall keeping the data.
+# started again, an update forced to fail rolled back (image and data), a job from root on the server, the audit log of
+# all of it, and uninstall keeping the data and the log.
# Nothing reaches a production service: the home's connected-apps broker points at a closed loopback port and its
# HighLevel relay is off; the Admin is the fake one on loopback.
# OUT=<evidence folder> bash connector/e2e/run.sh
@@ -171,6 +172,23 @@ docker logs mausbot-connector >"$OUT/connector.log" 2>&1
if grep -qF "$SECRET" "$OUT/connector.log"; then fail "the bootstrap secret reached the connector's log"; fi
if grep -q "ombs_" "$OUT/connector.log"; then fail "the agent token reached the connector's log"; fi
+step "the audit log: every job, its steps and its result, each line linked to the one before, nothing secret"
+local_status=$(docker exec mausbot-connector mausbot-connector job status '{}')
+expect '.ok and .result.home.state == "running"' "$local_status" "a job from root on this server"
+expect '.ok == false and .error.code == "unknown_job"' "$(docker exec mausbot-connector mausbot-connector job shell '{}' || true)" "a job outside the list"
+[ "$(sudo stat -c %a /var/log/mausbot/audit.jsonl)" = 600 ] || fail "the audit log is not root's alone"
+sudo cat /var/log/mausbot/audit.jsonl >"$OUT/audit.jsonl"
+docker exec mausbot-connector mausbot-connector audit --verify | tee "$OUT/audit-verify.txt"
+grep -q "each linked to the one before it" "$OUT/audit-verify.txt" || fail "the audit log's chain is broken"
+audit=$(jq -cs . "$OUT/audit.jsonl")
+expect 'any(.[]; .event == "job" and .by == "admin" and .id == "start-1" and (.args.env | index("OMB_CLOUD_BOOTSTRAP_SECRET")))' "$audit" "the start, with its environment's names"
+expect '[.[] | select(.id == "update-1" and .event == "step") | .step] == ["pull", "checked", "stop", "snapshot", "swap", "wait", "healthy"]' "$audit" "the update's steps"
+expect 'any(.[]; .event == "result" and .id == "update-1" and .ok)' "$audit" "the update's result"
+expect 'any(.[]; .event == "result" and .id == "update-2" and .error.code == "update_rolled_back")' "$audit" "the rollback's result"
+expect 'any(.[]; .event == "step" and .id == "update-2" and .step == "rollback")' "$audit" "the rollback step"
+expect 'any(.[]; .event == "job" and .by == "local" and .type == "status")' "$audit" "the job from this server"
+if grep -qF "$SECRET" "$OUT/audit.jsonl"; then fail "the bootstrap secret reached the audit log"; fi
+
step "uninstall stops everything and keeps the data; --delete-data deletes it"
sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" uninstall | tee "$OUT/uninstall.txt"
for container in mausbot-connector mausbot-home; do
@@ -179,7 +197,9 @@ done
[ ! -e /etc/apparmor.d/omb-home-narrow ] || fail "the AppArmor profile is still installed"
[ "$(docker run --rm -v mausbot-data:/data --entrypoint cat "$HOME_B" /data/e2e-marker)" = kept ] || fail "uninstall did not keep the data"
docker volume inspect mausbot-snapshot >/dev/null || fail "uninstall did not keep the safety copy"
+sudo test -s /var/log/mausbot/audit.jsonl || fail "uninstall did not keep the audit log"
sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" uninstall --delete-data | tee -a "$OUT/uninstall.txt"
if docker volume inspect mausbot-data >/dev/null 2>&1; then fail "--delete-data kept the data"; fi
+if sudo test -e /var/log/mausbot; then fail "--delete-data kept the audit log"; fi
step "all passed"
diff --git a/connector/src/home.ts b/connector/src/home.ts
index 1c61ebe1ef..d1236619b0 100644
--- a/connector/src/home.ts
+++ b/connector/src/home.ts
@@ -6,6 +6,7 @@ import { rmSync } from "node:fs";
import { DockerError, type ContainerSpec, type Docker, type Mount } from "./docker.ts";
import { JobFailure } from "./failure.ts";
import { publicHost, summarizeHealth, type HealthRead } from "./home-health.ts";
+import { digestPinnedOnly, type ImageCheck } from "./images.ts";
import { errorText, registerSecret, type Log } from "./log.ts";
import { EXPORT_PATH, UPDATE_HEALTH_WINDOW_MS, type CopyInfo, type HomeHealth, type HomeReport, type HomeState, type JobError, type JobReply, type JobResults } from "./protocol.ts";
import {
@@ -83,6 +84,17 @@ function versionBelow(a: readonly number[], b: readonly number[]): boolean {
return false;
}
+/** How long an updated home's bot box has to finish its self-check once the home answers (it starts 5 s after boot). */
+const BOX_WINDOW_MS = 3 * 60_000;
+
+/** "passed" when the box ran its self-check and every check passed; "pending" until it has; otherwise what went wrong. */
+export function boxVerdict(box: HomeHealth["box"]): "passed" | "pending" | string {
+ if (!box) return "pending";
+ if (box.box !== "bwrap") return `its bot box is ${box.box ?? "unknown"}`;
+ if (box.checks === null) return "pending";
+ return box.failed.length ? `its bot box failed ${box.failed.join(", ")} (${box.checks})` : "passed";
+}
+
const lastLine = (text: string) => text.trim().split("\n").pop()?.slice(0, 300) ?? "";
const spoken = (ms: number) => (ms % 60_000 === 0 ? `${ms / 60_000} minutes` : `${Math.round(ms / 1000)} seconds`);
const gb = (bytes: number) => Math.round((bytes / 1e9) * 10) / 10;
@@ -97,6 +109,10 @@ export interface HomeOptions {
/** Free bytes where Docker keeps its volumes. */
diskFree: () => number;
transfer: Transfer;
+ /** Every image the home is to run, after it is pulled and before it runs. */
+ checkImage?: ImageCheck;
+ /** Each step of a job that changes the home or its data, as it begins: the audit log's `step` lines. */
+ onStep?: (step: { id: string; type: Operation["type"]; step: string; detail?: Record<string, unknown> }) => void;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
updateWindowMs?: number;
@@ -185,11 +201,13 @@ export class Home {
start(jobId: string, image: string, env: Record<string, string>): Promise<JobResults["start"]> {
return this.exclusive(async () => {
registerHomeSecrets(env);
- this.state.saveHomeEnv(env);
const record = this.state.home();
+ // Refused before anything is kept: the connector would otherwise start this image again on its own.
+ await this.ensureImage(image);
+ await this.checkImage(image, record.image);
+ this.state.saveHomeEnv(env);
this.state.saveHome({ ...record, desired: "running", image, operation: { jobId, type: "start", phase: "start", previousImage: record.image, nextImage: image, target: null, dataAtRisk: false, wasRunning: false, startedAt: this.now() } });
try {
- await this.ensureImage(image);
await this.ensureDataVolume();
await this.ensureContainer(image, env);
await this.startHome(image);
@@ -231,9 +249,13 @@ export class Home {
const { image: previous, env } = this.current();
const record = this.state.home();
const wasRunning = (await this.docker.containerInspect(NAMES.home))?.State.Running === true;
+ // The new version must keep a bot box that passed every check passing them: never a silent step down.
+ const boxBefore = wasRunning ? (await this.refreshHealth().catch(() => this.lastHealth))?.box ?? null : null;
+ const keepBox = boxVerdict(boxBefore) === "passed";
this.begin({ jobId, type: "update", phase: "pull", previousImage: previous, nextImage: image, target: null, dataAtRisk: false, wasRunning });
try {
await this.ensureImage(image);
+ await this.checkImage(image, previous);
await this.ensureRoomForCopy(previous);
} catch (error) {
this.finish({});
@@ -248,8 +270,9 @@ export class Home {
await this.createContainer(image, env);
await this.startHome(image);
this.phase({ phase: "wait" });
- const waited = await this.waitHealthy(image, this.updateWindowMs);
+ const waited = await this.waitHealthy(image, this.updateWindowMs, keepBox);
if (!waited.ok) failure = waited.reason;
+ else this.step("healthy", { box: this.lastHealth?.box?.checks ?? null });
} catch (error) {
failure = errorText(error);
}
@@ -466,11 +489,28 @@ export class Home {
private begin(op: Omit<Operation, "startedAt">): void {
this.state.saveHome({ ...this.state.home(), operation: { ...op, startedAt: this.now() } });
+ this.step(op.phase, op.nextImage ? { image: op.nextImage, from: op.previousImage } : undefined);
}
private phase(patch: Partial<Operation>): void {
const record = this.state.home();
- if (record.operation) this.state.saveHome({ ...record, operation: { ...record.operation, ...patch } });
+ if (!record.operation) return;
+ this.state.saveHome({ ...record, operation: { ...record.operation, ...patch } });
+ if (patch.phase && patch.phase !== record.operation.phase) this.step(patch.phase);
+ }
+
+ private step(step: string, detail?: Record<string, unknown>): void {
+ const op = this.state.home().operation;
+ if (op) this.options.onStep?.({ id: op.jobId, type: op.type, step, ...(detail ? { detail } : {}) });
+ }
+
+ private async checkImage(image: string, current: string | null): Promise<void> {
+ try {
+ await (this.options.checkImage ?? digestPinnedOnly)(image, { kind: "home", current });
+ } catch (error) {
+ throw new JobFailure("image_refused", `${image} was refused (${errorText(error)}). Nothing was changed.`);
+ }
+ this.step("checked", { image });
}
private finish(patch: Partial<HomeRecord>): void {
@@ -539,8 +579,10 @@ export class Home {
if (paths.length) this.log(`cleared the data-directory lease records a stopped home left: ${paths.join(", ")}`);
}
- private async waitHealthy(image: string, windowMs: number): Promise<Waited> {
- const deadline = this.now() + windowMs;
+ /** The home reports `image`, and with `box` its bot box has passed every check, within `windowMs` plus BOX_WINDOW_MS. */
+ private async waitHealthy(image: string, windowMs: number, box = false): Promise<Waited> {
+ let deadline = this.now() + windowMs;
+ let reported = false;
const env = this.state.homeEnv();
if (!env) return { ok: false, reason: "the home has no environment" };
for (;;) {
@@ -551,8 +593,19 @@ export class Home {
}
const { status, report } = await this.options.readHealth({ port: HOME_PORT, publicHost: publicHost(env), secret: env.OMB_CLOUD_BOOTSTRAP_SECRET });
this.lastHealth = summarizeHealth(status, report, image, this.now());
- if (this.lastHealth.ok) return { ok: true };
- if (this.now() >= deadline) return { ok: false, reason: `it did not report ${image} within ${spoken(windowMs)}` };
+ if (this.lastHealth.ok) {
+ if (!box) return { ok: true };
+ if (!reported) {
+ reported = true;
+ deadline = this.now() + BOX_WINDOW_MS;
+ }
+ const verdict = boxVerdict(this.lastHealth.box);
+ if (verdict === "passed") return { ok: true };
+ if (verdict !== "pending") return { ok: false, reason: verdict };
+ }
+ if (this.now() >= deadline) {
+ return { ok: false, reason: reported ? `its bot box did not finish its self-check within ${spoken(BOX_WINDOW_MS)}` : `it did not report ${image} within ${spoken(windowMs)}` };
+ }
await this.sleep(this.pollMs);
}
}
diff --git a/connector/src/images.ts b/connector/src/images.ts
new file mode 100644
index 0000000000..9c56f49fb8
--- /dev/null
+++ b/connector/src/images.ts
@@ -0,0 +1,7 @@
+// The last word on which image the home, or the connector itself, may run, after the protocol's rule (our registry,
+// pinned by digest). Images are not signed yet, so that pin is today's whole check; a signature check plugs in here.
+
+/** Throws, in plain words, to refuse `image`; nothing is changed then. `current` is the image running now, if any. */
+export type ImageCheck = (image: string, context: { kind: "home" | "connector"; current: string | null }) => Promise<void>;
+
+export const digestPinnedOnly: ImageCheck = async () => {};
diff --git a/connector/src/main.ts b/connector/src/main.ts
index 69e2d9293b..f913c5d945 100644
--- a/connector/src/main.ts
+++ b/connector/src/main.ts
@@ -120,6 +120,7 @@ async function run(): Promise<void> {
docker, state, log, readHealth, seccomp, transfer: httpTransfer,
diskFree: () => reader.disk().free,
updateWindowMs: envSeconds("MAUSBOT_UPDATE_WAIT_S", 600, 60, 3600) * 1000,
+ onStep: ({ id, type, step, detail }) => note({ event: "step", id, type, step, ...(detail ? { detail } : {}) }),
});
const updater = new SelfUpdater({ docker, state, log, instance, identity });
const heartbeat = async (): Promise<Heartbeat> => {
diff --git a/connector/src/protocol.ts b/connector/src/protocol.ts
index 1b20e84155..b11ec065ea 100644
--- a/connector/src/protocol.ts
+++ b/connector/src/protocol.ts
@@ -154,7 +154,7 @@ export interface JobResults {
}
export type JobErrorCode =
- | "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted" | "audit_unavailable" | "refused_by_policy"
+ | "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted" | "audit_unavailable" | "refused_by_policy" | "image_refused"
| "no_home" | "docker" | "pull_failed" | "unhealthy" | "update_rolled_back" | "rollback_failed"
| "not_found" | "disk_full" | "port_in_use" | "box_unavailable" | "transfer_failed" | "self_update_failed";
diff --git a/connector/src/self-update.ts b/connector/src/self-update.ts
index 894300883b..a2e3a220eb 100644
--- a/connector/src/self-update.ts
+++ b/connector/src/self-update.ts
@@ -5,6 +5,7 @@
import { randomUUID } from "node:crypto";
import type { ContainerInfo, ContainerSpec, Docker } from "./docker.ts";
+import { digestPinnedOnly, type ImageCheck } from "./images.ts";
import { errorText, type Log } from "./log.ts";
import type { ConnectorIdentity, Job, JobReply } from "./protocol.ts";
import { LABELS, NAMES } from "./settings.ts";
@@ -21,6 +22,8 @@ export interface SelfUpdateDeps {
/** This connector's MAUSBOT_INSTANCE, also its container's instance label. */
instance: string;
identity: () => ConnectorIdentity;
+ /** The connector's next image, once pulled and before it runs. */
+ checkImage?: ImageCheck;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
deadlineMs?: number;
@@ -82,6 +85,11 @@ export class SelfUpdater {
} catch (error) {
return this.fail(job, `Could not download ${image} (${errorText(error)}). The connector was not changed.`);
}
+ try {
+ await (this.deps.checkImage ?? digestPinnedOnly)(image, { kind: "connector", current: self.Config.Image });
+ } catch (error) {
+ return { id: job.id, ok: false, error: { code: "image_refused", message: `${image} was refused (${errorText(error)}). The connector was not changed.` } };
+ }
const instance = randomUUID();
const record: SelfUpdateRecord = {
jobId: job.id, from: self.Config.Image, to: image, previousContainer: self.Id, candidateContainer: NAMES.connectorNext,
diff --git a/connector/test/home.test.ts b/connector/test/home.test.ts
index cb55e0d802..7d5aff6bca 100644
--- a/connector/test/home.test.ts
+++ b/connector/test/home.test.ts
@@ -36,6 +36,10 @@ function fixture(options: { free?: number } = {}) {
docker.now = () => clock;
for (const [ref, version] of [[A, "v0.1.130"], [B, "v0.1.131"], [C, "v0.1.132"]] as const) docker.publish(ref, version);
const healthy = new Set<string>([A, B, C]);
+ /** What each image's bot box reports; every check passes unless a test says otherwise. */
+ const boxes = new Map<string, { box: string; checks: string | null; failed: string[] }>();
+ const steps: string[] = [];
+ const refused = new Set<string>();
const lines: string[] = [];
const readHealth: HealthRead = async (target) => {
const home = docker.container("mausbot-home");
@@ -44,7 +48,7 @@ function fixture(options: { free?: number } = {}) {
if (target.secret !== homeEnv.OMB_CLOUD_BOOTSTRAP_SECRET) return { status: 401, report: { error: "invalid_signature" } };
if (target.publicHost !== new URL(homeEnv.OMB_PUBLIC_URL).hostname || target.port !== 8080) return { status: 403, report: null };
if (!healthy.has(home.spec.Image)) return { status: 0, report: null };
- return { status: 200, report: { version: "0.1.130", image: homeEnv.OMB_CLOUD_IMAGE, box: { box: "bwrap", checks: "32/32", failed: [] } } };
+ return { status: 200, report: { version: "0.1.130", image: homeEnv.OMB_CLOUD_IMAGE, box: boxes.get(home.spec.Image) ?? { box: "bwrap", checks: "32/32", failed: [] } } };
};
const uploads: { url: string; headers: Record<string, string>; body: string }[] = [];
const downloads: { url: string; headers: Record<string, string> }[] = [];
@@ -67,11 +71,13 @@ function fixture(options: { free?: number } = {}) {
now: () => clock,
sleep: async (ms) => { clock += ms; },
updateWindowMs: 600_000, startWindowMs: 600_000, pollMs: 2_000,
+ checkImage: async (ref) => { if (refused.has(ref)) throw new Error("it is not signed by MausBot"); },
+ onStep: ({ id, step }) => steps.push(`${id} ${step}`),
});
const data = () => docker.files("mausbot-data");
const write = (path: string, content: string) => docker.volume("mausbot-data").files.set(path, content);
return {
- dir, state, docker, home, healthy, lines, uploads, downloads, data, write,
+ dir, state, docker, home, healthy, boxes, steps, refused, lines, uploads, downloads, data, write,
clock: () => clock,
advance: (ms: number) => { clock += ms; },
setArchive: (value: string) => { archive = value; },
@@ -265,6 +271,61 @@ describe("the home on an own server", () => {
expect(tight.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });
});
+ it("records each step of an update as it begins it", async () => {
+ const f = fixture();
+ await started(f);
+ f.steps.splice(0);
+ await f.home.update("update-1", B);
+ expect(f.steps).toEqual(["update-1 pull", "update-1 checked", "update-1 stop", "update-1 snapshot", "update-1 swap", "update-1 wait", "update-1 healthy"]);
+ f.steps.splice(0);
+ f.healthy.delete(C);
+ await failure(f.home.update("update-2", C));
+ expect(f.steps.at(-1)).toBe("update-2 rollback");
+ });
+
+ it("runs no image the image check refuses, and keeps nothing of it", async () => {
+ const f = fixture();
+ f.refused.add(A);
+ expect((await failure(f.home.start("start-1", A, env))).toJobError()).toEqual({
+ code: "image_refused", message: `${A} was refused (it is not signed by MausBot). Nothing was changed.`,
+ });
+ expect(f.state.home()).toMatchObject({ desired: "stopped", image: null, operation: null });
+ expect(f.state.homeEnv()).toBeNull();
+ await f.home.supervise();
+ expect(f.docker.container("mausbot-home")).toBeNull();
+ await started(f, B);
+ f.refused.add(C);
+ f.docker.calls.splice(0);
+ expect((await failure(f.home.update("update-1", C))).toJobError()).toMatchObject({ code: "image_refused" });
+ expect(f.docker.calls.filter((call) => /^(stop|rm|create) /.test(call))).toEqual([]);
+ expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: B } });
+ expect(f.state.home()).toMatchObject({ image: B, operation: null });
+ });
+
+ it("rolls back an update whose bot box no longer passes every check, or is off", async () => {
+ const f = fixture();
+ await started(f);
+ f.write("a.txt", "1");
+ f.boxes.set(B, { box: "bwrap", checks: "31/32", failed: ["server-pid-hidden"] });
+ expect((await failure(f.home.update("update-1", B))).toJobError()).toMatchObject({
+ code: "update_rolled_back", image: A,
+ message: "The new version did not become healthy (its bot box failed server-pid-hidden (31/32)). The previous version and its data are back.",
+ });
+ expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });
+ expect(f.data()).toEqual({ "a.txt": "1" });
+ f.boxes.set(B, { box: "off", checks: null, failed: [] });
+ expect((await failure(f.home.update("update-2", B))).message).toContain("(its bot box is off)");
+ // A self-check that never finishes is not a pass either.
+ f.boxes.set(B, { box: "bwrap", checks: null, failed: [] });
+ const began = f.clock();
+ expect((await failure(f.home.update("update-3", B))).message).toContain("(its bot box did not finish its self-check within 3 minutes)");
+ expect(f.clock() - began).toBeLessThan(600_000);
+ // A box that already failed before the update does not hold an update back: it may be the fix.
+ f.boxes.set(A, { box: "bwrap", checks: "31/32", failed: ["server-pid-hidden"] });
+ await f.home.refreshHealth();
+ expect((await f.home.update("update-4", B)).home).toMatchObject({ image: B });
+ });
+
it("keeps the newest three backups and restores one, taking a safety copy of the data first", async () => {
const f = fixture();
await started(f);
diff --git a/connector/test/self-update.test.ts b/connector/test/self-update.test.ts
index 54d15637e6..80aa05c224 100644
--- a/connector/test/self-update.test.ts
+++ b/connector/test/self-update.test.ts
@@ -57,6 +57,18 @@ async function fixture() {
}
describe("the connector replacing itself", () => {
+ it("never starts a new connector the image check refuses", async () => {
+ const f = await fixture();
+ const updater = new SelfUpdater({
+ docker: f.docker, state: f.state, log: () => {}, instance: "instance-old",
+ identity: () => ({ version: "1.0.0", protocol: 1, image: OLD }),
+ checkImage: async (image, context) => { if (image === NEW && context.kind === "connector" && context.current === OLD) throw new Error("it is older than this one"); },
+ });
+ expect(await updater.run(f.job, f.agent)).toEqual({ id: "self-1", ok: false, error: { code: "image_refused", message: `${NEW} was refused (it is older than this one). The connector was not changed.` } });
+ expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);
+ expect(f.agent).toMatchObject({ paused: 0, resumed: 0 });
+ });
+
it("hands over once the new connector has connected: it answers the job, removes the old one and takes its name", async () => {
const f = await fixture();
let candidateReply: JobReply | null = null;