Skip to content

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

Own-server homes: trust only the tunnel to name a client, and start again after an unclean kill (#3727)

Milind Soni773bdc1f5c16
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 7f043894f9..5bf3a44206 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -267,6 +267,90 @@ jobs:
test "$(pair "$body" "$secret" "$(date +%s)" "$(rand43)")" = 200
docker rm -f home >/dev/null
docker volume rm omb-home-ci >/dev/null
+ - name: Cloud home on an own server trusts only its tunnel to name a client, and starts again after an unclean kill
+ # Without FLY_APP_NAME the home is on its own server, where any local process reaches the published port: only
+ # the tunnel, in the home's own network namespace, names the client (Cf-Connecting-IP from loopback), so a header
+ # forged through the port cannot reset the pairing lockout. With FLY_APP_NAME, Fly's proxy names it, as before.
+ # A SIGKILL leaves the server's lease on the volume; on one Docker host every container shares the boot id and
+ # its pids start again from 1. The same container and a new one both start again on that volume, and a second
+ # home beside a live one refuses to start.
+ run: |
+ set -euo pipefail
+ rand43() { openssl rand -base64 32 | tr '+/' '-_' | tr -d '=\n'; }
+ b64url() { base64 | tr '+/' '-_' | tr -d '=\n'; }
+ secret=$(rand43)
+ host=home.own-server.invalid
+ contract=(-e OMB_CLOUD_ROLE=home -e OMB_CLOUD_MACHINE_ID=7d1e2f3a-4b5c-4d6e-8f70-8192a3b4c5d6 -e OMB_CLOUD_ADMIN_URL=https://cloud.example.test
+ -e "OMB_PUBLIC_URL=https://$host" -e "OMB_CLOUD_BOOTSTRAP_SECRET=$secret" -e OMB_COMPOSIO_BROKER_URL=http://127.0.0.1:9 -e OMB_HIGHLEVEL_RELAY_URL=off)
+ run_home() { # name volume port [docker run options...]
+ local name=$1 volume=$2 port=$3; shift 3
+ docker run -d --name "$name" --init --stop-timeout 30 -p "127.0.0.1:$port:8080" -v "$volume:/data" "${contract[@]}" "$@" omb-cloud-home:ci >/dev/null
+ }
+ healthy() { # name port
+ for i in $(seq 1 45); do
+ curl -sf --max-time 2 "http://127.0.0.1:$2/api/health" | grep -q openmausbot && return 0
+ if [ "$(docker inspect -f '{{.State.Running}}' "$1")" != true ]; then docker logs "$1" 2>&1 | tail -20; echo "$1 exited"; return 1; fi
+ sleep 2
+ done
+ docker logs "$1" 2>&1 | tail -20; echo "$1 never became healthy"; return 1
+ }
+ # A pairing signed with a wrong key: it counts toward the lockout of the address the edge names (10 a minute).
+ bad_pair_headers() {
+ local ts nonce bh sig
+ ts=$(date +%s); nonce=$(rand43)
+ bh=$(printf '{}' | openssl dgst -sha256 -binary | b64url)
+ sig=$(printf 'v1\n%s\n%s\nPOST\n/api/cloud/pairing\n%s' "$ts" "$nonce" "$bh" | openssl dgst -sha256 -hmac "$(rand43)" -binary | b64url)
+ printf '%s\n' -H "Host: $host" -H 'content-type: application/json' -H "x-omb-cloud-timestamp: $ts" -H "x-omb-cloud-nonce: $nonce" -H "x-omb-cloud-signature: v1=$sig"
+ }
+ bad_pair() { # port [curl options...]: through the published port, from the host
+ local port=$1; shift; local signed; mapfile -t signed < <(bad_pair_headers)
+ curl -s -o /dev/null -w '%{http_code}' --max-time 5 -X POST "${signed[@]}" "$@" --data-binary '{}' "http://127.0.0.1:$port/api/cloud/pairing"
+ }
+ bad_pair_from_tunnel() { # name [curl options...]: from the home's own loopback, where the tunnel connects from
+ local name=$1; shift; local signed; mapfile -t signed < <(bad_pair_headers)
+ docker exec "$name" curl -s -o /dev/null -w '%{http_code}' --max-time 5 -X POST "${signed[@]}" "$@" --data-binary '{}' http://127.0.0.1:8080/api/cloud/pairing
+ }
+
+ # Own server: every request through the port counts against the port's one peer, whatever address it forges.
+ run_home own omb-own-ci 18081
+ healthy own 18081
+ for i in $(seq 1 10); do
+ test "$(bad_pair 18081 -H "Cf-Connecting-IP: 198.51.100.$i" -H "Fly-Client-IP: 203.0.113.$i" -H "X-Forwarded-For: 192.0.2.$i")" = 401
+ done
+ test "$(bad_pair 18081 -H 'Cf-Connecting-IP: 198.51.100.99' -H 'Fly-Client-IP: 203.0.113.99')" = 429
+ # The tunnel does name the client, so the person behind it is not locked out with the port's peer; Fly's header names nobody.
+ test "$(bad_pair_from_tunnel own -H 'Cf-Connecting-IP: 198.51.100.200')" = 401
+ test "$(bad_pair_from_tunnel own -H 'Fly-Client-IP: 203.0.113.200')" = 401
+ for i in $(seq 1 9); do bad_pair_from_tunnel own -H 'Fly-Client-IP: 203.0.113.201' >/dev/null; done
+ test "$(bad_pair_from_tunnel own -H 'Cf-Connecting-IP: 198.51.100.201')" = 401
+ test "$(bad_pair_from_tunnel own -H 'Fly-Client-IP: 203.0.113.202')" = 429
+
+ # Fly: the proxy's private address names the client in Fly-Client-IP, exactly as before.
+ run_home fly omb-fly-ci 18082 -e FLY_APP_NAME=omb-t-ci
+ healthy fly 18082
+ for i in $(seq 1 10); do test "$(bad_pair 18082 -H 'Fly-Client-IP: 203.0.113.7' -H "Cf-Connecting-IP: 198.51.100.$i")" = 401; done
+ test "$(bad_pair 18082 -H 'Fly-Client-IP: 203.0.113.7')" = 429
+ test "$(bad_pair 18082 -H 'Fly-Client-IP: 203.0.113.8')" = 401
+ docker rm -f fly >/dev/null
+ docker volume rm omb-fly-ci >/dev/null
+
+ # A SIGKILL leaves the server's lease behind; the same container starts again, and so does a new one.
+ docker kill -s KILL own >/dev/null
+ docker run --rm -v omb-own-ci:/data:ro --entrypoint test omb-cloud-home:ci -s /data/.openmausbot/openmausbot-server.lease
+ docker start own >/dev/null
+ healthy own 18081
+ docker kill -s KILL own >/dev/null
+ docker rm -f own >/dev/null
+ run_home own2 omb-own-ci 18081
+ healthy own2 18081
+ grep -q 7d1e2f3a-4b5c-4d6e-8f70-8192a3b4c5d6 <<<"$(docker run --rm -v omb-own-ci:/data:ro --entrypoint cat omb-cloud-home:ci /data/.omb-cloud-home.json)"
+ # A second home on the volume the live one holds refuses to start, and the live one carries on.
+ if timeout 90 docker run --name own3 -v omb-own-ci:/data "${contract[@]}" omb-cloud-home:ci; then echo "a second home started on a held volume"; exit 1; fi
+ grep -qF "Another MausBot home is already running on this volume. No data was changed." <<<"$(docker logs own3 2>&1)"
+ docker rm -f own3 >/dev/null
+ healthy own2 18081
+ docker rm -f own2 >/dev/null
+ docker volume rm omb-own-ci >/dev/null
- name: Prove each image ships its files once, no build cache, and a Caddy without capabilities
# A pull downloads every layer, so a file written twice or a cache left
# in a layer costs every machine that pulls the image. The Cloud home's
diff --git a/deploy/fly/Caddyfile b/deploy/fly/Caddyfile
index 62b111a1ac..792be88a24 100644
--- a/deploy/fly/Caddyfile
+++ b/deploy/fly/Caddyfile
@@ -1,5 +1,6 @@
# Edge for one OMB Cloud Pro home machine (docs/cloud-pro.md). Fly's proxy
-# terminates TLS for <app>.fly.dev and reaches this machine on :8080. The
+# terminates TLS for <app>.fly.dev and reaches this machine on :8080 (on an own
+# server, the Cloudflare tunnel does, in this home's network namespace). The
# OpenMausBot server listens only on 127.0.0.1, and every request forwarded
# to it carries X-Forwarded-*, so it is never the loopback owner
# (server/request-auth.ts): a remote client needs a paired session.
@@ -15,12 +16,15 @@
auto_https off
persist_config off
servers {
- # Fly's proxy connects from its private ranges and names the real
- # client in Fly-Client-IP. Only those peers may name a client; the
- # address feeds the pairing lockout, never authorization.
- trusted_proxies static private_ranges
+ # Only these peers may name the real client, and only in this header:
+ # Fly's proxy from its private ranges in Fly-Client-IP, or an own
+ # server's tunnel from this home's loopback in Cf-Connecting-IP (the
+ # launcher sets both: server/cloud-home-start.ts). Any other peer's
+ # header is ignored, and unset, no peer may name one. The address feeds
+ # the pairing lockout, never authorization.
+ trusted_proxies static {$OMB_CLOUD_EDGE_TRUSTED_PROXIES}
trusted_proxies_strict
- client_ip_headers Fly-Client-IP
+ client_ip_headers {$OMB_CLOUD_EDGE_CLIENT_IP_HEADER}
}
}
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 63d7b83014..731a6b5713 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1123,9 +1123,15 @@ differs from the previous one only in those (a few MB) unless Chrome, an
engine, Grok's pin, or the Node base image changed in between.
At boot the launcher, running as root, hands the volume's mount point to the
-`maus` user, binds the volume to this machine as `maus`
-(`/data/.omb-cloud-home.json`; another machine's volume, or an unmarked
-volume with data on it, is refused), and runs two children as `maus`: the
+`maus` user, locks the volume for as long as it runs (`flock` on the volume's
+root: a second home on a volume a live home holds refuses to start, which
+Docker on your own server does not prevent by itself), binds the volume to
+this machine as `maus` (`/data/.omb-cloud-home.json`; another machine's
+volume, or an unmarked volume with data on it, is refused), clears the
+data-directory lease records another machine or container left on it (a home
+killed uncleanly leaves one, and on one Docker host every container shares the
+boot id while its pids start again from 1, so the lease names its pid
+namespace and its process's start time too), and runs two children as `maus`: the
server on `127.0.0.1:8799` (webhooks on `127.0.0.1:8800`) and Caddy on
`:8080`. It stays a small root supervisor: if either child exits, both stop
and Fly restarts the machine. The one exception: after a restore commits
@@ -1226,10 +1232,14 @@ home as a service, never the owner (see above), and the server never binds
a public interface. Caddy
(`deploy/fly/Caddyfile`) forwards every request with `X-Forwarded-Proto:
https` and `X-Forwarded-For`, so the server sees each one as remote: it needs
-a paired session, whatever `Host` it claims. Caddy trusts `Fly-Client-IP`
-only from Fly's private ranges; that address feeds the pairing lockout, never
-authorization. Apart from `/api/health`, Caddy answers only for the machine's
-own name (`OMB_PUBLIC_URL`) and refuses any other `Host`.
+a paired session, whatever `Host` it claims. On Fly (`FLY_APP_NAME` is set),
+Caddy trusts `Fly-Client-IP` only from Fly's private ranges. On your own
+server, where any local process can reach the published port, it trusts
+`Cf-Connecting-IP` only from the home's own loopback, where the Cloudflare
+tunnel connects from, and ignores a client-address header from any other peer
+(the launcher sets both: `edgeClientAddress`). That address feeds the pairing
+lockout, never authorization. Apart from `/api/health`, Caddy answers only for
+the machine's own name (`OMB_PUBLIC_URL`) and refuses any other `Host`.
### Fly
diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjs
index 82aae4a51b..d2757bc2e9 100644
--- a/electron/data-dir-lease.mjs
+++ b/electron/data-dir-lease.mjs
@@ -1,6 +1,6 @@
import { execFileSync } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { hostname, uptime } from "node:os";
import { join } from "node:path";
@@ -68,6 +68,62 @@ function isBootIdentity(value) {
return value === null || (typeof value === "string" && normalizeBootId(value) === value);
}
+/**
+ * Containers on one host share its boot id, and each runs in a pid namespace of its own, where pids start again from 1:
+ * a new container's server is often given the very pid its dead predecessor recorded. A pid means something only in
+ * the namespace it was read in, so Linux records name theirs.
+ */
+let cachedPidNamespace;
+
+function readPidNamespace() {
+ if (process.platform !== "linux") return null;
+ try {
+ return /^pid:\[([1-9][0-9]{0,19})\]$/.exec(readlinkSync("/proc/self/ns/pid"))?.[1] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function pidNamespace() {
+ if (cachedPidNamespace === undefined) cachedPidNamespace = readPidNamespace();
+ return cachedPidNamespace;
+}
+
+function isPidNamespace(value) {
+ return value === null || (typeof value === "string" && /^[1-9][0-9]{0,19}$/.test(value));
+}
+
+/** Linux: when a process started, in clock ticks since boot (/proc/<pid>/stat field 22); null when unreadable. */
+function processStartTicks(pid) {
+ if (process.platform !== "linux") return null;
+ let stat;
+ try {
+ stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ } catch {
+ return null;
+ }
+ // Field 2, the command name, is in parentheses and may itself hold spaces and parentheses.
+ const ticks = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]);
+ return Number.isSafeInteger(ticks) && ticks >= 0 ? ticks : null;
+}
+
+function isStartTicks(value) {
+ return value === null || (Number.isSafeInteger(value) && value >= 0);
+}
+
+/** Who this process is beyond its pid: its pid namespace and when it started, so a reused pid is never taken for it. */
+function processIdentity() {
+ return { ns: pidNamespace(), start: processStartTicks(process.pid) };
+}
+
+/** Unless the record provably predates this boot, one made in another pid namespace belongs to another container. */
+function fromAnotherPidNamespace(record) {
+ const current = bootSession();
+ if (current !== null && typeof record.boot === "string" && record.boot !== current) return false;
+ const ns = pidNamespace();
+ return ns !== null && typeof record.ns === "string" && record.ns !== ns;
+}
+
function ownerPredatesThisBoot(owner) {
const current = bootSession();
if (current !== null && typeof owner.boot === "string") return owner.boot !== current;
@@ -83,13 +139,14 @@ function ownerIsAlive(owner) {
/** macOS renames the host on another network, so the same boot session (random per boot) also proves this machine. */
function sameMachine(record) {
+ if (fromAnotherPidNamespace(record)) return false;
if (record.host === hostname()) return true;
const boot = bootSession();
return boot !== null && typeof record.boot === "string" && record.boot === boot;
}
function otherMachineAdvice(path) {
- return ` If OpenMausBot is not running on another computer that shares this folder, quit OpenMausBot, delete ${JSON.stringify(path)} and start again.`;
+ return ` If OpenMausBot is not running on another computer or container that shares this folder, quit OpenMausBot, delete ${JSON.stringify(path)} and start again.`;
}
function isLeaseOwner(value) {
@@ -107,7 +164,9 @@ function isLeaseOwner(value) {
&& value.createdAt > 0
// Optional so an older build's lease stays readable during an upgrade.
&& (value.boot === undefined || isBootIdentity(value.boot))
- && (value.uptime === undefined || (Number.isInteger(value.uptime) && value.uptime >= 0));
+ && (value.uptime === undefined || (Number.isInteger(value.uptime) && value.uptime >= 0))
+ && (value.ns === undefined || isPidNamespace(value.ns))
+ && (value.start === undefined || isStartTicks(value.start));
}
function isReaperOwner(value, targetToken) {
@@ -202,8 +261,13 @@ function processCreationTimeMs(pid) {
return null;
}
-/** Windows reuses pids within a boot: a process created after the lease cannot be its original owner. */
+/** Pids are reused within a boot: a process that started at another moment, or after the lease, is not its owner. */
function ownerIdentityMatches(owner) {
+ if (process.platform === "linux") {
+ if (!Number.isSafeInteger(owner.start) || typeof owner.ns !== "string" || owner.ns !== pidNamespace()) return true;
+ const started = processStartTicks(owner.pid);
+ return started === null || started === owner.start;
+ }
if (process.platform !== "win32") return true;
const created = processCreationTimeMs(owner.pid);
if (created === null) return true;
@@ -255,6 +319,7 @@ function claimReaperAuthority(leasePath, expected) {
createdAt: Date.now(),
boot: bootSession(),
uptime: uptimeMs(),
+ ...processIdentity(),
targetToken: expected.token,
};
if (publishRecord(
@@ -402,6 +467,7 @@ function acquireDataDirLeaseInternal(dataDir, options = {}) {
createdAt: Date.now(),
boot: bootSession(),
uptime: uptimeMs(),
+ ...processIdentity(),
};
const candidatePath = `${leasePath}.candidate-${owner.pid}-${owner.token}`;
try {
@@ -475,10 +541,11 @@ export function acquireDataDirLease(dataDir, options = {}) {
}
/**
- * For a data directory whose disk only ever mounts on one machine at a time (a Cloud home's volume: server/cloud-home-start.ts),
- * where a record another machine wrote can never belong to a live process: removes every lease, delegated-child lease and
- * recovery record held by another machine and returns their holders. Records from this machine are left as they are:
- * acquireDataDirLease() refuses a live one and recovers a dead one. Never for a folder several computers share.
+ * For a data directory only one machine or container uses at a time (a Cloud home's volume, which its launcher holds
+ * locked: server/cloud-home-start.ts), where a record another one wrote can never belong to a live process: removes every
+ * lease, delegated-child lease and recovery record held by another machine or container and returns their holders.
+ * Records from this one are left as they are: acquireDataDirLease() refuses a live one and recovers a dead one. Never
+ * for a folder several computers share.
*/
export function clearRecordsFromOtherMachines(dataDir) {
validateDataDir(dataDir);
diff --git a/electron/data-dir-lease.node-test.mjs b/electron/data-dir-lease.node-test.mjs
index 366556acb7..4a4c07f09f 100644
--- a/electron/data-dir-lease.node-test.mjs
+++ b/electron/data-dir-lease.node-test.mjs
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { execFileSync, spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
import { hostname, tmpdir, uptime as osUptime } from "node:os";
import path from "node:path";
import test from "node:test";
@@ -430,6 +430,59 @@ test("a live owner from the current boot still blocks a second instance", () =>
assert.throws(() => acquireDataDirLease(dataDir), /already using this data directory/i);
});
+test("a Linux record names its pid namespace and when its process started; elsewhere both are null", () => {
+ const { dataDir } = temporaryDirectory();
+ const record = recordWrittenByThisProcess(dataDir);
+ if (process.platform !== "linux") {
+ assert.deepEqual({ ns: record.ns, start: record.start }, { ns: null, start: null });
+ return;
+ }
+ assert.equal(record.ns, /^pid:\[(\d+)\]$/.exec(readlinkSync("/proc/self/ns/pid"))[1]);
+ const stat = readFileSync("/proc/self/stat", "utf8");
+ assert.equal(record.start, Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]));
+});
+
+// Two containers on one host: the same boot, another pid namespace, and pids that start again from 1.
+const anotherPidNamespace = (current) => String(BigInt(current.ns) + 1n);
+
+test("a lease another container on this host left is never judged by this container's pids", (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.ns === null || current.boot === null) return t.skip("no pid namespace or boot identity on this platform");
+ // The new container's server got the pid the dead one recorded, here our own live pid.
+ const leasePath = plantOwner(dataDir, { ns: anotherPidNamespace(current), pid: process.pid, token: randomUUID() });
+ const planted = readFileSync(leasePath, "utf8");
+
+ assert.throws(() => acquireDataDirLease(dataDir), /already owned by a process on another machine/i);
+ assert.equal(readFileSync(leasePath, "utf8"), planted);
+ assert.deepEqual(clearRecordsFromOtherMachines(dataDir), [{ path: leasePath, host: current.host, pid: process.pid }]);
+ const lease = acquireDataDirLease(dataDir);
+ assert.equal(JSON.parse(readFileSync(leasePath, "utf8")).ns, current.ns);
+ assert.equal(lease.release(), true);
+});
+
+test("a pid this container reused for another process is not the lease's owner", (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.ns === null || current.start === null) return t.skip("no process start time on this platform");
+ plantOwner(dataDir, { pid: process.pid, start: current.start + 1, token: randomUUID() });
+
+ const lease = acquireDataDirLease(dataDir);
+ assert.equal(lease.ownerPid, process.pid);
+ assert.equal(lease.release(), true);
+});
+
+test("a lease this host left before a reboot is recovered whatever pid namespace wrote it", (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.ns === null || current.boot === null) return t.skip("no pid namespace or boot identity on this platform");
+ plantOwner(dataDir, { boot: randomUUID(), ns: anotherPidNamespace(current), pid: process.pid, token: randomUUID() });
+
+ const lease = acquireDataDirLease(dataDir);
+ assert.equal(lease.ownerPid, process.pid);
+ assert.equal(lease.release(), true);
+});
+
test("a reaper from an earlier boot is succeeded even when its pid is live", (t) => {
const { dataDir } = temporaryDirectory();
const current = recordWrittenByThisProcess(dataDir);
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index 4899844073..d5b01ec713 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -3,7 +3,7 @@
// loopback trust. Secrets never ride a child's environment (/proc/<pid>/environ stays readable by the same user): the
// server reads them from an inherited pipe. Root runs and trusts only the image's code, never the volume's.
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
-import { chmodSync, chownSync, existsSync, readFileSync, statSync, type Stats } from "node:fs";
+import { chmodSync, chownSync, closeSync, existsSync, openSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs";
import { dirname, join, posix, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
@@ -50,19 +50,64 @@ export function edgeHold(raw: string | undefined): string {
return match && Number(match[1]) <= 120 ? `${Number(match[1])}s` : "0s";
}
+/**
+ * Who may name the client to the edge, and in which header (deploy/fly/Caddyfile). On Fly only Fly's proxy reaches the
+ * edge, from its private ranges, and it overwrites Fly-Client-IP. On an own server any local process reaches the published
+ * port, so only the Cloudflare tunnel, running in this home's own network namespace, may name a client, in
+ * Cf-Connecting-IP; a header from any other peer is ignored. The address feeds the pairing lockout, never authorization.
+ */
+export function edgeClientAddress(env: NodeJS.ProcessEnv): { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: string; OMB_CLOUD_EDGE_TRUSTED_PROXIES: string } {
+ return env.FLY_APP_NAME?.trim()
+ ? { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "Fly-Client-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "private_ranges" }
+ : { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "Cf-Connecting-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "127.0.0.1/32 ::1/128" };
+}
+
/** The server's data directory on the volume. */
export function cloudHomeDataDir(env: NodeJS.ProcessEnv, home: string): string {
return env.OMB_DATA_DIR || posix.join(home, ".openmausbot");
}
+/** flock(1)'s exit status when another process holds the lock (its --conflict-exit-code). */
+const VOLUME_HELD = 75;
+const heldVolumes = new Set<string>();
+
+type VolumeLock = (fd: number) => { status: number | null; error?: Error; stderr?: string };
+
+const flockVolume: VolumeLock = (fd) => spawnSync("/usr/bin/flock", ["--exclusive", "--nonblock", "--conflict-exit-code", String(VOLUME_HELD), "3"],
+ { stdio: ["ignore", "ignore", "pipe", fd], encoding: "utf8", timeout: 10_000 });
+
+/**
+ * Locks the volume for as long as this process lives, or refuses: a second home on the same volume must never start.
+ * Docker lets any number of containers mount one volume, each in its own pid namespace, so no pid or lease record can
+ * tell a live home from a dead one; a kernel lock on the volume can, and the kernel drops it when this process dies.
+ * The lock is flock(2) on the volume's root, an inode `maus` cannot replace. flock(1) takes it on this process's own
+ * open descriptor, which keeps it after flock exits.
+ */
+export function holdVolume(home: string, lock: VolumeLock = flockVolume): void {
+ const root = realpathSync(home);
+ if (heldVolumes.has(root)) return;
+ const fd = openSync(root, "r");
+ const result = lock(fd);
+ if (result.status === 0) {
+ heldVolumes.add(root);
+ return;
+ }
+ closeSync(fd);
+ if (result.status === VOLUME_HELD) throw new Error("Another MausBot home is already running on this volume. No data was changed.");
+ const why = result.error?.message ?? (String(result.stderr ?? "").trim().split("\n")[0] || `exit ${result.status}`);
+ throw new Error(`This home could not lock its volume (${why}), so it will not start: another home might be using it. No data was changed.`);
+}
+
/**
- * Confirms the volume is this Cloud's (`prepareCloudHomeVolume`), then clears the data-directory records another machine
- * left on it. A Fly volume mounts on one machine at a time, and every home the Admin makes on a kept volume (a resume, a
- * restore, an export) is a new machine with a new hostname, so a lease from another machine is always stale here: one a
- * home destroyed mid-boot left (seen live Oct 23 2026) made every later home exit at once refusing it. A lease from this
- * machine is the server's own to refuse or recover. Returns what was cleared, for the log.
+ * Locks the volume (`holdVolume`), confirms it is this Cloud's (`prepareCloudHomeVolume`), then clears the data-directory
+ * records another machine or container left on it. With the volume locked no other home is running on it, and every
+ * home the Admin makes on a kept volume (a resume, a restore, an export; a new container on an own server) is another
+ * machine or container, so its records are always stale here: one a home destroyed mid-boot left (seen live Oct 23
+ * 2026) made every later home exit at once refusing it. A lease from this one is the server's own to refuse or recover.
+ * Returns what was cleared, for the log.
*/
-export function prepareCloudHomeData(home: string, dataDir: string, machineId: string) {
+export function prepareCloudHomeData(home: string, dataDir: string, machineId: string, lock: (home: string) => void = holdVolume) {
+ lock(home);
const volume = prepareCloudHomeVolume(home, machineId);
return { volume, cleared: clearRecordsFromOtherMachines(dataDir) };
}
@@ -86,6 +131,7 @@ export function cloudHomeChildEnvironments(config: CloudHomeConfig, env: NodeJS.
OMB_CLOUD_PUBLIC_HOST: cloudHomeHost(config),
// A plan whose home sleeps: requests wait this long for the server while it starts (deploy/fly/Caddyfile). Unset: 0s.
OMB_CLOUD_EDGE_HOLD: edgeHold(env.OMB_CLOUD_EDGE_HOLD),
+ ...edgeClientAddress(env),
};
return { server, edge, secrets: cloudHomeSecrets(env), dropped };
}
diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.ts
index 5578792b0d..a5dac5e417 100644
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@ -1,6 +1,8 @@
+import { spawn } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { hostname, tmpdir } from "node:os";
import { join, relative } from "node:path";
+import { pathToFileURL } from "node:url";
import type { IncomingMessage } from "node:http";
import { afterEach, expect, it } from "vitest";
import {
@@ -8,7 +10,7 @@ import {
cloudHomeHost, cloudHomeOffersPlace, cloudHomePlaceRefusal, cloudPairingSignature, cloudRequestSignature, createCloudPairing, firstCloudTurnPatch, prepareCloudHomeVolume,
withoutIgnoredCloudKeys,
} from "./cloud-home.ts";
-import { cloudHomeChildEnvironments, cloudHomeDataDir, codeTrustProblem, edgeHold, hardenHost, passwdIds, prepareCloudHomeData, spawnWithSecrets } from "./cloud-home-start.ts";
+import { cloudHomeChildEnvironments, cloudHomeDataDir, codeTrustProblem, edgeClientAddress, edgeHold, hardenHost, holdVolume, passwdIds, prepareCloudHomeData, spawnWithSecrets } from "./cloud-home-start.ts";
import { RESTART_EXIT_CODE, restartPolicy } from "./restart.ts";
import { hostedModelPolicy } from "./hosted-models.ts";
import { resolveRequestAuth } from "./request-auth.ts";
@@ -288,23 +290,77 @@ it("a new home on a kept volume clears the data-directory lease the previous mac
expect(cloudHomeDataDir({}, "/data")).toBe("/data/.openmausbot");
expect(cloudHomeDataDir({ OMB_DATA_DIR: "/elsewhere" }, home)).toBe("/elsewhere");
mkdirSync(join(home, "lost+found"));
- expect(prepareCloudHomeData(home, dataDir, "home-7f3k2")).toEqual({ volume: "new", cleared: [] });
+ const locked: string[] = [];
+ const lock = (volume: string) => { locked.push(volume); };
+ expect(prepareCloudHomeData(home, dataDir, "home-7f3k2", lock)).toEqual({ volume: "new", cleared: [] });
+ expect(locked).toEqual([home]);
// The lease the home destroyed mid-boot left (its hostname is Fly's machine id), and the previous machine's own pid.
const lease = join(dataDir, "openmausbot-server.lease");
mkdirSync(dataDir, { recursive: true });
const left = (host: string) => writeFileSync(lease, `${JSON.stringify({ version: 1, pid: 613, host, token: "0f5e6c4a-1b2c-4d3e-8f9a-0b1c2d3e4f5a", createdAt: 1, boot: "boot-of-the-old-machine", uptime: 44_000 })}\n`);
left("d8d9e0f1a2b3c4");
// Another Cloud's volume: refused before anything on it is read or changed.
- expect(() => prepareCloudHomeData(home, dataDir, "home-other")).toThrow(/another Cloud machine/);
+ expect(() => prepareCloudHomeData(home, dataDir, "home-other", lock)).toThrow(/another Cloud machine/);
expect(readFileSync(lease, "utf8")).toContain("d8d9e0f1a2b3c4");
- expect(prepareCloudHomeData(home, dataDir, "home-7f3k2")).toEqual({ volume: "existing", cleared: [{ path: lease, host: "d8d9e0f1a2b3c4", pid: 613 }] });
+ // A volume another live home holds: refused before the volume is even checked.
+ const held = () => { throw new Error("Another MausBot home is already running on this volume. No data was changed."); };
+ expect(() => prepareCloudHomeData(home, dataDir, "home-7f3k2", held)).toThrow(/already running on this volume/);
+ expect(readFileSync(lease, "utf8")).toContain("d8d9e0f1a2b3c4");
+ expect(prepareCloudHomeData(home, dataDir, "home-7f3k2", lock)).toEqual({ volume: "existing", cleared: [{ path: lease, host: "d8d9e0f1a2b3c4", pid: 613 }] });
expect(existsSync(lease)).toBe(false);
// This machine's own lease (its server restarted by the launcher): left for the server to refuse or recover.
left(hostname());
- expect(prepareCloudHomeData(home, dataDir, "home-7f3k2")).toEqual({ volume: "existing", cleared: [] });
+ expect(prepareCloudHomeData(home, dataDir, "home-7f3k2", lock)).toEqual({ volume: "existing", cleared: [] });
expect(readFileSync(lease, "utf8")).toContain(hostname());
});
+it("holds its volume for as long as it lives, and says plainly why it will not start on a volume it cannot hold", () => {
+ const home = directory();
+ const calls: number[] = [];
+ const answer = (status: number | null, extra: { error?: Error; stderr?: string } = {}) => (fd: number) => { calls.push(fd); return { status, ...extra }; };
+ expect(() => holdVolume(home, answer(75))).toThrow("Another MausBot home is already running on this volume. No data was changed.");
+ expect(() => holdVolume(home, answer(null, { error: new Error("spawnSync /usr/bin/flock ENOENT") }))).toThrow(/could not lock its volume \(spawnSync \/usr\/bin\/flock ENOENT\)/);
+ expect(() => holdVolume(home, answer(1, { stderr: "flock: 3: Bad file descriptor\n" }))).toThrow(/could not lock its volume \(flock: 3: Bad file descriptor\)/);
+ holdVolume(home, answer(0));
+ // Held once: the same process never locks its own volume again (the server restarts within one container).
+ holdVolume(home, answer(75));
+ expect(calls).toHaveLength(4);
+});
+
+it.skipIf(!existsSync("/usr/bin/flock"))("a second home on a volume a live home holds refuses to start, and once that home dies, even uncleanly, the volume is free", async () => {
+ const home = directory();
+ const holder = spawn(process.execPath, ["--no-warnings", "--experimental-strip-types", "--input-type=module", "--eval",
+ `const { holdVolume } = await import(${JSON.stringify(pathToFileURL(join(import.meta.dirname, "cloud-home-start.ts")).href)});
+ holdVolume(${JSON.stringify(home)}); process.stdout.write("held\\n"); setInterval(() => {}, 1000);`], { stdio: ["ignore", "pipe", "inherit"] });
+ try {
+ await new Promise<void>((resolve, reject) => {
+ holder.stdout.on("data", (chunk: Buffer) => { if (chunk.toString().includes("held")) resolve(); });
+ holder.once("exit", (code) => reject(new Error(`the holder exited ${code}`)));
+ });
+ expect(() => holdVolume(home)).toThrow("Another MausBot home is already running on this volume. No data was changed.");
+ } finally {
+ holder.kill("SIGKILL");
+ }
+ await new Promise((resolve) => holder.once("exit", resolve));
+ holdVolume(home);
+});
+
+it("lets only the tunnel name the client on an own server, and only Fly's proxy on Fly, exactly as before", () => {
+ const config = cloudHomeConfiguration(contract())!;
+ const own = cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin" }, "/data").edge;
+ expect(own).toMatchObject({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "Cf-Connecting-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "127.0.0.1/32 ::1/128" });
+ const fly = cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin", FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }, "/data").edge;
+ expect(fly).toMatchObject({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "Fly-Client-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "private_ranges" });
+ expect(edgeClientAddress({ FLY_APP_NAME: " " })).toEqual(edgeClientAddress({}));
+ // Both values are written into the edge's config as they are, so neither may come from anywhere but here.
+ for (const env of [{}, { FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }, { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Real-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "0.0.0.0/0" }]) {
+ const edge = cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin", ...env }, "/data").edge;
+ expect(edge.OMB_CLOUD_EDGE_CLIENT_IP_HEADER).toMatch(/^(?:Fly-Client-IP|Cf-Connecting-IP)$/);
+ expect(edge.OMB_CLOUD_EDGE_TRUSTED_PROXIES).toMatch(/^(?:private_ranges|127\.0\.0\.1\/32 ::1\/128)$/);
+ }
+ expect(cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin", FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }, "/data").server).not.toHaveProperty("OMB_CLOUD_EDGE_CLIENT_IP_HEADER");
+});
+
it("gives the edge only its routing name and the server the contract, never a gateway's settings or a secret", () => {
const relay = { OMB_CLOUD_BOAT_TOKEN: `box_omb_${"b".repeat(43)}`, OMB_CLOUD_VOICE_TOKEN: `omb_voice_${"v".repeat(43)}`, OMB_CLOUD_DECIDER_TOKEN: `omb_decide_${"d".repeat(43)}`,
OMB_CLOUD_AI_TOKEN: `omb_ai_${"a".repeat(43)}` };
@@ -392,6 +448,9 @@ it("ships an edge and a Fly template that keep the server private", () => {
expect(caddy.slice(homeStart, homeEnd)).toContain("handle /hooks/* {");
expect(caddy.match(/header_up X-Forwarded-For \{client_ip\}/g)).toHaveLength(upstreams.length);
expect(caddy.match(/lb_try_interval 50ms/g)).toHaveLength(upstreams.length);
+ // Who may name the client, and in which header, is the launcher's to say (edgeClientAddress); the file names neither.
+ expect(caddy).toMatch(/^\t\ttrusted_proxies static \{\$OMB_CLOUD_EDGE_TRUSTED_PROXIES\}\r?\n\t\ttrusted_proxies_strict\r?\n\t\tclient_ip_headers \{\$OMB_CLOUD_EDGE_CLIENT_IP_HEADER\}\r?\n/m);
+ expect(caddy.match(/^\s*(?:trusted_proxies|client_ip_headers)\b/gm)).toHaveLength(2);
// The root supervisor's code is root's, maus owns only the volume; the image's last step refuses to build otherwise.
const dockerfile = readFileSync(join(import.meta.dirname, "../Dockerfile"), "utf8");
const image = dockerfile.slice(dockerfile.indexOf("FROM runtime AS cloud-home"), dockerfile.indexOf("FROM runtime AS server"));
diff --git a/server/data-dir-lease.test.ts b/server/data-dir-lease.test.ts
index f6ff7bf54a..4ef706a748 100644
--- a/server/data-dir-lease.test.ts
+++ b/server/data-dir-lease.test.ts
@@ -60,9 +60,10 @@ describe("OpenMausBot data-directory lease", () => {
const stored = JSON.parse(readFileSync(join(dir, "openmausbot-server.lease"), "utf8"));
// boot/uptime identify which boot wrote the record, so a pid recycled
- // across a restart cannot be mistaken for a live owner. boot is null on
- // platforms that expose no boot id, so it is checked separately.
- const { boot, ...rest } = stored;
+ // across a restart cannot be mistaken for a live owner, and ns/start which
+ // pid namespace and process, so a container's reused pid cannot either.
+ // Each is null where the platform does not expose it.
+ const { boot, ns, start, ...rest } = stored;
expect(rest).toEqual({
version: 1,
pid: process.pid,
@@ -72,8 +73,9 @@ describe("OpenMausBot data-directory lease", () => {
uptime: expect.any(Number),
});
expect(boot === null || (typeof boot === "string" && boot.length > 0)).toBe(true);
+ expect(process.platform === "linux" ? /^[1-9]\d*$/.test(ns) && Number.isSafeInteger(start) : ns === null && start === null).toBe(true);
expect(Object.keys(stored).sort()).toEqual(
- ["boot", "createdAt", "host", "pid", "token", "uptime", "version"],
+ ["boot", "createdAt", "host", "ns", "pid", "start", "token", "uptime", "version"],
);
expect(() => acquireDataDirLease(dir)).toThrow(/already using this data directory/i);