Skip to content

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

Team on your own server: the home serves HTTPS on its own domain, and only named proxies name a client

milind-soni7264e45a0741
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 181a593af0..c9ad18853c 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -223,7 +223,7 @@ jobs:
if docker exec -u maus home grep -qaF -- "$value" "/proc/$spid/environ"; then echo "a secret is in the server's environment"; exit 1; fi
done
# The root launcher runs only code maus cannot change; maus owns only the volume.
- docker exec -u maus home sh -c 'for f in /app /app/dist-server /app/dist-server/index.js /app/dist-server/cloud-home-start.js /app/cloud/Caddyfile /usr/local/bin/caddy; do if test -w "$f"; then echo "maus can write $f"; exit 1; fi; done; test -w /data'
+ docker exec -u maus home sh -c 'for f in /app /app/dist-server /app/dist-server/index.js /app/dist-server/cloud-home-start.js /app/cloud/Caddyfile /app/cloud/Caddyfile.tls /app/cloud/edge-routes.caddy /usr/local/bin/caddy; do if test -w "$f"; then echo "maus can write $f"; exit 1; fi; done; test -w /data'
test "$(docker exec home stat -c %U /app/dist-server/index.js)" = root
# The shell tools bots use on a Cloud, as the user their engines run as.
docker exec -u maus home sh -c 'python3 -c "import json, sqlite3, zipfile, csv" && pdftotext -v 2>&1 | grep -q pdftotext && unzip -v | grep -q UnZip'
@@ -267,10 +267,11 @@ 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.
+ - name: Cloud home on an own server names a client only through its owner's proxies, serves its own domain, 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 and a
+ # bot reaches the edge's loopback: by default nobody names the client, so a forged header cannot reset the pairing
+ # lockout. Proxies the owner names (OMB_CLOUD_TRUSTED_PROXIES) do, in their header. OMB_CLOUD_EDGE_TLS=1 makes the
+ # edge serve 443 for the home's name, its certificate on the volume. With FLY_APP_NAME, Fly's proxy names it.
# 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.
@@ -306,24 +307,68 @@ jobs:
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
+ bad_pair_inside() { # name [curl options...]: from the home's own loopback, where its bots are
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.
+ # Own server: every request counts against its own peer, whatever address it forges, through the port or inside.
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
+ test "$(bad_pair 18081 -H 'Cf-Connecting-IP: 198.51.100.99' -H 'X-Forwarded-For: 192.0.2.99')" = 429
+ # The loopback inside is another peer, so it is not locked out with the port's; its headers name nobody either.
+ for i in $(seq 1 10); do
+ test "$(bad_pair_inside own -H "Cf-Connecting-IP: 198.51.100.$((i + 100))" -H "X-Forwarded-For: 192.0.2.$((i + 100))")" = 401
+ done
+ test "$(bad_pair_inside own -H 'Cf-Connecting-IP: 198.51.100.250')" = 429
+
+ # Proxies the owner names: here the Docker bridge the published port arrives from. Each client they name is
+ # counted on its own; a header from the loopback, which is not named, still names nobody.
+ bridge=$(docker network inspect bridge -f '{{(index .IPAM.Config 0).Subnet}}')
+ run_home proxied omb-proxied-ci 18083 -e "OMB_CLOUD_TRUSTED_PROXIES=$bridge"
+ healthy proxied 18083
+ for i in $(seq 1 10); do test "$(bad_pair 18083 -H 'X-Forwarded-For: 192.0.2.10')" = 401; done
+ test "$(bad_pair 18083 -H 'X-Forwarded-For: 192.0.2.10')" = 429
+ test "$(bad_pair 18083 -H 'X-Forwarded-For: 192.0.2.11')" = 401
+ test "$(bad_pair 18083 -H 'X-Forwarded-For: 192.0.2.10, 192.0.2.12')" = 401 # only the proxy's own hop counts
+ test "$(bad_pair 18083 -H 'Cf-Connecting-IP: 192.0.2.11')" = 401 # no header: the proxy itself
+ for i in $(seq 1 10); do bad_pair_inside proxied -H "X-Forwarded-For: 192.0.2.$((i + 20))" >/dev/null; done
+ test "$(bad_pair_inside proxied -H 'X-Forwarded-For: 192.0.2.40')" = 429
+ docker rm -f proxied >/dev/null
+ docker volume rm omb-proxied-ci >/dev/null
+ # A setting that would let any client name itself, or that the edge's config would read as more, never serves.
+ for bad in "OMB_CLOUD_TRUSTED_PROXIES=0.0.0.0/0" "OMB_CLOUD_TRUSTED_PROXIES=10.0.0.1}" "OMB_CLOUD_CLIENT_IP_HEADER=X-Real-IP"; do
+ if timeout 60 docker run --name home-bad -v omb-bad-ci:/data "${contract[@]}" -e "$bad" omb-cloud-home:ci; then echo "$bad served"; exit 1; fi
+ grep -q "Cloud home configuration is invalid" <<<"$(docker logs home-bad 2>&1)"
+ docker rm -f home-bad >/dev/null
+ done
+ docker volume rm omb-bad-ci >/dev/null
+
+ # Its own domain: the edge serves 443 as well as :8080, from Caddyfile.tls, and keeps its certificate on the
+ # volume, so a restart serves the same one. Caddy issues an .internal name from its own local CA: no CA is asked.
+ run_home tls omb-tls-ci 18084 -e OMB_CLOUD_EDGE_TLS=1 -e OMB_PUBLIC_URL=https://home.own-server.internal
+ healthy tls 18084
+ grep -qF "caddy run --config /app/cloud/Caddyfile.tls --adapter caddyfile" <<<"$(docker top tls -eo pid,uid,args)"
+ served() { # name: the certificate the edge serves on 443, once it answers there
+ for i in $(seq 1 30); do
+ if docker exec "$1" curl -sfk --max-time 2 --resolve home.own-server.internal:443:127.0.0.1 https://home.own-server.internal/api/health | grep -q openmausbot; then
+ docker exec "$1" sh -c 'echo | openssl s_client -connect 127.0.0.1:443 -servername home.own-server.internal 2>/dev/null | openssl x509 -noout -fingerprint -sha256'
+ return 0
+ fi
+ sleep 1
+ done
+ docker logs "$1" 2>&1 | tail -20; echo "$1 never served 443"; return 1
+ }
+ first=$(served tls)
+ docker run --rm -v omb-tls-ci:/data:ro --entrypoint sh omb-cloud-home:ci -c 'ls /data/.omb-edge/caddy/certificates/*/home.own-server.internal/home.own-server.internal.crt'
+ docker restart tls >/dev/null
+ healthy tls 18084
+ test "$(served tls)" = "$first"
+ docker rm -f tls >/dev/null
+ docker volume rm omb-tls-ci >/dev/null
# 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
diff --git a/Dockerfile b/Dockerfile
index 17ba3ff51d..31df980aa9 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -169,7 +169,7 @@ ARG ENGINES_CACHE_TAG=""
RUN echo "engines: ${CLOUD_HOME_ENGINES:-none} ${ENGINES_CACHE_TAG}" \
&& if [ -n "$CLOUD_HOME_ENGINES" ]; then HOME=/tmp/omb-build-home npm install -g $CLOUD_HOME_ENGINES; fi \
&& rm -rf /tmp/omb-build-home /tmp/node-compile-cache
-COPY deploy/fly/Caddyfile /app/cloud/Caddyfile
+COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/edge-routes.caddy /app/cloud/
# The root supervisor runs /app's code and hands the server its secrets, so
# no file there may be one `maus` can change: unlike the server image's, these
# copies stay root's. Only the /data volume is maus's; the launcher refuses to
@@ -181,9 +181,10 @@ COPY --from=build /src/dist ./dist
# The bundled skills (server/skill-library.ts reads ./skills from /app).
COPY --from=build /src/skills ./skills
RUN export HOME=/tmp/omb-build-home \
- && chmod go-w /app/cloud /app/cloud/Caddyfile \
+ && chmod go-w /app/cloud /app/cloud/Caddyfile /app/cloud/Caddyfile.tls /app/cloud/edge-routes.caddy \
&& caddy version \
&& OMB_CLOUD_PUBLIC_HOST=validate.fly.dev caddy validate --config /app/cloud/Caddyfile --adapter caddyfile \
+ && OMB_CLOUD_PUBLIC_HOST=validate.example.com OMB_CLOUD_EDGE_STORAGE=/tmp/omb-build-home/edge caddy validate --config /app/cloud/Caddyfile.tls --adapter caddyfile \
&& test -f /app/dist-server/cloud-home-start.js \
&& untrusted="$(find /app /usr/local/bin/caddy \( ! -user root -o ! -type l -perm /022 \) -print)" \
&& if [ -n "$untrusted" ]; then echo "not root's, or writable by others:" >&2; echo "$untrusted" >&2; exit 1; fi \
diff --git a/deploy/fly/Caddyfile b/deploy/fly/Caddyfile
index 792be88a24..3c2f42b944 100644
--- a/deploy/fly/Caddyfile
+++ b/deploy/fly/Caddyfile
@@ -1,9 +1,9 @@
-# Edge for one OMB Cloud Pro home machine (docs/cloud-pro.md). Fly's proxy
+# Edge for one OMB Cloud home machine (docs/cloud-pro.md). Fly's proxy
# 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.
+# server, the connector does, or a proxy of the owner's). 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.
#
# OMB_CLOUD_EDGE_HOLD (a duration, unset: 0s, as before): how long a request
# waits for the server while it starts, instead of a 502. The Admin sets it
@@ -17,11 +17,11 @@
persist_config off
servers {
# 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.
+ # Fly's proxy from its private ranges in Fly-Client-IP, or on an own
+ # server the proxies its owner names (the launcher sets both:
+ # server/cloud-home-start.ts). Any other peer's header is ignored, and
+ # with none named, 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 {$OMB_CLOUD_EDGE_CLIENT_IP_HEADER}
@@ -29,43 +29,5 @@
}
:8080 {
- encode zstd gzip
-
- # Fly's health check reaches the machine by address, not by name.
- handle /api/health {
- reverse_proxy 127.0.0.1:8799 {
- lb_try_duration {$OMB_CLOUD_EDGE_HOLD:0s}
- lb_try_interval 50ms
- header_up X-Forwarded-Proto https
- header_up X-Forwarded-For {client_ip}
- }
- }
-
- # Everything else answers only for this machine's own public name.
- @home host {$OMB_CLOUD_PUBLIC_HOST}
- handle @home {
- # Webhook ingress has its own per-hook secrets.
- handle /hooks/* {
- reverse_proxy 127.0.0.1:8800 {
- lb_try_duration {$OMB_CLOUD_EDGE_HOLD:0s}
- lb_try_interval 50ms
- header_up X-Forwarded-Proto https
- header_up X-Forwarded-For {client_ip}
- }
- }
- handle {
- reverse_proxy 127.0.0.1:8799 {
- lb_try_duration {$OMB_CLOUD_EDGE_HOLD:0s}
- lb_try_interval 50ms
- header_up X-Forwarded-Proto https
- header_up X-Forwarded-For {client_ip}
- # the event stream must not be buffered
- flush_interval -1
- }
- }
- }
-
- handle {
- respond 403
- }
+ import edge-routes.caddy
}
diff --git a/deploy/fly/Caddyfile.tls b/deploy/fly/Caddyfile.tls
new file mode 100644
index 0000000000..5c6d056cef
--- /dev/null
+++ b/deploy/fly/Caddyfile.tls
@@ -0,0 +1,29 @@
+# Edge for a Cloud home on a server with its own domain (docs/cloud-pro.md, "On
+# your own server"): the same routes as Caddyfile on :8080, for the connector,
+# and on 443 for OMB_PUBLIC_URL's name, with a Let's Encrypt certificate this
+# edge gets and renews itself. TLS-ALPN answers the challenge on 443, so port
+# 80 is optional. Clients reach 443 directly, so the client address is the TCP
+# peer unless the owner names a proxy (the launcher sets these values:
+# server/cloud-home-start.ts).
+{
+ admin off
+ persist_config off
+ # On the volume: an update or a rollback is a new container, and Let's
+ # Encrypt issues the same name at most 5 times a week.
+ storage file_system {$OMB_CLOUD_EDGE_STORAGE}
+ servers {
+ # HTTP/3 needs UDP 443, which the server does not open.
+ protocols h1 h2
+ trusted_proxies static {$OMB_CLOUD_EDGE_TRUSTED_PROXIES}
+ trusted_proxies_strict
+ client_ip_headers {$OMB_CLOUD_EDGE_CLIENT_IP_HEADER}
+ }
+}
+
+http://:8080 {
+ import edge-routes.caddy
+}
+
+{$OMB_CLOUD_PUBLIC_HOST} {
+ import edge-routes.caddy
+}
diff --git a/deploy/fly/edge-routes.caddy b/deploy/fly/edge-routes.caddy
new file mode 100644
index 0000000000..ea1dacc54b
--- /dev/null
+++ b/deploy/fly/edge-routes.caddy
@@ -0,0 +1,41 @@
+# What the home's edge answers, imported by each of its configs: Caddyfile (Fly, or a server where something else ends
+# TLS) and Caddyfile.tls (a server with its own domain).
+encode zstd gzip
+
+# Fly's health check reaches the machine by address, not by name.
+handle /api/health {
+ reverse_proxy 127.0.0.1:8799 {
+ lb_try_duration {$OMB_CLOUD_EDGE_HOLD:0s}
+ lb_try_interval 50ms
+ header_up X-Forwarded-Proto https
+ header_up X-Forwarded-For {client_ip}
+ }
+}
+
+# Everything else answers only for this machine's own public name.
+@home host {$OMB_CLOUD_PUBLIC_HOST}
+handle @home {
+ # Webhook ingress has its own per-hook secrets.
+ handle /hooks/* {
+ reverse_proxy 127.0.0.1:8800 {
+ lb_try_duration {$OMB_CLOUD_EDGE_HOLD:0s}
+ lb_try_interval 50ms
+ header_up X-Forwarded-Proto https
+ header_up X-Forwarded-For {client_ip}
+ }
+ }
+ handle {
+ reverse_proxy 127.0.0.1:8799 {
+ lb_try_duration {$OMB_CLOUD_EDGE_HOLD:0s}
+ lb_try_interval 50ms
+ header_up X-Forwarded-Proto https
+ header_up X-Forwarded-For {client_ip}
+ # the event stream must not be buffered
+ flush_interval -1
+ }
+ }
+}
+
+handle {
+ respond 403
+}
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 6c37a5249b..1910e96001 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1062,8 +1062,10 @@ the `list_shared_computers` and `shared_computer` tools.
The `Dockerfile`'s `cloud-home` target shares the server image's runtime
layers (Node, Chrome's libraries, agent-browser and its Chrome) and adds:
-- Caddy (`deploy/fly/Caddyfile`), as the only listener the network can reach
- (`0.0.0.0:8080`);
+- Caddy, as the only listener the network can reach: `0.0.0.0:8080` with
+ `deploy/fly/Caddyfile`, and also 443 for the home's own domain with
+ `deploy/fly/Caddyfile.tls` (both import the same routes,
+ `deploy/fly/edge-routes.caddy`);
- Grok Build (`/usr/local/bin/grok`) from xAI's own installer, pinned by
`GROK_VERSION` to the version the Grok driver is verified against. The
build fails if the installer cannot be reached, rather than shipping an
@@ -1238,12 +1240,64 @@ a public interface. Caddy
https` and `X-Forwarded-For`, so the server sees each one as remote: it needs
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`.
+server, where any local process can reach the published port and a bot can
+reach the edge's loopback, it trusts no client-address header by default: the
+client is the connection's peer. Only proxies the owner names may name one
+(below). The launcher sets these values (`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`.
+
+### On your own server: how people reach it
+
+A home on a server of its owner's (Team on your own server) runs the same
+image. Its agent on the server sets these, with the boot contract below, on the
+home's container. None of them may be set on Fly: the launcher refuses to
+start.
+
+| Variable | Value |
+| --- | --- |
+| `OMB_PUBLIC_URL` | `https://` and the name people use, e.g. `https://mausbot.acme.eu`. Its DNS points at the server. |
+| `OMB_CLOUD_EDGE_TLS` | `1`: the edge gets and renews a Let's Encrypt certificate for that name and serves it on 443. Unset or `0`: the edge serves only `:8080`, for the agent, and something else ends TLS. |
+| `OMB_CLOUD_TRUSTED_PROXIES` | Only when the owner's own proxy stands in front: its addresses or ranges (`10.0.0.5`, `10.0.0.0/24`, `private_ranges`), separated by spaces or commas, at most 32. Unset: none. A `/0` range, a host name or anything else stops the home with a message naming the variable. |
+| `OMB_CLOUD_CLIENT_IP_HEADER` | The header those proxies put the client's address in. Default `X-Forwarded-For`; it needs `OMB_CLOUD_TRUSTED_PROXIES`. |
+
+**Its own domain (`OMB_CLOUD_EDGE_TLS=1`).** The agent publishes the
+container's 443 (and 80 if the owner opens it). Let's Encrypt checks the name
+over TLS on 443 (TLS-ALPN), so port 80 is optional; a certificate took 6 to 8 s
+in tests. Clients reach 443 directly, so the edge counts each by its own
+address with no header at all, and the agent's requests, which arrive through
+`127.0.0.1:8080` from the Docker bridge, are counted apart from any stranger
+on 443. The certificate and the ACME account live on the volume, in
+`/data/.omb-edge/caddy`, outside the server's data folder (no workspace backup
+or export carries the key) and never in `/tmp`: an update or a rollback is a
+new container, and Let's Encrypt issues the same name at most 5 times a week.
+The edge speaks HTTP/1.1 and HTTP/2 only, so UDP 443 stays closed.
+
+Docker gives a container on its default bridge no IPv6 address, and then
+forwards IPv6 clients of a port published on `[::]` through its own proxy,
+from the bridge's gateway, `172.17.0.1`: the address the agent's requests come
+from. Measured on Docker 29: ten wrong codes from one IPv6 client made the
+Admin's next signed pairing answer 429. So the agent publishes 443 on IPv4
+only (`0.0.0.0`) and the name has no AAAA record, unless the home's Docker
+network has IPv6 of its own (not verified).
+
+**The owner's own proxy in front.** It ends TLS and forwards to the home's
+`:8080` (published where the proxy can reach it). Name it in
+`OMB_CLOUD_TRUSTED_PROXIES` and, if it does not use `X-Forwarded-For`, its
+header in `OMB_CLOUD_CLIENT_IP_HEADER`, or every member shares one lockout:
+ten wrong codes from anyone would also refuse the Admin's own pairings for a
+minute. A proxy on the same host reaches a published port from the Docker
+bridge's gateway (usually `172.17.0.1`), which the agent shares. Only the
+named peers are believed, and only the last address they add, so a client's
+own `X-Forwarded-For` or `Cf-Connecting-IP` changes nothing.
+
+**Private, on a tailnet.** `tailscale serve --bg --https=443
+http://127.0.0.1:8080` on the server serves `https://<machine>.<tailnet>.ts.net`
+to the tailnet; set `OMB_PUBLIC_URL` to that name, and name the bridge's
+gateway in `OMB_CLOUD_TRUSTED_PROXIES` so each member's tailnet address is
+counted apart. The Admin never needs that address: its requests come through
+the agent. Not verified on a tailnet.
### Fly
diff --git a/server/cloud-home-address.test.ts b/server/cloud-home-address.test.ts
new file mode 100644
index 0000000000..5593c28793
--- /dev/null
+++ b/server/cloud-home-address.test.ts
@@ -0,0 +1,127 @@
+import { mkdtempSync } from "node:fs";
+import type { IncomingMessage } from "node:http";
+import { tmpdir } from "node:os";
+import { join, posix } from "node:path";
+import { afterEach, expect, it } from "vitest";
+import { cloudHomeConfiguration, cloudRequestSignature, createCloudPairing } from "./cloud-home.ts";
+import {
+ cloudHomeChildEnvironments, edgeCertificateStorage, edgeClientAddress, edgeConfigFiles, edgeTerminatesTls, OWN_SERVER_EDGE_KEYS, trustedProxyList,
+} from "./cloud-home-start.ts";
+import { requestSource } from "./request-auth.ts";
+import { LOCKOUT, SessionRegistry } from "./sessions.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+const directories: string[] = [];
+afterEach(async () => { for (const directory of directories.splice(0)) await removeTempDir(directory); });
+
+const secret = "S".repeat(43);
+const ownServer = (extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv => ({
+ OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: "team-1", OMB_CLOUD_TEAM_NAME: "Acme", OMB_CLOUD_MACHINE_ID: "box-1a2b3c",
+ OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_PUBLIC_URL: "https://mausbot.acme.example", OMB_CLOUD_BOOTSTRAP_SECRET: secret,
+ PATH: "/usr/bin", ...extra,
+});
+const edgeOf = (env: NodeJS.ProcessEnv, home = "/data") => cloudHomeChildEnvironments(cloudHomeConfiguration(env)!, env, home);
+
+it("takes the owner's proxies as addresses or ranges, and refuses anything else the edge's config would read as more", () => {
+ expect(trustedProxyList(undefined)).toEqual([]);
+ expect(trustedProxyList(" ")).toEqual([]);
+ expect(trustedProxyList("10.0.0.5, 172.17.0.1\n192.168.0.0/16 2001:db8::1 fd00::/8 private_ranges"))
+ .toEqual(["10.0.0.5/32", "172.17.0.1/32", "192.168.0.0/16", "2001:db8::1/128", "fd00::/8", "private_ranges"]);
+ for (const bad of [
+ "0.0.0.0/0", "::/0", "10.0.0.0/33", "fd00::/129", "10.0.0.0/", "10.0.0.0/8/8", "10.0.0.0/x", "proxy.acme.example", "10.0.0.256",
+ "10.0.0.1}\nrespond 200", "{$OMB_CLOUD_BOOTSTRAP_SECRET}", "10.0.0.1;", "*",
+ ]) expect(() => trustedProxyList(bad), bad).toThrow(/OMB_CLOUD_TRUSTED_PROXIES/);
+ expect(() => trustedProxyList(Array.from({ length: 33 }, (_, i) => `10.0.0.${i}`).join(" "))).toThrow(/more than 32/);
+});
+
+it("trusts no client-address header on an own server by default, and only the named proxies' header when set", () => {
+ expect(edgeClientAddress({})).toEqual({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Forwarded-For", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "" });
+ expect(edgeClientAddress({ OMB_CLOUD_TRUSTED_PROXIES: "172.17.0.1" }))
+ .toEqual({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Forwarded-For", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "172.17.0.1/32" });
+ expect(edgeClientAddress({ OMB_CLOUD_TRUSTED_PROXIES: "10.1.2.0/24", OMB_CLOUD_CLIENT_IP_HEADER: "X-Real-IP" }))
+ .toEqual({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Real-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "10.1.2.0/24" });
+ expect(() => edgeClientAddress({ OMB_CLOUD_CLIENT_IP_HEADER: "Cf-Connecting-IP" })).toThrow(/needs OMB_CLOUD_TRUSTED_PROXIES/);
+ for (const header of ["X-Forwarded-For X-Real-IP", "X-Real-IP}", "-X", "X_Real_IP", "x".repeat(65)]) {
+ expect(() => edgeClientAddress({ OMB_CLOUD_TRUSTED_PROXIES: "10.0.0.1", OMB_CLOUD_CLIENT_IP_HEADER: header }), header).toThrow(/one header name/);
+ }
+ // The edge's own names are the launcher's to write; set from outside, they change nothing.
+ expect(edgeOf(ownServer({ OMB_CLOUD_EDGE_TRUSTED_PROXIES: "0.0.0.0/0", OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Real-IP" })).edge)
+ .toMatchObject({ OMB_CLOUD_EDGE_TRUSTED_PROXIES: "", OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Forwarded-For" });
+ // Fly's proxy ends TLS and names the client there, so an own server's settings on Fly are a mistake that stops the start.
+ for (const key of OWN_SERVER_EDGE_KEYS) {
+ expect(() => edgeClientAddress({ FLY_APP_NAME: "omb-u-1a2b3c4d5e6f", [key]: "1" }), key).toThrow(new RegExp(`${key} is for a home on its own server`));
+ }
+});
+
+it("serves HTTPS on the home's own domain only when asked, with the certificate on the volume", () => {
+ expect(edgeTerminatesTls({})).toBe(false);
+ expect(edgeTerminatesTls({ OMB_CLOUD_EDGE_TLS: "0" })).toBe(false);
+ expect(edgeTerminatesTls({ OMB_CLOUD_EDGE_TLS: " 1 " })).toBe(true);
+ for (const raw of ["true", "yes", "2"]) expect(() => edgeTerminatesTls({ OMB_CLOUD_EDGE_TLS: raw }), raw).toThrow(/OMB_CLOUD_EDGE_TLS must be 1/);
+
+ const plain = edgeOf(ownServer());
+ expect(plain.edgeFiles).toEqual({ config: "/app/cloud/Caddyfile", routes: "/app/cloud/edge-routes.caddy" });
+ expect(plain.edge).not.toHaveProperty("OMB_CLOUD_EDGE_STORAGE");
+
+ const tls = edgeOf(ownServer({ OMB_CLOUD_EDGE_TLS: "1" }));
+ expect(tls.edgeFiles).toEqual({ config: "/app/cloud/Caddyfile.tls", routes: "/app/cloud/edge-routes.caddy" });
+ expect(tls.edge.OMB_CLOUD_PUBLIC_HOST).toBe("mausbot.acme.example");
+ // A new container (an update, a rollback, a restart on a new host) finds the same certificate; Let's Encrypt issues
+ // one name at most 5 times a week.
+ expect(tls.edge.OMB_CLOUD_EDGE_STORAGE).toBe("/data/.omb-edge/caddy");
+ expect(posix.relative("/data", tls.edge.OMB_CLOUD_EDGE_STORAGE!)).not.toMatch(/^\.\.|^\//);
+ expect(tls.edge.OMB_CLOUD_EDGE_STORAGE).not.toMatch(/^\/tmp\//);
+ expect(edgeCertificateStorage("/srv/home")).toBe("/srv/home/.omb-edge/caddy");
+ // Never in the server's data folder: a workspace backup or export must not carry the site's private key.
+ expect(posix.relative(tls.server.OMB_DATA_DIR!, tls.edge.OMB_CLOUD_EDGE_STORAGE!)).toMatch(/^\.\.\//);
+ expect(tls.server).not.toHaveProperty("OMB_CLOUD_EDGE_TLS");
+ expect(tls.server).not.toHaveProperty("OMB_CLOUD_EDGE_STORAGE");
+
+ expect(edgeConfigFiles({ OMB_CLOUD_EDGE_CONFIG: "/etc/omb-edge/Caddyfile", OMB_CLOUD_EDGE_TLS: "1" }))
+ .toEqual({ config: "/etc/omb-edge/Caddyfile", routes: "/etc/omb-edge/edge-routes.caddy" });
+ expect(() => edgeOf(ownServer({ OMB_CLOUD_EDGE_TLS: "on" }))).toThrow(/OMB_CLOUD_EDGE_TLS/);
+});
+
+/** A request as the server receives it: the edge on loopback, with X-Forwarded-For set to the address it trusts. */
+const fromEdge = (client: string) =>
+ // SAFETY: only headers and the socket peer are read
+ ({ headers: { "x-forwarded-for": client, "x-forwarded-proto": "https" }, method: "POST", socket: { remoteAddress: "127.0.0.1" } }) as unknown as IncomingMessage;
+const direct = (peer: string, headers: Record<string, string>) =>
+ // SAFETY: only headers and the socket peer are read
+ ({ headers, method: "POST", socket: { remoteAddress: peer } }) as unknown as IncomingMessage;
+
+it("counts each client behind the edge on its own: one stranger's wrong codes lock out neither a member nor the Admin", () => {
+ const directory = mkdtempSync(join(tmpdir(), "omb-cloud-address-"));
+ directories.push(directory);
+ let now = 1_800_000_000_000;
+ const sessions = new SessionRegistry({ file: join(directory, "sessions.json"), now: () => now });
+ const team = { id: "team-1", name: "Acme" };
+ const pairing = createCloudPairing({ secret, sessions, team, now: () => now });
+ const adminPairs = (source: string) => {
+ const body = Buffer.from(JSON.stringify({ label: "Phone", team: { id: team.id }, member: { email: "[email protected]", role: "member" } }));
+ const timestamp = String(Math.floor(now / 1000)), nonce = `nonce-${now}-${source}`.replace(/[^\w-]/g, "-");
+ const signature = `v1=${cloudRequestSignature(secret, timestamp, nonce, "POST", "/api/cloud/pairing", body)}`;
+ return pairing.handle({ timestamp, nonce, signature, body, source });
+ };
+
+ const stranger = requestSource(fromEdge("203.0.113.7"));
+ for (let i = 0; i < LOCKOUT.failures; i++) expect(sessions.exchange({ code: "AAAAAAAAAAAA", label: "", source: stranger }).ok).toBe(false);
+ expect(sessions.exchange({ code: "AAAAAAAAAAAA", label: "", source: stranger })).toMatchObject({ ok: false, status: 429 });
+
+ // The Admin's request reaches the edge through the agent, whose address the edge names like any other.
+ const admin = adminPairs(requestSource(fromEdge("172.17.0.1")));
+ expect(admin.status).toBe(200);
+ const member = requestSource(fromEdge("198.51.100.20"));
+ expect(sessions.exchange({ code: "AAAAAAAAAAAA", label: "", source: member })).toMatchObject({ ok: false, status: 401 });
+ expect(sessions.exchange({ code: String(admin.body.code), label: "Phone", source: member }).ok).toBe(true);
+
+ // The edge is the only loopback peer: a forwarded header from any other peer names nobody, so a stranger who forges
+ // a new address on each try is still one source.
+ const spoofed = new Set(Array.from({ length: 5 }, (_, i) => requestSource(direct("203.0.113.9", { "x-forwarded-for": `10.9.9.${i}`, "cf-connecting-ip": `10.8.8.${i}` }))));
+ expect([...spoofed]).toEqual(["203.0.113.9"]);
+ // Only the edge's own hop counts: a client's forged X-Forwarded-For comes before it.
+ expect(requestSource(fromEdge("10.9.9.9, 203.0.113.7"))).toBe(stranger);
+
+ now += LOCKOUT.lockMs + 1;
+ expect(adminPairs(stranger).status).toBe(200);
+});
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index 6c79fa257d..c2a7a774a2 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -4,6 +4,7 @@
// 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, closeSync, existsSync, openSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs";
+import { isIP } from "node:net";
import { dirname, join, posix, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
@@ -51,16 +52,75 @@ export function edgeHold(raw: string | undefined): string {
return match && Number(match[1]) <= 120 ? `${Number(match[1])}s` : "0s";
}
+/** How a home on its owner's server is reached (docs/cloud-pro.md, "On your own server"); never set on Fly. */
+export const OWN_SERVER_EDGE_KEYS = ["OMB_CLOUD_EDGE_TLS", "OMB_CLOUD_TRUSTED_PROXIES", "OMB_CLOUD_CLIENT_IP_HEADER"] as const;
+const EDGE_CONFIG_DIR = "/app/cloud";
+export const EDGE_ROUTES_FILE = "edge-routes.caddy";
+const MAX_TRUSTED_PROXIES = 32;
+
+function invalidEdge(why: string): never {
+ throw new Error(`Cloud home configuration is invalid: ${why}.`);
+}
+
+const onFly = (env: NodeJS.ProcessEnv) => Boolean(env.FLY_APP_NAME?.trim());
+
+/** OMB_CLOUD_EDGE_TLS=1: the edge gets and renews the certificate for OMB_PUBLIC_URL's name and serves it on 443. */
+export function edgeTerminatesTls(env: NodeJS.ProcessEnv): boolean {
+ const raw = env.OMB_CLOUD_EDGE_TLS?.trim() ?? "";
+ if (raw !== "" && raw !== "0" && raw !== "1") invalidEdge("OMB_CLOUD_EDGE_TLS must be 1 (the home serves HTTPS on its own domain) or 0");
+ return raw === "1";
+}
+
+/**
+ * The proxies an owner puts in front of the home, from OMB_CLOUD_TRUSTED_PROXIES: addresses, CIDR ranges or Caddy's
+ * `private_ranges`, separated by spaces or commas. Each is written into the edge's config as a token, so anything else is
+ * refused; so is a /0 range, which would let any client name itself and step round the pairing lockout.
+ */
+export function trustedProxyList(raw: string | undefined): string[] {
+ const entries = (raw ?? "").split(/[\s,]+/).filter(Boolean);
+ if (entries.length > MAX_TRUSTED_PROXIES) invalidEdge(`OMB_CLOUD_TRUSTED_PROXIES names more than ${MAX_TRUSTED_PROXIES} proxies`);
+ return entries.map((entry) => {
+ if (entry === "private_ranges") return entry;
+ const [address, prefix, extra] = entry.split("/");
+ const family = isIP(address ?? "");
+ const bits = family === 4 ? 32 : 128;
+ const width = prefix === undefined ? bits : /^\d{1,3}$/.test(prefix) ? Number(prefix) : NaN;
+ if (!family || extra !== undefined || !(width >= 1 && width <= bits)) {
+ invalidEdge(`OMB_CLOUD_TRUSTED_PROXIES must list proxy addresses or ranges such as 10.0.0.5 or 10.0.0.0/24 ("${entry.slice(0, 64)}" is not one, and /0 is refused)`);
+ }
+ return `${address}/${width}`;
+ });
+}
+
/**
* 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.
+ * edge, from its private ranges, and it overwrites Fly-Client-IP. On an own server nobody may: the client is the TCP
+ * peer, so a header from a stranger, a local process or a bot is ignored. Only the proxies its owner names in
+ * OMB_CLOUD_TRUSTED_PROXIES may, in OMB_CLOUD_CLIENT_IP_HEADER (X-Forwarded-For unless set). 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" };
+ if (onFly(env)) {
+ const set = OWN_SERVER_EDGE_KEYS.filter((key) => env[key]?.trim());
+ if (set.length) invalidEdge(`${set.join(", ")} ${set.length === 1 ? "is" : "are"} for a home on its own server; on Fly, Fly's proxy ends TLS and names the client`);
+ return { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "Fly-Client-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "private_ranges" };
+ }
+ const proxies = trustedProxyList(env.OMB_CLOUD_TRUSTED_PROXIES);
+ const header = env.OMB_CLOUD_CLIENT_IP_HEADER?.trim() ?? "";
+ if (header && !/^[A-Za-z0-9][A-Za-z0-9-]{0,63}$/.test(header)) invalidEdge("OMB_CLOUD_CLIENT_IP_HEADER must be one header name, such as X-Forwarded-For");
+ if (header && !proxies.length) invalidEdge("OMB_CLOUD_CLIENT_IP_HEADER needs OMB_CLOUD_TRUSTED_PROXIES: the proxies allowed to send it");
+ return { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: header || "X-Forwarded-For", OMB_CLOUD_EDGE_TRUSTED_PROXIES: proxies.join(" ") };
+}
+
+/** The edge's config, and the file every config imports: both run as root's trusted code. */
+export function edgeConfigFiles(env: NodeJS.ProcessEnv): { config: string; routes: string } {
+ const config = env.OMB_CLOUD_EDGE_CONFIG || posix.join(EDGE_CONFIG_DIR, edgeTerminatesTls(env) ? "Caddyfile.tls" : "Caddyfile");
+ return { config, routes: posix.join(posix.dirname(config), EDGE_ROUTES_FILE) };
+}
+
+/** Where the edge keeps its certificate and ACME account: on the volume, never /tmp, so a new container reuses them. */
+export function edgeCertificateStorage(home: string): string {
+ return posix.join(home, ".omb-edge", "caddy");
}
/** The server's data directory on the volume. */
@@ -133,8 +193,9 @@ export function cloudHomeChildEnvironments(config: CloudHomeConfig, env: NodeJS.
// 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),
+ ...(edgeTerminatesTls(env) ? { OMB_CLOUD_EDGE_STORAGE: edgeCertificateStorage(home) } : {}),
};
- return { server, edge, secrets: cloudHomeSecrets(env), dropped };
+ return { server, edge, edgeFiles: edgeConfigFiles(env), secrets: cloudHomeSecrets(env), dropped };
}
/** What root does to the machine before anything runs as `maus` (docs/bot-box.md, "What each layer stops"): /proc hides
@@ -190,6 +251,7 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {
// Logged here once: the server child never sees what they are about.
for (const warning of config.warnings) console.warn(`cloud home: ${warning}`);
const home = env.HOME || "/data";
+ const { server, edge, edgeFiles, secrets, dropped } = cloudHomeChildEnvironments(config, env, home);
const prepare = () => prepareCloudHomeData(home, cloudHomeDataDir(env, home), config.machineId);
let prepared: ReturnType<typeof prepare>;
let ids: { uid: number; gid: number } | null = null;
@@ -215,12 +277,10 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {
for (const record of prepared.cleared) console.log(`cloud home: cleared a stale data-directory record machine ${record.host} (process ${record.pid}) left on this volume: ${record.path}`);
const here = dirname(fileURLToPath(import.meta.url));
const edgeBin = env.OMB_CLOUD_EDGE_BIN || "/usr/local/bin/caddy";
- const edgeConfig = env.OMB_CLOUD_EDGE_CONFIG || "/app/cloud/Caddyfile";
if (ids) {
- const problem = codeTrustProblem([process.execPath, fileURLToPath(import.meta.url), join(here, "index.js"), edgeBin, edgeConfig], home);
+ const problem = codeTrustProblem([process.execPath, fileURLToPath(import.meta.url), join(here, "index.js"), edgeBin, edgeFiles.config, edgeFiles.routes], home);
if (problem) throw new Error(`This image's code is not safe to run as root: ${problem}. Rebuild it with docker build --target cloud-home.`);
}
- const { server, edge, secrets, dropped } = cloudHomeChildEnvironments(config, env, home);
// Names only, never values: what the server does not get from here.
if (dropped.length) console.log(`cloud home: not passed to the server: ${dropped.join(", ")}`);
const children: ChildProcess[] = [];
@@ -250,7 +310,7 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {
});
};
runServer();
- watch(spawnWithOomScore(OOM_SCORE.edge, () => spawn(edgeBin, ["run", "--config", edgeConfig, "--adapter", "caddyfile"],
+ watch(spawnWithOomScore(OOM_SCORE.edge, () => spawn(edgeBin, ["run", "--config", edgeFiles.config, "--adapter", "caddyfile"],
{ env: edge, stdio: "inherit", ...(ids ? { uid: ids.uid, gid: ids.gid } : {}) })));
process.once("SIGTERM", () => stop(false));
process.once("SIGINT", () => stop(false));
diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.ts
index f9e5d67577..87c1bc3c29 100644
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@ -345,18 +345,18 @@ it.skipIf(!existsSync("/usr/bin/flock"))("a second home on a volume a live home
holdVolume(home);
});
-it("lets only the tunnel name the client on an own server, and only Fly's proxy on Fly, exactly as before", () => {
+it("lets nobody name the client on an own server unless its owner names a proxy, and only Fly's proxy on Fly", () => {
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" });
+ expect(own).toMatchObject({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Forwarded-For", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "" });
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.
+ // Both values are written into the edge's config as they are, so the edge's own names are never taken from outside.
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(edge.OMB_CLOUD_EDGE_CLIENT_IP_HEADER).toMatch(/^(?:Fly-Client-IP|X-Forwarded-For)$/);
+ expect(edge.OMB_CLOUD_EDGE_TRUSTED_PROXIES).toMatch(/^(?:private_ranges|)$/);
}
expect(cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin", FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }, "/data").server).not.toHaveProperty("OMB_CLOUD_EDGE_CLIENT_IP_HEADER");
});
@@ -436,8 +436,19 @@ it("the root supervisor runs and trusts only root's code, never the volume's or
});
it("ships an edge and a Fly template that keep the server private", () => {
- const caddy = readFileSync(join(import.meta.dirname, "../deploy/fly/Caddyfile"), "utf8");
- expect(caddy).toMatch(/^:8080 \{/m);
+ const edgeFile = (name: string) => readFileSync(join(import.meta.dirname, "../deploy/fly", name), "utf8");
+ const caddy = edgeFile("edge-routes.caddy");
+ expect(edgeFile("Caddyfile")).toMatch(/^:8080 \{\n\timport edge-routes\.caddy\n\}\n/m);
+ expect(edgeFile("Caddyfile")).toMatch(/^\tauto_https off$/m);
+ expect(edgeFile("Caddyfile.tls")).toMatch(/^http:\/\/:8080 \{\n\timport edge-routes\.caddy\n\}\n\n\{\$OMB_CLOUD_PUBLIC_HOST\} \{\n\timport edge-routes\.caddy\n\}\n/m);
+ for (const config of [edgeFile("Caddyfile"), edgeFile("Caddyfile.tls")]) {
+ expect(config.match(/^(?!#)\S[^\n]* \{$/gm)?.length, "every site imports the same routes").toBe(config.match(/^\timport edge-routes\.caddy$/gm)?.length);
+ expect(config).not.toMatch(/reverse_proxy|respond/);
+ // Who may name the client, and in which header, is the launcher's to say (edgeClientAddress); no file names either.
+ expect(config).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(config.match(/^\s*(?:trusted_proxies|client_ip_headers)\b/gm)).toHaveLength(2);
+ }
+ expect(caddy).not.toMatch(/trusted_proxies|client_ip_headers/);
const upstreams = [...caddy.matchAll(/reverse_proxy (\S+)/g)].map(match => match[1]);
expect(new Set(upstreams)).toEqual(new Set(["127.0.0.1:8799", "127.0.0.1:8800"]));
expect(caddy).toMatch(/handle \/hooks\/\* \{\s*reverse_proxy 127\.0\.0\.1:8800 \{/);
@@ -448,9 +459,6 @@ 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"));
@@ -458,7 +466,7 @@ it("ships an edge and a Fly template that keep the server private", () => {
expect(image.slice(check)).toMatch(/^untrusted=.*\n && if \[ -n "\$untrusted" \]; then .*exit 1; fi \\\n/);
expect(check).toBeGreaterThan(image.lastIndexOf("COPY "));
expect(check).toBeLessThan(image.indexOf("CMD ["));
- expect(image).toContain("COPY deploy/fly/Caddyfile /app/cloud/Caddyfile");
+ expect(image).toContain("COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/edge-routes.caddy /app/cloud/");
// The bot box (server/bot-box) needs bubblewrap and socat in the image; pnpm is what bots' projects ask for.
expect(image).toMatch(/apt-get install -y --no-install-recommends [^\n]*\bbubblewrap\b[^\n]*\bsocat\b/);
expect(image).toMatch(/npm install -g pnpm@10\.33\.0/);