Skip to content

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

Customer-run: MausBot cannot replace the connector, roll the server back or restore

milind-soni560a6931a626
diff --git a/apps/docs/content/docs/self-hosting/connected-servers.mdx b/apps/docs/content/docs/self-hosting/connected-servers.mdx
index 66d4586af3..163cf77206 100644
--- a/apps/docs/content/docs/self-hosting/connected-servers.mdx
+++ b/apps/docs/content/docs/self-hosting/connected-servers.mdx
@@ -18,7 +18,7 @@ The whole list of what the Admin may run, ask and learn in this mode is one file
- It only calls out: one HTTPS request to enrol, then one WebSocket to the Admin. It opens no port.
- It makes its own Ed25519 key at enrolment. The private key stays on your server. It pins the Admin's signing keys.
- It runs with every Linux capability dropped, a read-only file system and no new privileges.
-- It is given Docker's socket, which is root on the server in the hands of any program. What the connector does with it is fixed in its code: it starts and stops the two containers of your install, runs one fixed read inside your server's container (below), runs short helper containers that copy your data folder to and from a Docker volume on the same server, and replaces itself. It never makes a second MausBot and never changes your `.env` or your Compose file.
+- It is given Docker's socket, which is root on the server in the hands of any program. What the connector does with it is fixed in its code: it starts and stops the two containers of your install, runs one fixed read inside your server's container (below), runs short helper containers that copy your data folder to and from a Docker volume on the same server, and replaces itself when you tell it to. It never makes a second MausBot and never changes your `.env` or your Compose file.
- The mode is chosen on your server when it enrols, kept in the connector's own state, and told to the Admin. The Admin cannot change it.
## It connects the server you installed
@@ -28,7 +28,7 @@ The connector attaches to the MausBot the [server installer](/docs/self-hosting/
- It attaches only to that layout: Docker Compose, the published image, the data in a folder beside the Compose file. A server built from source, or run without Docker, cannot be connected yet.
- A connector started the other way (the mode MausBot uses on servers it operates itself) refuses to enrol on a machine where your MausBot already runs, so there are never two.
-## What MausBot can do: nine jobs
+## What MausBot can do: seven jobs
Every job is signed by the Admin for your server alone and is refused 15 minutes after it was signed. A job of any other kind, or with any other argument, is refused on your server and the refusal is written to your log. There is no shell, no command the Admin chooses, and no reading of a file by its path.
@@ -37,16 +37,30 @@ Every job is signed by the Admin for your server alone and is refused 15 minutes
| `start`, `stop`, `restart` | Starts or stops your server's containers, with your settings. A `start` that names an image or a setting is refused |
| `update` | Hands one image, MausBot's server image pinned by digest, to your server's own updater: `update.sh` in `/opt/openmausbot`, the command you run by hand. It copies the data aside, starts the new version, checks it, and puts the old version and the copy back when the check fails |
| `status` | Reads the server's state, the two versions and the list of backups |
-| `backup` | Copies the data folder to a Docker volume on your server; three are kept |
-| `restore` | Puts one of those copies back, after a safety copy of what is there |
+| `backup` | Copies the data folder to a Docker volume on your server. MausBot's three newest are kept; a backup you made is never removed to make room |
| `host-health` | Reads the server's size, load and checks (below) |
-| `self-update` | Replaces the connector with a newer one from the same registry, pinned by digest |
Three things to know:
- **Not on the list, so refused:** `export-disk` (uploads an archive of the data to MausBot) and `import-disk` (replaces the data with an archive from elsewhere). They exist in the connector for servers MausBot operates itself.
+- **`update` only moves forward.** An image whose version is older than the one your server runs, or that names no version, is refused: once by the connector, and again by the updater's runner on your server, outside any container. MausBot cannot roll your server back to an earlier release. A second floor, the first release with the hardened profile, is **planned**: no release has that profile yet.
- **`update` needs your updater.** It works only when `update.sh` is in `/opt/openmausbot` and the connector's installer has set up the small systemd unit that runs it. Without either, the job is refused and nothing changes. A server installer that puts `update.sh` there is not released yet: **planned**.
-- **`self-update` can change these rules**, because a new connector is new code. The new image comes only from MausBot's registry and its source is public, but images are not signed yet. To keep the connector you read, leave `self-update` out of your policy's job list (below).
+
+## What only you can do: two more jobs
+
+Two jobs exist on your server and are refused when MausBot sends them. Root on the server runs them:
+
+| Job | Why MausBot may not |
+|---|---|
+| `self-update` | It replaces the connector, and so every rule on this page. A connector from before this mode does not know the mode, so MausBot asking for one would undo it. You choose the connector; even then, one older than the one running, or one that names no version, is refused |
+| `restore` | It puts older data back over what is there, after a safety copy |
+
+```sh
+docker exec mausbot-connector mausbot-connector job self-update '{"image":"ghcr.io/milind-soni/mausbot-connector@sha256:…"}'
+docker exec mausbot-connector mausbot-connector job restore '{"backupId":"20261028-104512-3fa9"}'
+```
+
+Connector images are pinned by digest and come from MausBot's registry, but they are not signed yet. Checking a signature before a connector is replaced is **planned**. Going back to an older server version is also yours alone: `./update.sh --rollback` or `./update.sh --version` on the server.
Until your team's Owner accepts the server in MausBot, it answers only `status` and `host-health`.
@@ -80,14 +94,14 @@ People sign in to your server with your server's own sign-in: a pairing code you
docker exec mausbot-connector mausbot-connector audit --verify
```
-- **Pause.** One command makes the connector refuse every job and every request from MausBot, the connector's own update included, and log each one. The server keeps running, people keep signing in, and the heartbeat below still goes out, saying that you paused. A switch in Settings is **planned**.
+- **Pause.** One command makes the connector refuse every job and every request from MausBot, and log each one. The server keeps running, people keep signing in, and the heartbeat below still goes out, saying that you paused. A switch in Settings is **planned**.
```sh
docker exec mausbot-connector mausbot-connector pause
docker exec mausbot-connector mausbot-connector resume
```
-- **Your policy.** `/etc/mausbot/policy.json`, which only root on your server can write, narrows the nine jobs further and can hold updates. The connector reads it before every job and never writes it.
+- **Your policy.** `/etc/mausbot/policy.json`, which only root on your server can write, narrows the seven jobs further and can hold updates. The connector reads it before every job and never writes it.
```json
{ "jobs": ["status", "host-health", "update", "backup"], "updates": "hold" }
@@ -125,7 +139,8 @@ Traffic to the AI providers, engines and apps you set up is between your server
- A released server installer that puts `update.sh` in place, so `update` works without a manual step.
- Backups to storage of yours outside the server (a bucket). Today a backup is a Docker volume on the same server.
- A pause switch in Settings.
-- Signed connector images.
+- Signed connector images, checked on your server before a connector is replaced.
+- A floor under `update` at the first release with the hardened profile.
- Seats and plan features delivered to the server as a signed document. Today the seat count is only reported.
- Connecting a server built from source or run without Docker.
- A published list of the network addresses a connected server needs.
diff --git a/connector/host/mausbot-update-runner.sh b/connector/host/mausbot-update-runner.sh
index db02ebfefd..f186f22a9f 100755
--- a/connector/host/mausbot-update-runner.sh
+++ b/connector/host/mausbot-update-runner.sh
@@ -4,12 +4,16 @@
# update.sh in the install's folder, the same command its owner runs by hand, and writes down how that ended.
#
# The request is two lines, `id=<job id>` and `image=<image>`. The image must be MausBot's server image pinned by
-# digest; anything else is refused here, whatever the connector wrote. Nothing else in the request is read.
+# digest, and its version must not be older than the one running here or than FLOOR; anything else is refused here,
+# whatever the connector wrote. Nothing else in the request is read. To go back to an older version, run update.sh
+# yourself: that is yours to decide, never MausBot's.
set -u
DIR="${MAUSBOT_UPDATE_DIR:-/var/lib/mausbot/update}"
INSTALL_DIR="${MAUSBOT_INSTALL_DIR:-/opt/openmausbot}"
REQUEST="$DIR/request"
+FLOOR=0.0.0
+VERSION_LABEL=org.opencontainers.image.version
[ -f "$REQUEST" ] || exit 0
id=$(sed -n 's/^id=//p' "$REQUEST" | head -n 1)
@@ -29,6 +33,25 @@ if [ ! -f "$INSTALL_DIR/update.sh" ]; then
answer 127
exit 0
fi
+
+version_of() { # image → its released version as "1 2 3", or nothing
+ docker image inspect -f "{{index .Config.Labels \"$VERSION_LABEL\"}}" "$1" 2>/dev/null |
+ sed -n 's/^v\{0,1\}\([0-9]\{1,5\}\)\.\([0-9]\{1,5\}\)\.\([0-9]\{1,5\}\)$/\1 \2 \3/p'
+}
+older() { # "a b c" "x y z": true when the first is the older version
+ # shellcheck disable=SC2086
+ set -- $1 $2
+ [ "$1" -lt "$4" ] || { [ "$1" -eq "$4" ] && { [ "$2" -lt "$5" ] || { [ "$2" -eq "$5" ] && [ "$3" -lt "$6" ]; }; }; }
+}
+docker image inspect "$image" >/dev/null 2>&1 || docker pull -q "$image" >>"$DIR/runner.log" 2>&1 || { answer 4; exit 0; }
+wanted=$(version_of "$image")
+running=""
+container=$(docker ps -aq --filter label=com.docker.compose.project=openmausbot --filter label=com.docker.compose.service=omb 2>/dev/null | head -n 1)
+if [ -n "$container" ]; then running=$(version_of "$(docker inspect -f '{{.Image}}' "$container" 2>/dev/null)"); fi
+if [ -z "$wanted" ] || older "$wanted" "$(printf '%s' "$FLOOR" | tr . ' ')" || { [ -n "$running" ] && older "$wanted" "$running"; }; then
+ answer 5
+ exit 0
+fi
code=0
bash "$INSTALL_DIR/update.sh" --dir "$INSTALL_DIR" --image "$image" >>"$DIR/runner.log" 2>&1 || code=$?
answer "$code"
diff --git a/connector/install.sh b/connector/install.sh
index 3b25df2c26..c687f3e81f 100644
--- a/connector/install.sh
+++ b/connector/install.sh
@@ -397,6 +397,7 @@ install_connector() {
say "You run this server: MausBot can start, stop, update and back it up, and sees its versions, health and seat count."
say " What it was asked to do: sudo docker exec $CONNECTOR mausbot-connector audit"
say " Pause remote management: sudo docker exec $CONNECTOR mausbot-connector pause"
+ say "Only you can replace the connector or restore a backup: sudo docker exec $CONNECTOR mausbot-connector job <self-update|restore>"
return
fi
check_apparmor
diff --git a/connector/src/adopted-home.ts b/connector/src/adopted-home.ts
index e02a0a0081..054dd83803 100644
--- a/connector/src/adopted-home.ts
+++ b/connector/src/adopted-home.ts
@@ -6,7 +6,7 @@ import { randomBytes } from "node:crypto";
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { CUSTOMER_HOME_IMAGE, HOME_READS_COMMAND, parseHomeReads, type HomeFacts } from "./customer-run.ts";
+import { CUSTOMER_HOME_IMAGE, HOME_READS_COMMAND, VERSION_LABEL, olderVersionRefusal, parseHomeReads, type HomeFacts, type JobSource } from "./customer-run.ts";
import type { ContainerInfo, Docker, Mount } from "./docker.ts";
import { JobFailure } from "./failure.ts";
import { backupId, helperSpec } from "./home.ts";
@@ -27,8 +27,10 @@ const DELETE_CAPS = ["DAC_OVERRIDE", "DAC_READ_SEARCH"];
/** The request the connector leaves for the server's updater, and the answer it reads: `key=value` lines. */
export const UPDATE_FILES = { runner: "runner", request: "request", result: "result" } as const;
-/** deploy/update.sh's exit codes, and 127 when the server has no update.sh. */
-const UPDATE_EXIT = { done: 0, rolledBack: 1, rollbackFailed: 2, busy: 3, notStarted: 4, missing: 127 } as const;
+/** deploy/update.sh's exit codes; from the runner itself, 5 for an image older than the one running and 127 when the server has no update.sh. */
+const UPDATE_EXIT = { done: 0, rolledBack: 1, rollbackFailed: 2, busy: 3, notStarted: 4, older: 5, missing: 127 } as const;
+/** Who asked for a backup, kept on its volume: one sender's backups never push out the other's. */
+const MADE_BY_LABEL = "com.mausbot.by";
const lastLine = (text: string) => text.trim().split("\n").pop()?.slice(0, 300) ?? "";
const gb = (bytes: number) => Math.round((bytes / 1e9) * 10) / 10;
@@ -215,6 +217,7 @@ export class AdoptedHome {
if (!existsSync(join(dir, UPDATE_FILES.runner))) {
throw new JobFailure("update_unavailable", "This server has no updater for MausBot to hand an update to. Run the connector's install command again to add it; until then, update with ./update.sh on the server.");
}
+ await this.refuseOlder(image, container);
const wasRunning = container.State.Running;
this.begin({ jobId, type: "update", phase: "request", previousImage: previous, nextImage: image, target: null, dataAtRisk: false, wasRunning });
rmSync(join(dir, UPDATE_FILES.result), { force: true });
@@ -236,7 +239,7 @@ export class AdoptedHome {
});
}
- backup(jobId: string): Promise<JobResults["backup"]> {
+ backup(jobId: string, by: JobSource): Promise<JobResults["backup"]> {
return this.exclusive(async () => {
const { container, dataDir } = await this.install();
const helper = this.helperImage(container);
@@ -249,13 +252,14 @@ export class AdoptedHome {
try {
await this.takeDown();
this.phase({ phase: "copy" });
- await this.copy(helper, this.dataMount(dataDir, "/from", true), { Type: "volume", Source: target, Target: "/to" }, "backup", image);
+ await this.copy(helper, this.dataMount(dataDir, "/from", true), { Type: "volume", Source: target, Target: "/to" }, "backup", image, by);
} finally {
if (wasRunning) await this.bringUp().catch((error) => this.log(`could not start the home again: ${errorText(error)}`));
this.finish({});
}
const { backups } = await this.copies();
- for (const old of backups.slice(BACKUPS_KEPT)) await this.docker.removeVolume(`${NAMES.backupPrefix}${old.id}`);
+ const same = await this.backupsMadeBy(by);
+ for (const old of backups.filter((entry) => same.has(entry.id)).slice(BACKUPS_KEPT)) await this.docker.removeVolume(`${NAMES.backupPrefix}${old.id}`);
return { backup: backups.find((entry) => entry.id === id) ?? { id, kind: "backup", createdAt: this.now(), image } };
});
}
@@ -356,6 +360,26 @@ export class AdoptedHome {
}
}
+ /** Refused before anything is asked of the updater: the Admin may move the server forward, never back. */
+ private async refuseOlder(image: string, container: ContainerInfo): Promise<void> {
+ if (!(await this.docker.imageInspect(image))) {
+ try {
+ await this.docker.pull(image);
+ } catch (error) {
+ throw new JobFailure("pull_failed", `Could not download ${image} (${errorText(error)}). Nothing was changed.`);
+ }
+ }
+ const label = async (ref: string) => (await this.docker.imageInspect(ref).catch(() => null))?.Config?.Labels?.[VERSION_LABEL];
+ const refusal = olderVersionRefusal(await label(image), await label(container.Image ?? container.Config.Image));
+ if (refusal) throw new JobFailure("older_version", `${refusal} Nothing was changed. To go back to an older version, run ./update.sh on the server yourself.`);
+ }
+
+ /** The ids of the backups `by` asked for. A backup made before senders were recorded counts as the owner's. */
+ private async backupsMadeBy(by: JobSource): Promise<Set<string>> {
+ const volumes = await this.docker.listVolumes({ [LABELS.role]: "backup" });
+ return new Set(volumes.filter((volume) => (volume.Labels?.[MADE_BY_LABEL] ?? "local") === by).map((volume) => volume.Name.slice(NAMES.backupPrefix.length)));
+ }
+
private async container(service: string): Promise<ContainerInfo | null> {
const [found] = await this.docker.listContainers({ [PROJECT_LABEL]: COMPOSE_PROJECT, [SERVICE_LABEL]: service });
return found ? this.docker.containerInspect(found.Id) : null;
@@ -446,9 +470,9 @@ export class AdoptedHome {
if (free < needed) throw new JobFailure("disk_full", `There is not enough free disk for a copy of the data: it needs about ${gb(needed)} GB and ${gb(free)} GB are free. Free some space or add a disk.`);
}
- private async copy(helper: string, from: Mount, to: Mount, kind: "backup" | "snapshot", image: string | null): Promise<void> {
+ private async copy(helper: string, from: Mount, to: Mount, kind: "backup" | "snapshot", image: string | null, by?: JobSource): Promise<void> {
await this.docker.removeVolume(to.Source);
- await this.docker.createVolume(to.Source, { [LABELS.role]: kind, [LABELS.created]: String(this.now()), ...(image ? { [LABELS.image]: image } : {}) });
+ await this.docker.createVolume(to.Source, { [LABELS.role]: kind, [LABELS.created]: String(this.now()), ...(image ? { [LABELS.image]: image } : {}), ...(by ? { [MADE_BY_LABEL]: by } : {}) });
const copied = await this.helper(helper, [from, to], ["cp", "-a", "/from/.", "/to/"], COPY_CAPS);
if (copied.code !== 0) {
await this.docker.removeVolume(to.Source);
@@ -497,6 +521,7 @@ function updateFailure(code: number | null, previous: string | null): JobFailure
case UPDATE_EXIT.rollbackFailed: return new JobFailure("rollback_failed", `The update failed and the previous version did not come back healthy either. ${log}`, previous ?? undefined);
case UPDATE_EXIT.busy: return new JobFailure("busy", "Another update is already running on this server.");
case UPDATE_EXIT.notStarted: return new JobFailure("update_not_started", `The server's updater did not start the update, and nothing was changed. ${log}`);
+ case UPDATE_EXIT.older: return new JobFailure("older_version", "The server's updater refused the image: it is older than the version running, or names no version. Nothing was changed.");
case UPDATE_EXIT.missing: return new JobFailure("update_unavailable", "This server has no update.sh in its install folder, so MausBot cannot update it. Add deploy/update.sh there, or update by hand.");
case null: return new JobFailure("interrupted", "The server's updater did not answer in time. It finishes or undoes an update by itself; ask for the status to see which version runs.");
default: return new JobFailure("docker", `The server's updater stopped with code ${code}. ${log}`);
diff --git a/connector/src/agent.ts b/connector/src/agent.ts
index 9c2c23cfb2..5600b792f0 100644
--- a/connector/src/agent.ts
+++ b/connector/src/agent.ts
@@ -237,7 +237,8 @@ export class Agent {
const connection = this.connection;
if (!connection) return;
this.options.log(`dropping the connection to MausBot: ${why}`);
- try { connection.socket.close(code, why.slice(0, 120)); } catch { /* already closed */ }
+ // What went wrong here can name a path or quote Docker; a customer-run server sends the close code alone.
+ try { connection.socket.close(code, this.options.mode === "customer-run" ? "" : why.slice(0, 120)); } catch { /* already closed */ }
this.closed(code, why);
}
@@ -405,7 +406,7 @@ export class Agent {
const claimed = typeof opened.payload.job === "object" && opened.payload.job !== null ? opened.payload.job as { id?: unknown; type?: unknown } : {};
const id = typeof claimed.id === "string" ? claimed.id.slice(0, 64) : undefined;
if (!payload.ok) return this.refuse({ code: payload.code, message: payload.message, id, type: typeof claimed.type === "string" ? claimed.type.slice(0, 32) : undefined }, true);
- const checked = this.options.mode === "customer-run" ? checkCustomerRunJob(payload.job) : checkJob(payload.job);
+ const checked = this.options.mode === "customer-run" ? checkCustomerRunJob(payload.job, "admin") : checkJob(payload.job);
if (!checked.ok) {
if (checked.code === "refused_by_mode") this.refuse({ code: checked.code, message: checked.message, id: checked.id ?? undefined, type: typeof claimed.type === "string" ? claimed.type.slice(0, 32) : undefined }, true);
else if (checked.id) this.reply({ id: checked.id, ok: false, error: { code: checked.code, message: checked.message } });
diff --git a/connector/src/customer-run.ts b/connector/src/customer-run.ts
index ef2c7e78ce..af5f2b0370 100644
--- a/connector/src/customer-run.ts
+++ b/connector/src/customer-run.ts
@@ -5,42 +5,84 @@
// Security invariant: nothing in this file passes through text a person wrote. Every string that leaves is either a
// constant below, an enumerated code, or matches one of the patterns below (a version, an image reference, an id).
import {
- checkJob, type CheckId, type ConnectorIdentity, type CopyInfo, type Heartbeat, type HomeReport, type HomeState, type HostHealth,
+ checkJob, type CheckId, type ConnectorIdentity, type CopyInfo, type Heartbeat, type HomeReport, type HostFacts, type HomeState, type HostHealth,
type Job, type JobError, type JobErrorCode, type JobReply, type JobType,
} from "./protocol.ts";
// 1. JOBS. The only kinds the Admin may run. Not here, so refused: `export-disk` (uploads the data to MausBot) and
// `import-disk` (replaces the data with an archive from elsewhere).
-export const CUSTOMER_RUN_JOBS = ["start", "stop", "restart", "update", "self-update", "status", "host-health", "backup", "restore"] as const satisfies readonly JobType[];
+export const CUSTOMER_RUN_JOBS = ["start", "stop", "restart", "update", "status", "host-health", "backup"] as const satisfies readonly JobType[];
+
+/**
+ * Kinds only root on the server may run (`mausbot-connector job <kind>`), never the Admin:
+ * - `self-update` replaces the connector, and with it every rule in this file. An older connector does not know this
+ * mode at all, so the Admin asking for one would undo the mode. The owner replaces the connector, or nobody does.
+ * - `restore` puts older data back over what is there.
+ */
+export const CUSTOMER_RUN_LOCAL_JOBS = ["self-update", "restore"] as const satisfies readonly JobType[];
/**
* What each job may carry.
* - `start`, `stop`, `restart`: nothing. They start and stop the server its owner installed, with the owner's settings;
* a `start` that names an image or settings is refused.
- * - `update`: the image to move to, MausBot's own server image pinned by digest. The server's own updater does it.
- * - `self-update`: the connector's next image, pinned by digest.
- * - `backup`: nothing. Copies the data to a Docker volume on this server. `restore`: the id of one of those copies.
+ * - `update`: the image to move to, MausBot's own server image pinned by digest, and never an older version than the
+ * one running (below). The server's own updater does it.
+ * - `backup`: nothing. Copies the data to a Docker volume on this server; it never removes a copy the owner made.
* - `status`, `host-health`: nothing. They read.
*/
export const CUSTOMER_HOME_IMAGE = /^ghcr\.io\/milind-soni\/openmausbot@sha256:[0-9a-f]{64}$/;
-const isCustomerRunJob = (type: unknown): type is (typeof CUSTOMER_RUN_JOBS)[number] => (CUSTOMER_RUN_JOBS as readonly unknown[]).includes(type);
+/** Who sent a job: the Admin over the connection, or root on this server. */
+export type JobSource = "admin" | "local";
+
+const allowed = (type: unknown, by: JobSource): boolean =>
+ (CUSTOMER_RUN_JOBS as readonly unknown[]).includes(type) || (by === "local" && (CUSTOMER_RUN_LOCAL_JOBS as readonly unknown[]).includes(type));
+
+/** Why this server refuses a job of `type` sent by `by`, or null when the kind is on that sender's list. */
+export function customerRunRefusal(type: string, by: JobSource): string | null {
+ if (allowed(type, by)) return null;
+ if (allowed(type, "local")) return `This server is run by its owner, and only they may run ${type} here: sudo docker exec mausbot-connector mausbot-connector job ${type}`;
+ return `This server is run by its owner, and ${JSON.stringify(type.slice(0, 32))} is not a job that may run on it.`;
+}
+
+/**
+ * An `update` never moves the server to an older version than the one it runs, and never below this one. Checked on
+ * the image's own version label, once in the connector and again by the updater's runner on the server, which is the
+ * one that counts. The owner goes back with `./update.sh --rollback` or `--version` on the server, never the Admin.
+ * Raise this to the first release that carries the hardened profile when that release exists.
+ */
+export const SERVER_VERSION_FLOOR = "0.0.0";
+export const VERSION_LABEL = "org.opencontainers.image.version";
+
+/** "v0.1.130" → [0, 1, 130]; null for anything that is not a released version. */
+export function releasedVersion(label: unknown): [number, number, number] | null {
+ const match = typeof label === "string" ? /^v?(\d{1,5})\.(\d{1,5})\.(\d{1,5})$/.exec(label) : null;
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
+}
+
+const older = (a: readonly number[], b: readonly number[]) => a[0] !== b[0] ? a[0]! < b[0]! : a[1] !== b[1] ? a[1]! < b[1]! : a[2]! < b[2]!;
-/** Why this server refuses a job of `type`, or null when the kind is on the list. */
-export function customerRunRefusal(type: string): string | null {
- return isCustomerRunJob(type) ? null : `This server is run by its owner, and ${JSON.stringify(type.slice(0, 32))} is not a job MausBot may run on it.`;
+/** Why an image labelled `next` may not replace one labelled `current`, or null. An image that names no version is refused. */
+export function olderVersionRefusal(next: unknown, current: unknown, floor: string = SERVER_VERSION_FLOOR): string | null {
+ const wanted = releasedVersion(next);
+ if (!wanted) return "The image does not say which version it is.";
+ const least = releasedVersion(floor);
+ if (least && older(wanted, least)) return `Version ${wanted.join(".")} is older than ${least.join(".")}, the oldest this server accepts.`;
+ const running = releasedVersion(current);
+ if (running && older(wanted, running)) return `Version ${wanted.join(".")} is older than ${running.join(".")}, which runs here.`;
+ return null;
}
type CheckedJob = { ok: true; job: Job } | { ok: false; id: string | null; code: "invalid_job" | "unknown_job" | "invalid_args" | "refused_by_mode"; message: string };
/** A whole job message for a customer-run server: a listed kind with exactly that kind's arguments. */
-export function checkCustomerRunJob(message: unknown): CheckedJob {
+export function checkCustomerRunJob(message: unknown, by: JobSource): CheckedJob {
const fields = typeof message === "object" && message !== null && !Array.isArray(message) ? message as Record<string, unknown> : {};
const { id, type } = fields;
- if (typeof type === "string" && !isCustomerRunJob(type)) {
+ if (typeof type === "string" && !allowed(type, by)) {
const known = typeof id === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(id) ? id : null;
- return { ok: false, id: known, code: "refused_by_mode", message: customerRunRefusal(type)! };
+ return { ok: false, id: known, code: "refused_by_mode", message: customerRunRefusal(type, by)! };
}
if (type !== "start" && type !== "update") return checkJob(message);
const args = fields.args === undefined ? {} : fields.args;
@@ -150,12 +192,18 @@ const machine = (value: unknown) => (typeof value === "string" && MACHINE.test(v
const count = (value: unknown, max = 1e15) => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max ? value : 0);
const seatsOrNull = (value: unknown) => (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1_000_000 ? value : null);
+/** The server's facts as they leave it, at enrolment and in every heartbeat. */
+export function reducedFacts(host: HostFacts): HostFacts {
+ return {
+ os: machine(host.os), kernel: machine(host.kernel), arch: machine(host.arch), cpus: count(host.cpus), memMb: count(host.memMb), diskGb: count(host.diskGb),
+ docker: machine(host.docker), apparmor: host.apparmor === true, userns: host.userns === true,
+ };
+}
+
function reducedHost(host: HostHealth): HostHealth {
return {
- os: machine(host.os), kernel: machine(host.kernel), arch: machine(host.arch), docker: machine(host.docker),
- cpus: count(host.cpus), memMb: count(host.memMb), diskGb: count(host.diskGb), diskTotalGb: count(host.diskTotalGb), memAvailableMb: count(host.memAvailableMb),
- load1: count(host.load1), uptimeS: count(host.uptimeS),
- apparmor: host.apparmor === true, userns: host.userns === true,
+ ...reducedFacts(host),
+ diskTotalGb: count(host.diskTotalGb), memAvailableMb: count(host.memAvailableMb), load1: count(host.load1), uptimeS: count(host.uptimeS),
clockSkewS: typeof host.clockSkewS === "number" && Number.isFinite(host.clockSkewS) ? host.clockSkewS : null,
// The check's id and verdict. The sentence that tells the owner how to fix it stays on the server (`probe`).
checks: (host.checks ?? []).filter((check) => CHECK_IDS.includes(check.id)).map((check) => ({ id: check.id, ok: check.ok === true, ...(check.warning ? { warning: true } : {}) })),
@@ -206,6 +254,7 @@ const FAILURES: Record<JobErrorCode, string> = {
rollback_failed: "The update failed and the previous version did not come back healthy either.",
update_unavailable: "The server's own updater is not installed, so MausBot cannot update it.",
update_not_started: "The server's own updater did not start the update. Nothing was changed.",
+ older_version: "The image is older than the version the server runs, or names no version. Nothing was changed.",
not_found: "There is no such backup on this server.",
disk_full: "There is not enough free disk on the server for a safety copy of the data.",
port_in_use: "A port the server needs is used by another program.",
diff --git a/connector/src/enroll.ts b/connector/src/enroll.ts
index dbb8bacc6a..ce20246593 100644
--- a/connector/src/enroll.ts
+++ b/connector/src/enroll.ts
@@ -1,6 +1,7 @@
// Trades the one-time code for this server's place in the team: a key made here, whose public half the Admin keeps, and
// the Admin's own keys, which the connector pins. Once, over HTTPS.
import { errorText } from "./log.ts";
+import { reducedFacts } from "./customer-run.ts";
import { ENROLL_PATH, checkEnrollCode, checkEnrollResponse, isLoopbackHost, type ConnectorIdentity, type EnrollRequest, type HostFacts, type ServerMode } from "./protocol.ts";
import { generateKeyPair } from "./signed.ts";
import type { AgentRecord } from "./state.ts";
@@ -37,7 +38,7 @@ export async function enroll(options: {
if (!code.ok) throw new Error(code.message);
const key = generateKeyPair();
const customerRun = options.mode === "customer-run";
- const request: EnrollRequest = { code: code.value, publicKey: key.publicKey, host: options.host, connector: options.connector, ...(customerRun ? { mode: "customer-run" } : {}) };
+ const request: EnrollRequest = { code: code.value, publicKey: key.publicKey, host: customerRun ? reducedFacts(options.host) : options.host, connector: options.connector, ...(customerRun ? { mode: "customer-run" } : {}) };
let response: Response;
try {
response = await (options.fetch ?? fetch)(`${options.admin}${ENROLL_PATH}`, {
diff --git a/connector/src/images.ts b/connector/src/images.ts
index 9c56f49fb8..e8142e6248 100644
--- a/connector/src/images.ts
+++ b/connector/src/images.ts
@@ -1,7 +1,22 @@
// 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.
+import { VERSION_LABEL, olderVersionRefusal } from "./customer-run.ts";
+import type { Docker } from "./docker.ts";
+
/** 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 () => {};
+
+/**
+ * For a customer-run server: an image that names no released version, or an older one than the image running now, is
+ * refused. A connector from before that mode does not know the mode, so going back to one would undo it.
+ */
+export function neverOlder(docker: Pick<Docker, "imageInspect">): ImageCheck {
+ const label = async (image: string | null) => (image ? (await docker.imageInspect(image).catch(() => null))?.Config?.Labels?.[VERSION_LABEL] : undefined);
+ return async (image, context) => {
+ const refusal = olderVersionRefusal(await label(image), await label(context.current));
+ if (refusal) throw new Error(refusal);
+ };
+}
diff --git a/connector/src/jobs.ts b/connector/src/jobs.ts
index 7960ba4a9e..c412a9eac6 100644
--- a/connector/src/jobs.ts
+++ b/connector/src/jobs.ts
@@ -26,13 +26,15 @@ export interface RunnerDeps {
selfUpdate: (job: Job<"self-update">) => Promise<JobReply | null>;
}
-export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | null> {
+export function jobRunner(deps: RunnerDeps): (job: Job, by?: AuditSource) => Promise<JobReply | null> {
let waiting = 0;
- const run = async (job: Job): Promise<JobReply | null> => {
+ const run = async (job: Job, by: AuditSource): Promise<JobReply | null> => {
const ok = <T extends JobType>(result: JobResults[T]): JobReply => ({ id: job.id, ok: true, result });
try {
const adopted = deps.adopted;
if (adopted) {
+ const refusal = customerRunRefusal(job.type, by);
+ if (refusal) return { id: job.id, ok: false, error: { code: "refused_by_mode", message: refusal } };
switch (job.type) {
case "start":
return ok(await adopted.start());
@@ -43,7 +45,7 @@ export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | nu
case "update":
return ok(await adopted.update(job.id, (job.args as JobArgs["update"]).image));
case "backup":
- return ok(await adopted.backup(job.id));
+ return ok(await adopted.backup(job.id, by));
case "restore":
return ok(await adopted.restore(job.id, (job.args as JobArgs["restore"]).backupId));
case "status": {
@@ -56,7 +58,7 @@ export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | nu
case "self-update":
return await deps.selfUpdate(job as Job<"self-update">);
default:
- return { id: job.id, ok: false, error: { code: "refused_by_mode", message: customerRunRefusal(job.type) ?? "This server is run by its owner." } };
+ return { id: job.id, ok: false, error: { code: "refused_by_mode", message: "This server is run by its owner." } };
}
}
const home = deps.home;
@@ -94,12 +96,12 @@ export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | nu
return { id: job.id, ok: false, error: asJobError(error) };
}
};
- return async (job) => {
- if (!CHANGES.has(job.type)) return run(job);
+ return async (job, by = "admin") => {
+ if (!CHANGES.has(job.type)) return run(job, by);
if (waiting >= MAX_WAITING) return { id: job.id, ok: false, error: { code: "busy", message: `${MAX_WAITING} jobs are already waiting on this server; send this one again later.` } };
waiting += 1;
try {
- return await run(job);
+ return await run(job, by);
} finally {
waiting -= 1;
}
@@ -118,11 +120,11 @@ export interface Desk {
}
export interface DeskDeps {
- run: (job: Job) => Promise<JobReply | null>;
+ run: (job: Job, by: AuditSource) => Promise<JobReply | null>;
audit: AuditLog;
log: Log;
policyFile?: string;
- /** Absent: `operated`. On a customer-run server a job outside that mode's list is refused, whoever sent it. */
+ /** Absent: `operated`. On a customer-run server a job outside that mode's lists is refused: one list for MausBot, a longer one for root on the server. */
mode?: ServerMode;
/** The server's admin has paused remote management: every job from MausBot is refused until they resume it. */
paused?: () => boolean;
@@ -148,12 +150,12 @@ export function jobDesk(deps: DeskDeps): Desk {
record(resultEvent(by, job.type, refused));
return refused;
};
- const outsideMode = deps.mode === "customer-run" ? customerRunRefusal(job.type) : null;
+ const outsideMode = deps.mode === "customer-run" ? customerRunRefusal(job.type, by) : null;
if (outsideMode) return refuse("refused_by_mode", outsideMode);
if (by === "admin" && deps.paused?.()) return refuse("paused", "This server's admin has paused remote management. They resume it with: mausbot-connector resume");
- const refusal = by === "admin" && deps.policyFile ? policyRefusal(job, readPolicy(deps.policyFile), deps.policyFile, deps.mode) : null;
+ const refusal = by === "admin" && deps.policyFile ? policyRefusal(job, readPolicy(deps.policyFile), deps.policyFile) : null;
if (refusal) return refuse("refused_by_policy", refusal);
- const reply = await deps.run(job);
+ const reply = await deps.run(job, by);
if (reply) record(resultEvent(by, job.type, reply));
return reply;
},
diff --git a/connector/src/local.ts b/connector/src/local.ts
index 19a32f4dc3..d94dd44318 100644
--- a/connector/src/local.ts
+++ b/connector/src/local.ts
@@ -38,7 +38,7 @@ export function serveLocalJobs(socketPath: string, desk: Desk, log: Log, mode: S
try { request = JSON.parse(text.slice(0, end)); } catch { request = null; }
const fields = typeof request === "object" && request !== null && !Array.isArray(request) ? request as Record<string, unknown> : {};
const message = { id: localJobId(), type: fields.type, args: fields.args };
- const checked = mode === "customer-run" ? checkCustomerRunJob(message) : checkJob(message);
+ const checked = mode === "customer-run" ? checkCustomerRunJob(message, "local") : checkJob(message);
if (!checked.ok) {
answer({ ok: false, error: { code: checked.code, message: checked.message } });
return;
diff --git a/connector/src/main.ts b/connector/src/main.ts
index 882d5667be..0327986184 100644
--- a/connector/src/main.ts
+++ b/connector/src/main.ts
@@ -14,6 +14,7 @@ import { reducedHeartbeat, reducedReply } from "./customer-run.ts";
import { SocketDocker, dockerApiProblem, type DockerInfo } from "./docker.ts";
import { adminOrigin, enroll } from "./enroll.ts";
import { readHealth } from "./home-health.ts";
+import { neverOlder } from "./images.ts";
import { serveRequest } from "./home-requests.ts";
import { Home } from "./home.ts";
import { hostChecks, hostFacts, hostHealth, probeBox, type BoxProbeResult, type HostReader } from "./host.ts";
@@ -151,7 +152,9 @@ async function run(): Promise<void> {
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 });
+ // On a customer-run server only its owner replaces the connector, and never with an older one: one from before this
+ // mode would not know the mode.
+ const updater = new SelfUpdater({ docker, state, log, instance, identity, ...(mode === "customer-run" ? { checkImage: neverOlder(docker) } : {}) });
const heartbeat = async (): Promise<Heartbeat> => {
await home.refreshHealth().catch(() => null);
const facts = { host: await host.health(false), home: await home.report(), connector: identity() };
diff --git a/connector/src/policy.ts b/connector/src/policy.ts
index 7ef86770cf..c9d64d57e6 100644
--- a/connector/src/policy.ts
+++ b/connector/src/policy.ts
@@ -6,11 +6,9 @@
//
// `jobs`: the only kinds MausBot may run here (absent: all of them). `updates: "hold"`: MausBot's home updates wait.
// A self-update of the connector is always accepted, so a held or locked-down server never strands an old connector.
-// On a customer-run server the owner's list covers it too: a new connector could carry other rules, so the owner may
-// keep the one they read.
import { readFileSync } from "node:fs";
-import { JOB_TYPES, type Job, type JobType, type ServerMode } from "./protocol.ts";
+import { JOB_TYPES, type Job, type JobType } from "./protocol.ts";
export const POLICY_FILE = "policy.json";
@@ -46,9 +44,9 @@ export function readPolicy(file: string): ReturnType<typeof parsePolicy> {
return parsePolicy(text);
}
-/** Why the server's policy refuses `job` from MausBot, or null. On a server MausBot operates a self-update is never refused. */
-export function policyRefusal(job: Job, read: ReturnType<typeof parsePolicy>, file: string, mode: ServerMode = "operated"): string | null {
- if (job.type === "self-update" && (mode !== "customer-run" || !read.ok || !read.policy.jobs)) return null;
+/** Why the server's policy refuses `job` from MausBot, or null. A self-update is never refused. */
+export function policyRefusal(job: Job, read: ReturnType<typeof parsePolicy>, file: string): string | null {
+ if (job.type === "self-update") return null;
if (!read.ok) return READS.has(job.type) ? null : `This server's policy ${file} cannot be used (${read.problem}), so MausBot changes nothing here until it is fixed.`;
if (read.policy.jobs && !read.policy.jobs.includes(job.type)) return `This server's policy ${file} does not let MausBot run ${job.type} jobs.`;
if (job.type === "update" && read.policy.updates === "hold") return `This server's policy ${file} holds updates.`;
diff --git a/connector/src/protocol.ts b/connector/src/protocol.ts
index 33ce681586..a3906a30a6 100644
--- a/connector/src/protocol.ts
+++ b/connector/src/protocol.ts
@@ -202,8 +202,8 @@ export type JobErrorCode =
| "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"
| "unsigned_job" | "wrong_box" | "expired_job" | "pending_box"
- /** A customer-run server only: the job is not on its list, its admin has paused remote management, or its own updater is missing or declined. */
- | "refused_by_mode" | "paused" | "update_unavailable" | "update_not_started";
+ /** A customer-run server only: the job is not on its list, its admin has paused remote management, or its own updater is missing or declined, or the image asked for is older than the one running. */
+ | "refused_by_mode" | "paused" | "update_unavailable" | "update_not_started" | "older_version";
/** `message` is plain words for the Admin's log and alerts; it never carries a secret. */
export interface JobError {
diff --git a/connector/test/customer-run.test.ts b/connector/test/customer-run.test.ts
index f4db6b196d..70bd7a3308 100644
--- a/connector/test/customer-run.test.ts
+++ b/connector/test/customer-run.test.ts
@@ -4,15 +4,15 @@ import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { AdoptedHome, UPDATE_FILES, enrolmentRefusal, findInstall, standaloneServerPresent } from "../src/adopted-home.ts";
-import { Agent, type Refusal } from "../src/agent.ts";
+import { Agent, type Refusal, type Socket } from "../src/agent.ts";
import { AuditLog, type AuditEvent, type AuditLine } from "../src/audit.ts";
import { serveCustomerRunRequest } from "../src/customer-run-requests.ts";
import {
- CUSTOMER_RUN_JOBS, CUSTOMER_RUN_REQUESTS, HOME_READS, HOME_READS_COMMAND, checkCustomerRunJob, customerRunRefusal, parseHomeReads, reducedHeartbeat, reducedReply,
+ CUSTOMER_RUN_JOBS, CUSTOMER_RUN_LOCAL_JOBS, CUSTOMER_RUN_REQUESTS, HOME_READS, HOME_READS_COMMAND, checkCustomerRunJob, customerRunRefusal, olderVersionRefusal, parseHomeReads, reducedHeartbeat, reducedReply,
} from "../src/customer-run.ts";
import { enroll } from "../src/enroll.ts";
+import { neverOlder } from "../src/images.ts";
import { jobDesk, jobRunner } from "../src/jobs.ts";
-import { parsePolicy, policyRefusal } from "../src/policy.ts";
import { JOB_TYPES, checkJob, type HostFacts, type HostHealth, type Job, type JobReply, type JobType } from "../src/protocol.ts";
import { StateStore, type AgentRecord } from "../src/state.ts";
import { FakeAdmin } from "./fake-admin.ts";
@@ -23,6 +23,8 @@ const CLOUD_HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"c".repe
const CONNECTOR = `ghcr.io/milind-soni/mausbot-connector@sha256:${"1".repeat(64)}`;
const RUNNING = "ghcr.io/milind-soni/openmausbot:v0.1.151";
const NEXT = digest("b");
+const OLDER = digest("a");
+const UNNAMED = digest("d");
const EMAIL = "[email protected]";
const WRITTEN = "Quarterly numbers for Project Nightingale";
const SERVER_NAME = "Lovelace Analytical Engines";
@@ -47,7 +49,7 @@ async function until(check: () => boolean, ms = 5_000): Promise<void> {
}
/** A server its owner installed with deploy/install.sh: the Compose project, its data folder, and a home that answers on its own loopback. */
-function server(options: { image?: string; seats?: number | null } = {}) {
+async function server(options: { image?: string; seats?: number | null } = {}) {
const dir = mkdtempSync(join(tmpdir(), "omb-customer-run-"));
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
const dataDir = join(dir, "opt-openmausbot", "data");
@@ -59,10 +61,8 @@ function server(options: { image?: string; seats?: number | null } = {}) {
let clock = 1_800_000_000_000;
docker.now = () => clock;
const image = options.image ?? RUNNING;
- for (const ref of [image, NEXT, "caddy:2"]) {
- docker.publish(ref, null);
- docker.images.set(ref, {});
- }
+ for (const [ref, version] of [[image, "v0.1.151"], [NEXT, "v0.1.152"], [OLDER, "v0.1.150"], [UNNAMED, null], ["caddy:2", null]] as const) docker.publish(ref, version);
+ for (const ref of [image, "caddy:2"]) await docker.pull(ref);
const compose = (service: string) => ({ "com.docker.compose.project": "openmausbot", "com.docker.compose.service": service });
const home = { answers: true, seats: options.seats === undefined ? 7 : options.seats, execs: [] as string[][] };
docker.onExec = (_container, command) => {
@@ -92,10 +92,10 @@ function server(options: { image?: string; seats?: number | null } = {}) {
docker.folder(dataDir).files.set("chats.json", WRITTEN);
docker.calls.length = 0;
};
- return { dir, dataDir, updateDir, state, docker, adopted, home, steps, lines, install, image };
+ return { dir, dataDir, updateDir, state, docker, adopted, home, steps, lines, install, image, advance: (ms: number) => { clock += ms; } };
}
-function desk(fixture: ReturnType<typeof server>, options: { mode?: "customer-run" | "operated"; paused?: () => boolean } = {}) {
+function desk(fixture: Awaited<ReturnType<typeof server>>, options: { mode?: "customer-run" | "operated"; paused?: () => boolean } = {}) {
const ran: Job[] = [];
const audit = new AuditLog(join(fixture.dir, "audit.jsonl"));
const run = jobRunner({
@@ -103,44 +103,72 @@ function desk(fixture: ReturnType<typeof server>, options: { mode?: "customer-ru
admin: () => ({ origin: "https://cloud.example.test", authorization: () => "Box token" }),
selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: identity } }),
});
- const made = jobDesk({ run: async (job) => { ran.push(job); return run(job); }, audit, log: () => {}, mode: options.mode ?? "customer-run", paused: options.paused });
+ const made = jobDesk({ run: async (job, by) => { ran.push(job); return run(job, by); }, audit, log: () => {}, mode: options.mode ?? "customer-run", paused: options.paused });
const lines = () => audit.tail(100).map((line) => JSON.parse(line) as AuditLine);
return { desk: made, ran, lines };
}
describe("a customer-run server: the jobs MausBot may run", () => {
- it("lists nine kinds, and neither of the two that move the data", () => {
- expect([...CUSTOMER_RUN_JOBS].sort()).toEqual(["backup", "host-health", "restart", "restore", "self-update", "start", "status", "stop", "update"]);
- expect(JOB_TYPES.filter((type) => customerRunRefusal(type) !== null)).toEqual(["export-disk", "import-disk"]);
+ it("lists seven kinds for MausBot and two more for the server's own root, and for neither the two that move the data", () => {
+ expect([...CUSTOMER_RUN_JOBS].sort()).toEqual(["backup", "host-health", "restart", "start", "status", "stop", "update"]);
+ expect([...CUSTOMER_RUN_LOCAL_JOBS].sort()).toEqual(["restore", "self-update"]);
+ expect(JOB_TYPES.filter((type) => customerRunRefusal(type, "admin") !== null)).toEqual(["restore", "export-disk", "import-disk", "self-update"]);
+ expect(JOB_TYPES.filter((type) => customerRunRefusal(type, "local") !== null)).toEqual(["export-disk", "import-disk"]);
+ });
+
+ it("refuses MausBot replacing the connector or putting old data back, at each of the three checks, and lets the server's own root do both", async () => {
+ const jobs = [{ id: "c1", type: "self-update", args: { image: CONNECTOR } }, { id: "r1", type: "restore", args: { backupId: "20261028-104512-3fa9" } }] as Job[];
+ const fixture = await server();
+ await fixture.install();
+ const { desk: made, ran } = desk(fixture);
+ const run = jobRunner({
+ adopted: fixture.adopted, hostHealth: async () => health, identity: () => identity,
+ admin: () => ({ origin: "https://cloud.example.test", authorization: () => "Box token" }),
+ selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: identity } }),
+ });
+ for (const job of jobs) {
+ expect(checkJob(job), job.type).toMatchObject({ ok: true });
+ expect(checkCustomerRunJob(job, "admin"), job.type).toMatchObject({ ok: false, id: job.id, code: "refused_by_mode", message: expect.stringContaining(`only they may run ${job.type} here`) });
+ expect(checkCustomerRunJob(job, "local"), job.type).toMatchObject({ ok: true });
+ expect(await made.submit(job, "admin"), job.type).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });
+ expect(await run(job, "admin"), job.type).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });
+ }
+ expect(ran).toEqual([]);
+ expect(fixture.docker.calls).toEqual([]);
+ expect(await made.submit(jobs[0]!, "local")).toEqual({ id: "c1", ok: true, result: { connector: identity } });
+ expect(await made.submit(jobs[1]!, "local")).toMatchObject({ ok: false, error: { code: "not_found" } });
+ expect(ran.map((job) => job.type)).toEqual(["self-update", "restore"]);
});
it("refuses export-disk, import-disk and any kind it does not list as the job arrives, while the operated check still takes them", () => {
const moved: [JobType, Record<string, unknown>][] = [["export-disk", {}], ["import-disk", { url: "https://storage.example.test/disk.tar.gz" }]];
for (const [type, args] of moved) {
expect(checkJob({ id: "j1", type, args })).toMatchObject({ ok: true });
- expect(checkCustomerRunJob({ id: "j1", type, args })).toEqual({
- ok: false, id: "j1", code: "refused_by_mode", message: `This server is run by its owner, and "${type}" is not a job MausBot may run on it.`,
- });
+ for (const by of ["admin", "local"] as const) {
+ expect(checkCustomerRunJob({ id: "j1", type, args }, by)).toEqual({
+ ok: false, id: "j1", code: "refused_by_mode", message: `This server is run by its owner, and "${type}" is not a job that may run on it.`,
+ });
+ }
}
- expect(checkCustomerRunJob({ id: "j2", type: "shell", args: { command: "cat /data" } })).toMatchObject({ ok: false, code: "refused_by_mode" });
+ expect(checkCustomerRunJob({ id: "j2", type: "shell", args: { command: "cat /data" } }, "admin")).toMatchObject({ ok: false, code: "refused_by_mode" });
});
it("refuses a start that names an image or settings, and an update to anything but MausBot's server image by digest", () => {
const env = { OMB_CLOUD_ROLE: "team", OMB_CLOUD_MACHINE_ID: "m", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_PUBLIC_URL: "https://acme.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: "s".repeat(40) };
expect(checkJob({ id: "s1", type: "start", args: { image: CLOUD_HOME, env } })).toMatchObject({ ok: true });
- expect(checkCustomerRunJob({ id: "s1", type: "start", args: { image: CLOUD_HOME, env } })).toMatchObject({ ok: false, id: "s1", code: "refused_by_mode" });
- expect(checkCustomerRunJob({ id: "s2", type: "start" })).toEqual({ ok: true, job: { id: "s2", type: "start", args: {} } });
- expect(checkCustomerRunJob({ id: "u1", type: "update", args: { image: NEXT } })).toEqual({ ok: true, job: { id: "u1", type: "update", args: { image: NEXT } } });
+ expect(checkCustomerRunJob({ id: "s1", type: "start", args: { image: CLOUD_HOME, env } }, "admin")).toMatchObject({ ok: false, id: "s1", code: "refused_by_mode" });
+ expect(checkCustomerRunJob({ id: "s2", type: "start" }, "admin")).toEqual({ ok: true, job: { id: "s2", type: "start", args: {} } });
+ expect(checkCustomerRunJob({ id: "u1", type: "update", args: { image: NEXT } }, "admin")).toEqual({ ok: true, job: { id: "u1", type: "update", args: { image: NEXT } } });
for (const image of [CLOUD_HOME, RUNNING, "ghcr.io/someone-else/openmausbot@sha256:" + "a".repeat(64)]) {
- expect(checkCustomerRunJob({ id: "u2", type: "update", args: { image } }), image).toMatchObject({ ok: false, code: "invalid_args" });
+ expect(checkCustomerRunJob({ id: "u2", type: "update", args: { image } }, "admin"), image).toMatchObject({ ok: false, code: "invalid_args" });
}
- expect(checkCustomerRunJob({ id: "u3", type: "update", args: { image: NEXT, env } })).toMatchObject({ ok: false, code: "invalid_args" });
- expect(checkCustomerRunJob({ id: "bad id", type: "start" })).toMatchObject({ ok: false, id: null, code: "invalid_job" });
- expect(checkCustomerRunJob({ id: "r1", type: "restore", args: { backupId: "../etc" } })).toMatchObject({ ok: false, code: "invalid_args" });
+ expect(checkCustomerRunJob({ id: "u3", type: "update", args: { image: NEXT, env } }, "admin")).toMatchObject({ ok: false, code: "invalid_args" });
+ expect(checkCustomerRunJob({ id: "bad id", type: "start" }, "admin")).toMatchObject({ ok: false, id: null, code: "invalid_job" });
+ expect(checkCustomerRunJob({ id: "r1", type: "restore", args: { backupId: "../etc" } }, "local")).toMatchObject({ ok: false, code: "invalid_args" });
});
it("refuses them again at the desk, whoever sent them, runs nothing, and writes both the job and the refusal to the audit log", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
const { desk: made, ran, lines } = desk(fixture);
for (const by of ["admin", "local"] as const) {
@@ -161,7 +189,7 @@ describe("a customer-run server: the jobs MausBot may run", () => {
});
it("has no way to run them even past both checks: the home it attached to refuses the kind", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
const run = jobRunner({
adopted: fixture.adopted, hostHealth: async () => health, identity: () => identity,
@@ -175,13 +203,13 @@ describe("a customer-run server: the jobs MausBot may run", () => {
});
describe("a customer-run server: pausing remote management", () => {
- it("refuses every job from MausBot while paused, the connector's own update too, logs each, and still runs the admin's own", async () => {
- const fixture = server();
+ it("refuses every job from MausBot while paused, logs each, and still runs the admin's own", async () => {
+ const fixture = await server();
await fixture.install();
let paused = true;
const { desk: made, ran, lines } = desk(fixture, { paused: () => paused });
- for (const type of ["status", "stop", "self-update"] as const) {
- const job = { id: `p-${type}`, type, args: type === "self-update" ? { image: CONNECTOR } : {} } as Job;
+ for (const type of ["status", "stop", "backup"] as const) {
+ const job = { id: `p-${type}`, type, args: {} } as Job;
expect(await made.submit(job, "admin")).toMatchObject({ ok: false, error: { code: "paused" } });
}
expect(ran).toEqual([]);
@@ -191,17 +219,8 @@ describe("a customer-run server: pausing remote management", () => {
expect(await made.submit({ id: "after", type: "status", args: {} }, "admin")).toMatchObject({ ok: true });
});
- it("lets the owner's policy file keep the connector they read: its job list covers the connector's own update here, and only here", () => {
- const update = { id: "c1", type: "self-update", args: { image: CONNECTOR } } as Job;
- const listed = parsePolicy('{"jobs":["status","host-health"]}');
- expect(policyRefusal(update, listed, "/etc/mausbot/policy.json", "customer-run")).toBe("This server's policy /etc/mausbot/policy.json does not let MausBot run self-update jobs.");
- expect(policyRefusal(update, listed, "/etc/mausbot/policy.json")).toBeNull();
- expect(policyRefusal(update, parsePolicy(null), "/etc/mausbot/policy.json", "customer-run")).toBeNull();
- expect(policyRefusal(update, parsePolicy('{"jobs":["self-update"]}'), "/etc/mausbot/policy.json", "customer-run")).toBeNull();
- });
-
- it("is kept on the server's disk, where the running connector reads it before each job", () => {
- const { state } = server();
+ it("is kept on the server's disk, where the running connector reads it before each job", async () => {
+ const { state } = await server();
expect(state.paused()).toBe(false);
state.savePause(true);
expect(new StateStore(state.dir).paused()).toBe(true);
@@ -219,8 +238,8 @@ describe("a customer-run server: what leaves it", () => {
return out;
};
- it("reads three fields from the home and drops everything else it answered", () => {
- const fixture = server();
+ it("reads three fields from the home and drops everything else it answered", async () => {
+ const fixture = await server();
expect(HOME_READS).toEqual(["/api/health", "/.well-known/openmausbot/environment", "/api/seats"]);
const facts = parseHomeReads(fixture.docker.onExec!({} as never, []).output);
expect(facts).toEqual({ answers: true, version: "0.1.151", seats: 7 });
@@ -229,7 +248,7 @@ describe("a customer-run server: what leaves it", () => {
});
it("sends a heartbeat of versions, states, counts and the seat count, with no address, name or sentence in it", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
await fixture.adopted.refreshHealth();
expect(fixture.home.execs).toEqual([[...HOME_READS_COMMAND]]);
@@ -282,19 +301,19 @@ describe("a customer-run server: what leaves it", () => {
describe("a customer-run server: the home its owner installed", () => {
it("attaches to the Compose install, and says in plain words why it cannot when there is none or it was built here", async () => {
- const fixture = server();
+ const fixture = await server();
expect(await standaloneServerPresent(fixture.docker)).toBe(false);
expect(await findInstall(fixture.docker)).toEqual({ ok: false, why: "MausBot is not installed on this server yet. Install it first with the server's install command, then connect it." });
await fixture.install();
expect(await standaloneServerPresent(fixture.docker)).toBe(true);
expect(await findInstall(fixture.docker)).toMatchObject({ ok: true, install: { dataDir: fixture.dataDir } });
- const built = server({ image: "deploy-omb" });
+ const built = await server({ image: "deploy-omb" });
await built.install();
expect(await findInstall(built.docker)).toMatchObject({ ok: false, why: expect.stringContaining("was built here") });
});
it("will not be enrolled as a server MausBot runs where its owner's MausBot is already installed: that would start a second one", async () => {
- const fixture = server();
+ const fixture = await server();
expect(await enrolmentRefusal("operated", fixture.docker)).toBeNull();
expect(await enrolmentRefusal("customer-run", fixture.docker)).toContain("MausBot is not installed on this server yet.");
await fixture.install();
@@ -305,7 +324,7 @@ describe("a customer-run server: the home its owner installed", () => {
});
it("stops Caddy before the home and starts it after the home answers, and never makes, removes or renames a container", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
expect(await fixture.adopted.stop()).toEqual({ home: { state: "stopped", image: RUNNING, health: null } });
expect(fixture.docker.calls).toEqual(["stop openmausbot-caddy-1", "stop openmausbot-omb-1"]);
@@ -320,7 +339,7 @@ describe("a customer-run server: the home its owner installed", () => {
});
it("says the home did not answer when it does not, within the wait", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
await fixture.adopted.stop();
fixture.home.answers = false;
@@ -329,9 +348,9 @@ describe("a customer-run server: the home its owner installed", () => {
});
it("backs the data folder up to a volume on the same server and puts a backup back, with a safety copy first", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
- const { backup } = await fixture.adopted.backup("b1");
+ const { backup } = await fixture.adopted.backup("b1", "local");
expect(fixture.docker.files(`mausbot-backup-${backup.id}`)).toEqual({ "chats.json": WRITTEN });
expect(fixture.docker.container("openmausbot-omb-1")?.status).toBe("running");
fixture.docker.folder(fixture.dataDir).files.set("chats.json", "changed since");
@@ -344,10 +363,24 @@ describe("a customer-run server: the home its owner installed", () => {
await expect(fixture.adopted.restore("r2", "20200101-000000-aaaa")).rejects.toMatchObject({ code: "not_found" });
});
+ it("keeps three backups for each sender, so MausBot's backups never push out one the owner made", async () => {
+ const fixture = await server();
+ await fixture.install();
+ const mine = (await fixture.adopted.backup("mine", "local")).backup.id;
+ const theirs: string[] = [];
+ for (const id of ["a1", "a2", "a3", "a4", "a5"]) {
+ fixture.advance(1_000);
+ theirs.push((await fixture.adopted.backup(id, "admin")).backup.id);
+ }
+ const kept = (await fixture.adopted.copies()).backups.map((copy) => copy.id).sort();
+ expect(kept).toEqual([mine, ...theirs.slice(2)].sort());
+ expect(fixture.docker.files(`mausbot-backup-${mine}`)).toEqual({ "chats.json": WRITTEN });
+ });
+
it("puts the data back as it was when the connector restarts in the middle of a restore", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
- const { backup } = await fixture.adopted.backup("b1");
+ const { backup } = await fixture.adopted.backup("b1", "local");
const before = { "chats.json": "the newest chats" };
fixture.docker.folder(fixture.dataDir).files.set("chats.json", before["chats.json"]);
await fixture.docker.createVolume("mausbot-snapshot", { "com.mausbot.role": "snapshot" });
@@ -360,9 +393,24 @@ describe("a customer-run server: the home its owner installed", () => {
});
});
+describe("a customer-run server: replacing the connector", () => {
+ it("is refused, even for the server's own root, when the new image is older than the one running or names no version", async () => {
+ const fixture = await server();
+ const [now, newer, old, unnamed] = ["1", "2", "3", "4"].map((letter) => `ghcr.io/milind-soni/mausbot-connector@sha256:${letter.repeat(64)}`);
+ for (const [ref, version] of [[now, "v0.1.152"], [newer, "v0.1.153"], [old, "v0.1.140"], [unnamed, null]] as const) {
+ fixture.docker.publish(ref!, version);
+ await fixture.docker.pull(ref!);
+ }
+ const check = neverOlder(fixture.docker);
+ await expect(check(newer!, { kind: "connector", current: now! })).resolves.toBeUndefined();
+ await expect(check(old!, { kind: "connector", current: now! })).rejects.toThrow("Version 0.1.140 is older than 0.1.152, which runs here.");
+ await expect(check(unnamed!, { kind: "connector", current: now! })).rejects.toThrow("The image does not say which version it is.");
+ });
+});
+
describe("a customer-run server: updates go to the server's own updater", () => {
/** Stands in for mausbot-update-runner.sh: reads the request the connector left and answers with update.sh's exit code. */
- const updater = (fixture: ReturnType<typeof server>, code: number, seen: string[] = []) => {
+ const updater = (fixture: Awaited<ReturnType<typeof server>>, code: number, seen: string[] = []) => {
writeFileSync(join(fixture.updateDir, UPDATE_FILES.runner), "1\n");
const sleep = (fixture.adopted as unknown as { sleep: (ms: number) => Promise<void> }).sleep;
(fixture.adopted as unknown as { sleep: (ms: number) => Promise<void> }).sleep = async (ms) => {
@@ -379,26 +427,47 @@ describe("a customer-run server: updates go to the server's own updater", () =>
};
it("leaves the image for the updater, touches no container itself, and reports the new image once the updater is done", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
const seen = updater(fixture, 0);
const result = await fixture.adopted.update("u1", NEXT);
expect(seen).toEqual([`id=u1\nimage=${NEXT}\n`]);
expect(result).toMatchObject({ previousImage: RUNNING, snapshot: null, home: { state: "running" } });
- expect(fixture.docker.calls.filter((call) => !call.startsWith("exec "))).toEqual([]);
+ expect(fixture.docker.calls.filter((call) => !call.startsWith("exec "))).toEqual([`pull ${NEXT}`]);
expect(fixture.state.home()).toMatchObject({ image: NEXT, previousImage: RUNNING, operation: null });
expect(fixture.steps).toEqual(["u1 request", "u1 wait"]);
});
+ it("never moves the server to an older version, or to an image that names none, and asks nothing of the updater then", async () => {
+ expect(olderVersionRefusal("v0.1.152", "v0.1.151")).toBeNull();
+ expect(olderVersionRefusal("0.1.151", "v0.1.151")).toBeNull();
+ expect(olderVersionRefusal("v0.1.150", "v0.1.151")).toBe("Version 0.1.150 is older than 0.1.151, which runs here.");
+ expect(olderVersionRefusal("v0.2.0", "v0.10.0")).toBe("Version 0.2.0 is older than 0.10.0, which runs here.");
+ expect(olderVersionRefusal("v0.1.152", "v0.1.151", "0.1.160")).toBe("Version 0.1.152 is older than 0.1.160, the oldest this server accepts.");
+ expect(olderVersionRefusal(undefined, "v0.1.151")).toBe("The image does not say which version it is.");
+ expect(olderVersionRefusal("latest", null)).toBe("The image does not say which version it is.");
+ expect(olderVersionRefusal("v0.1.152", undefined)).toBeNull();
+ const fixture = await server();
+ await fixture.install();
+ const seen = updater(fixture, 0);
+ for (const image of [OLDER, UNNAMED]) {
+ await expect(fixture.adopted.update("u1", image), image).rejects.toMatchObject({ code: "older_version", message: expect.stringContaining("Nothing was changed.") });
+ }
+ expect(seen).toEqual([]);
+ expect(existsSync(join(fixture.updateDir, UPDATE_FILES.request))).toBe(false);
+ expect(fixture.state.home().operation).toBeNull();
+ expect(fixture.docker.calls.filter((call) => !call.startsWith("pull "))).toEqual([]);
+ });
+
it("maps each way the updater ends to a code, and refuses when the server has no updater or the image is not MausBot's", async () => {
- for (const [code, expected] of [[1, "update_rolled_back"], [2, "rollback_failed"], [3, "busy"], [4, "update_not_started"], [127, "update_unavailable"], [9, "docker"]] as const) {
- const fixture = server();
+ for (const [code, expected] of [[1, "update_rolled_back"], [2, "rollback_failed"], [3, "busy"], [4, "update_not_started"], [5, "older_version"], [127, "update_unavailable"], [9, "docker"]] as const) {
+ const fixture = await server();
await fixture.install();
updater(fixture, code);
await expect(fixture.adopted.update("u1", NEXT), String(code)).rejects.toMatchObject({ code: expected });
expect(fixture.state.home().operation).toBeNull();
}
- const bare = server();
+ const bare = await server();
await bare.install();
await expect(bare.adopted.update("u2", NEXT)).rejects.toMatchObject({ code: "update_unavailable" });
await expect(bare.adopted.update("u3", CLOUD_HOME)).rejects.toMatchObject({ code: "image_refused" });
@@ -406,7 +475,7 @@ describe("a customer-run server: updates go to the server's own updater", () =>
});
it("says so when the updater never answers, and takes its late verdict after a restart", async () => {
- const fixture = server();
+ const fixture = await server();
await fixture.install();
writeFileSync(join(fixture.updateDir, UPDATE_FILES.runner), "1\n");
await expect(fixture.adopted.update("u1", NEXT)).rejects.toMatchObject({ code: "interrupted" });
@@ -458,6 +527,40 @@ describe("a customer-run server: MausBot's requests", () => {
expect("mode" in operated).toBe(false);
});
+ it("sends the server's facts at enrolment as it does in the heartbeat: nothing that is not a machine's own name for itself", async () => {
+ const admin = new FakeAdmin();
+ await admin.listen();
+ cleanups.push(() => admin.close());
+ const odd = { ...host, os: `Ubuntu (${EMAIL})`, kernel: "6.8.0\nBcc: someone", docker: WRITTEN + "!" };
+ const record = await enroll({ admin: admin.origin, code: admin.mintCode(), host: odd, connector: identity, mode: "customer-run" });
+ expect(admin.boxes.get(record.boxId)!.enroll.host).toEqual({ ...host, os: "unknown", kernel: "unknown", docker: "unknown" });
+ const operated = await enroll({ admin: admin.origin, code: admin.mintCode(), host: odd, connector: identity });
+ expect(admin.boxes.get(operated.boxId)!.enroll.host).toEqual(odd);
+ });
+
+ it("closes a connection with the code alone: the reason, which can name a path on the server, stays in its own log", () => {
+ const closes: { mode: string; code?: number; reason?: string }[] = [];
+ const lines: string[] = [];
+ for (const mode of ["customer-run", "operated"] as const) {
+ const socket: Socket = {
+ readyState: 1, bufferedAmount: 0, binaryType: "", send: () => {}, onopen: null, onmessage: null, onclose: null, onerror: null,
+ close: (code, reason) => { closes.push({ mode, code, reason }); },
+ };
+ const agent = new Agent({
+ identity: () => ({ version: 2, admin: "https://cloud.example.test", boxId: "box-12345678", teamId: "t", publicKey: "", privateKey: "", adminKeys: {}, enrolledAt: 1 }),
+ log: (line) => lines.push(line), heartbeat: async () => { throw new Error("unused"); }, handle: async () => null, socket: () => socket, mode,
+ nextCount: () => { throw new Error("EACCES: permission denied, open '/state/connect-count.json'"); },
+ setTimer: () => null, clearTimer: () => {},
+ });
+ agent.start();
+ socket.onmessage!({ data: JSON.stringify({ t: "challenge", v: 1, nonce: "A".repeat(43) }) });
+ agent.stop();
+ }
+ expect(closes[0]).toEqual({ mode: "customer-run", code: 4000, reason: "" });
+ expect(closes.find((close) => close.mode === "operated")?.reason).toContain("/state/connect-count.json");
+ expect(lines.filter((line) => line.includes("/state/connect-count.json"))).toHaveLength(2);
+ });
+
it("answers the four requests on its list itself, with numbers and versions only", async () => {
const { admin, audits } = await connected();
expect(Object.keys(CUSTOMER_RUN_REQUESTS)).toEqual(["GET /v1/health", "GET /v1/version", "GET /v1/seats", "GET /v1/update"]);
@@ -503,6 +606,13 @@ describe("a customer-run server: MausBot's requests", () => {
expect(await admin.replyTo("x2", 5_000)).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });
expect(handled).toEqual([]);
expect(refusals.map((refusal) => `${refusal.code} ${refusal.id} ${refusal.type}`)).toEqual(["refused_by_mode x1 export-disk", "refused_by_mode x2 import-disk"]);
+ admin.send({ job: admin.signJob(record.boxId, { id: "x4", type: "self-update", args: { image: CONNECTOR } }) });
+ expect(await admin.replyTo("x4", 5_000)).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });
+ admin.send({ job: admin.signJob(record.boxId, { id: "x5", type: "restore", args: { backupId: "20261028-104512-3fa9" } }) });
+ expect(await admin.replyTo("x5", 5_000)).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });
+ expect(handled).toEqual([]);
+ expect(refusals.slice(2).map((refusal) => `${refusal.code} ${refusal.id} ${refusal.type}`)).toEqual(["refused_by_mode x4 self-update", "refused_by_mode x5 restore"]);
+ refusals.length = 2;
admin.send({ job: admin.signJob(record.boxId, { id: "x3", type: "stop", args: {} }) });
const failed = await admin.replyTo("x3", 5_000);
expect(failed).toMatchObject({ ok: false, error: { code: "docker" } });
diff --git a/connector/test/update-runner.test.ts b/connector/test/update-runner.test.ts
index 9a1f3caa30..356d41804e 100644
--- a/connector/test/update-runner.test.ts
+++ b/connector/test/update-runner.test.ts
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { UPDATE_FILES } from "../src/adopted-home.ts";
-import { CUSTOMER_HOME_IMAGE } from "../src/customer-run.ts";
+import { CUSTOMER_HOME_IMAGE, SERVER_VERSION_FLOOR, VERSION_LABEL } from "../src/customer-run.ts";
const SCRIPT = join(import.meta.dirname, "..", "host", "mausbot-update-runner.sh");
const IMAGE = `ghcr.io/milind-soni/openmausbot@sha256:${"b".repeat(64)}`;
@@ -16,7 +16,7 @@ afterEach(() => {
});
/** Runs the runner on a request, beside an update.sh that records how it was called and exits with `exit`. */
-function run(request: string | null, options: { exit?: number; updater?: boolean } = {}) {
+function run(request: string | null, options: { exit?: number; updater?: boolean; wanted?: string; running?: string; pulls?: boolean } = {}) {
const dir = mkdtempSync(join(tmpdir(), "omb-update-runner-"));
dirs.push(dir);
const update = join(dir, "update");
@@ -28,8 +28,20 @@ function run(request: string | null, options: { exit?: number; updater?: boolean
writeFileSync(join(install, "update.sh"), `printf '%s\\n' "$*" >> "${called}"\nexit ${options.exit ?? 0}\n`);
chmodSync(join(install, "update.sh"), 0o755);
}
+ // Stands in for docker: the image asked for carries `wanted` as its version, the server's container runs `running`.
+ const bin = join(dir, "bin");
+ mkdirSync(bin);
+ writeFileSync(join(bin, "docker"), `#!/bin/sh
+case "$1 $2" in
+ "image inspect") if [ "$3" = -f ]; then case "$5" in sha256:running) echo "${options.running ?? "v0.1.151"}" ;; *) echo "${options.wanted ?? "v0.1.152"}" ;; esac; else exit ${options.pulls === false ? 1 : 0}; fi ;;
+ "pull -q") exit 1 ;;
+ "ps -aq") echo c1 ;;
+ "inspect -f") echo sha256:running ;;
+esac
+`);
+ chmodSync(join(bin, "docker"), 0o755);
if (request !== null) writeFileSync(join(update, UPDATE_FILES.request), request);
- const result = spawnSync("sh", [SCRIPT], { encoding: "utf8", env: { PATH: "/usr/bin:/bin", MAUSBOT_UPDATE_DIR: update, MAUSBOT_INSTALL_DIR: install }, timeout: 30_000 });
+ const result = spawnSync("sh", [SCRIPT], { encoding: "utf8", env: { PATH: `${bin}:/usr/bin:/bin`, MAUSBOT_UPDATE_DIR: update, MAUSBOT_INSTALL_DIR: install }, timeout: 30_000 });
const answer = existsSync(join(update, UPDATE_FILES.result)) ? readFileSync(join(update, UPDATE_FILES.result), "utf8") : null;
return { result, answer, calls: existsSync(called) ? readFileSync(called, "utf8").trim().split("\n") : [], install, pending: existsSync(join(update, UPDATE_FILES.request)) };
}
@@ -63,6 +75,20 @@ describe.skipIf(!posix)("mausbot-update-runner.sh", () => {
expect(odd.pending).toBe(false);
});
+ it("never hands over an image older than the version running, or one that names no version, and holds the connector's own floor", () => {
+ for (const [wanted, running] of [["v0.1.150", "v0.1.151"], ["v0.1.9", "v0.1.10"], ["v0.9.9", "v1.0.0"], ["", "v0.1.151"], ["latest", "v0.1.151"], ["<no value>", "v0.1.151"]]) {
+ const refused = run(`id=u1\nimage=${IMAGE}\n`, { wanted, running });
+ expect(refused.calls, `${wanted} over ${running}`).toEqual([]);
+ expect(refused.answer, `${wanted} over ${running}`).toBe("id=u1\ncode=5\n");
+ }
+ for (const [wanted, running] of [["v0.1.151", "v0.1.151"], ["v0.1.152", "v0.1.151"], ["v0.2.0", "v0.1.151"], ["v1.0.0", "v0.9.9"], ["v0.1.152", ""]]) {
+ expect(run(`id=u1\nimage=${IMAGE}\n`, { wanted, running }).answer, `${wanted} over ${running}`).toBe("id=u1\ncode=0\n");
+ }
+ expect(run(`id=u1\nimage=${IMAGE}\n`, { pulls: false }).answer).toBe("id=u1\ncode=4\n");
+ expect(readFileSync(SCRIPT, "utf8")).toContain(`\nFLOOR=${SERVER_VERSION_FLOOR}\n`);
+ expect(readFileSync(SCRIPT, "utf8")).toContain(`\nVERSION_LABEL=${VERSION_LABEL}\n`);
+ });
+
it("answers 127 when the install has no update.sh, and does nothing without a request", () => {
expect(run(`id=u1\nimage=${IMAGE}\n`, { updater: false }).answer).toBe("id=u1\ncode=127\n");
const idle = run(null);
diff --git a/docs/design/self-hosted-design.md b/docs/design/self-hosted-design.md
index dbe7e95256..902ec88d29 100644
--- a/docs/design/self-hosted-design.md
+++ b/docs/design/self-hosted-design.md
@@ -24,9 +24,10 @@ A standalone server becomes connected by enrolling the connector. No reinstall,
- **Connector** (`connector/`): enrols with a one-time code, holds its own Ed25519 key, keeps one outbound WebSocket
and runs only a fixed job list. No shell, no command of its own choosing, no read of a file by path. In this
repository, so customers can read what it can do. It has two modes, chosen on the server when it enrols:
- - `customer-run`, for a server its owner installed: nine jobs (`start`, `stop`, `restart`, `update`, `status`,
- `backup`, `restore`, `host-health`, `self-update`), four requests it answers itself, and a reduced report. The
- whole list is `connector/src/customer-run.ts`. This is the mode of the Business self-hosted plan.
+ - `customer-run`, for a server its owner installed: seven jobs from us (`start`, `stop`, `restart`, `update`,
+ `status`, `backup`, `host-health`), two more that only root on the server may run (`self-update`, `restore`),
+ four requests it answers itself, and a reduced report. The whole list is `connector/src/customer-run.ts`. This is
+ the mode of the Business self-hosted plan.
- `operated`, for a server we run a Team Cloud on: those jobs plus `export-disk` and `import-disk`, a `start` that
carries the image and the settings, and the Admin's signed requests to the home, pairing among them.
- **Installer**: one script with a preflight. This repository.
@@ -106,6 +107,17 @@ Decided: the server installer brings MausBot; the connector attaches to that ins
- **Enforced on the server, three times over for jobs.** A job outside the list is refused as it arrives
(`checkCustomerRunJob`), again at the desk every job passes through (`jobDesk`), and the home the connector attached
to has no code path for it (`AdoptedHome`). Each refusal is a line in the audit log.
+- **We cannot replace the connector.** `self-update` from the Admin is refused in this mode: any older connector image
+ is still in our registry, and one from before the mode would run as `operated`. Only root on the server replaces
+ it (`mausbot-connector job self-update`), and even then not with an older version or one that names none
+ (`images.ts neverOlder`, on the image's version label).
+- **Updates only move forward.** An `update` to an image older than the one running, or without a version label, is
+ refused by the connector after it pulls the image and again by `mausbot-update-runner` on the host, which is the
+ check that cannot be bypassed from the connector's container. Going back is the owner's, with `update.sh` by hand.
+ `SERVER_VERSION_FLOOR` (and `FLOOR` in the runner; a test holds them equal) is a second floor, to be set to the
+ first release with the hardened profile; it is `0.0.0` until such a release exists.
+- **`restore` is the owner's**, and a backup the owner made is never removed to make room for ours: each sender keeps
+ its own three.
- **Requests never reach the home.** The connector answers the four listed requests itself from the facts it already
reports (`customer-run-requests.ts`). Everything else is answered 403 and logged.
- **The report is rebuilt, not filtered.** `reducedHeartbeat` and `reducedReply` copy named fields; every string is an
@@ -135,11 +147,11 @@ Backward compatible: a field is only ever added, and only by a customer-run serv
|---|---|---|
| `EnrollRequest` (`POST /api/cloud/box/v1/enroll`) | `mode: "customer-run"` | Present only for a customer-run server; absent means `operated`, exactly the request sent before. Store it with the box |
| `Heartbeat.heartbeat` | `mode: "customer-run"`, `paused: boolean`, `seats: number \| null` | Present only for a customer-run server. `host`, `home` and `connector` keep their shape; `host.checks[]` carries `id`, `ok` and `warning` without `fix`; `home.health.box` is always null |
-| `JobErrorCode` | `refused_by_mode`, `paused`, `update_unavailable`, `update_not_started` | Only from a customer-run server. Its error `message` is a fixed sentence per code |
+| `JobErrorCode` | `refused_by_mode`, `paused`, `update_unavailable`, `update_not_started`, `older_version` | Only from a customer-run server. Its error `message` is a fixed sentence per code |
For a customer-run box the Admin should: send `start` with no arguments; send `update` with
-`ghcr.io/milind-soni/openmausbot@sha256:…` (the server image, not the Cloud home image); never send `export-disk`,
-`import-disk` or a request other than `GET /v1/health`, `/v1/version`, `/v1/seats`, `/v1/update`; send
+`ghcr.io/milind-soni/openmausbot@sha256:…` (the server image, not the Cloud home image); never an older version than the one running; never send `export-disk`,
+`import-disk`, `self-update`, `restore` or a request other than `GET /v1/health`, `/v1/version`, `/v1/seats`, `/v1/update`; send
`schedule.image: null` in the signed config (a Cloud home image there is accepted, any other is ignored with the whole
config); and sign people in by sending them to the server's own address, never by pairing.
@@ -181,8 +193,15 @@ Read at the commit that adds the customer-run mode. "Built" means the code is in
message, the bot's name and recent log lines to us, and its status is asked hourly while it is open; browser
analytics are on until a person turns them off. Principle 6 is about the connector; these are the docs page's
"What your server itself still sends".
-- **`self-update` can replace the rules.** A new connector is new code from our registry, pinned by digest and not
- yet signed. The owner's policy file can leave `self-update` out on a customer-run server.
+- **Connector images are not signed.** Only the owner replaces the connector on a customer-run server, and never
+ with an older one, but what they install is trusted by its digest and our registry alone. Planned: a signing key's
+ public half built into the connector, the signature of the new image's digest checked in `images.ts` before it
+ runs (the `ImageCheck` hook is where it plugs in), and the same check in `connector/install.sh`.
+- **The hardened floor is not set.** The mechanism is built and tested; the number waits for the first release with
+ the hardened profile.
+- **A connector is updated by hand.** Since we cannot send `self-update`, a fix to the connector reaches a
+ customer-run server only when its owner runs it. The Admin should show which servers run an old connector.
+- **The WebSocket close reason is empty** from a customer-run server; the code says why.
- **Only one layout is adopted.** Docker Compose from the server installer, the published image, data in a folder. A
source build or an npm install cannot be connected.
- **The seat count is a lower bound for a domain entry.** `@example.com` on the sign-in list counts each person from