Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud home edge: an optional fallback certificate CA when Let's Encrypt refuses (#5121)
Milind Soni3093b718b027
diff --git a/Dockerfile b/Dockerfileindex 46063d6786..270130e18f 100644--- a/Dockerfile+++ b/Dockerfile@@ -197,6 +197,7 @@ RUN export HOME=/tmp/omb-build-home \&& cloudflared 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 \+ && OMB_CLOUD_PUBLIC_HOST=validate.example.com OMB_CLOUD_EDGE_STORAGE=/tmp/omb-build-home/edge OMB_CLOUD_EDGE_CERT_ISSUERS="$([email protected] node --input-type=module -e 'import { edgeCertIssuers } from "/app/dist-server/cloud-home-start.js"; process.stdout.write(edgeCertIssuers(process.env));')" caddy validate --config /app/cloud/Caddyfile.tls --adapter caddyfile \&& OMB_CLOUD_PUBLIC_HOST=validate.example.com caddy validate --config /app/cloud/Caddyfile.tunnel --adapter caddyfile \&& test -f /app/dist-server/cloud-home-start.js \&& untrusted="$(find /app /usr/local/bin/caddy /usr/local/bin/cloudflared \( ! -user root -o ! -type l -perm /022 \) -print)" \diff --git a/deploy/fly/Caddyfile.tls b/deploy/fly/Caddyfile.tlsindex 5c6d056cef..b594d524ff 100644--- a/deploy/fly/Caddyfile.tls+++ b/deploy/fly/Caddyfile.tls@@ -1,7 +1,8 @@# 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+# edge gets and renews itself (a fallback CA's when Let's Encrypt refuses and+# the launcher names one). 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).@@ -11,6 +12,9 @@# 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}+ # Let's Encrypt alone, unless the launcher writes more here (edgeCertIssuers:+ # the fallback CA, from OMB_CLOUD_EDGE_ACME_EMAIL). Unset, this line is blank.+ {$OMB_CLOUD_EDGE_CERT_ISSUERS}servers {# HTTP/3 needs UDP 443, which the server does not open.protocols h1 h2diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex f1d6f9dd26..40d4747e32 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1285,6 +1285,7 @@ start.| --- | --- || `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_EDGE_ACME_EMAIL` | With `OMB_CLOUD_EDGE_TLS=1`: a fallback CA for when Let's Encrypt refuses a certificate (its rate limits, say). The address of the account ZeroSSL's ACME endpoint gets: Caddy creates that account by itself from the address, with no sign-up or key to set. Let's Encrypt stays first and keeps its own account, and whichever CA issued the certificate stays on the volume. Unset or empty: Let's Encrypt alone. Anything but one plain address stops the home with a message naming the variable. It has no default; the operator sets it. || `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`. || `OMB_CLOUD_TUNNEL_TOKEN` | For a server with no inbound port: the connector token of the home's own Cloudflare tunnel. `OMB_PUBLIC_URL` is then the tunnel's address. Not with `OMB_CLOUD_EDGE_TLS`. |diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex 89443e1033..204e29210f 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -74,6 +74,32 @@ export function edgeTerminatesTls(env: NodeJS.ProcessEnv): boolean {return raw === "1";}+/** ZeroSSL's ACME directory: Caddy makes the account there itself from an address, so the fallback needs no sign-up or key. */+const ZEROSSL_ACME_DIRECTORY = "https://acme.zerossl.com/v2/DV90";+/** The fallback account's address, as the Caddy option it becomes: plain ASCII, nothing Caddy would read as more. */+const ACME_EMAIL = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/;++/**+ * What Caddyfile.tls gets for OMB_CLOUD_EDGE_CERT_ISSUERS, when the home ends TLS itself: nothing (Caddy's default, Let's+ * Encrypt alone) until OMB_CLOUD_EDGE_ACME_EMAIL names the account for a fallback CA. Then Let's Encrypt first and ZeroSSL+ * after it, tried only when Let's Encrypt has just refused that certificate (50 new ones a week per registered domain).+ * Let's Encrypt keeps today's account, which has no address; only the fallback gets it. Either certificate stays on the+ * volume and is served and renewed from there, whichever CA issued it. OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY=1 uses the+ * fallback alone: for a live check that it issues (the Admin never sets it).+ */+export function edgeCertIssuers(env: NodeJS.ProcessEnv): string {+ const email = env.OMB_CLOUD_EDGE_ACME_EMAIL?.trim() ?? "";+ const only = env.OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY?.trim() ?? "";+ if (only !== "" && only !== "0" && only !== "1") invalidEdge("OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY must be 1 (only the fallback CA issues, for a live check of it) or 0");+ if (!email) {+ if (only === "1") invalidEdge("OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY needs OMB_CLOUD_EDGE_ACME_EMAIL: the fallback CA's account address");+ return "";+ }+ if (email.length > 254 || !ACME_EMAIL.test(email)) invalidEdge("OMB_CLOUD_EDGE_ACME_EMAIL must be one plain address, such as [email protected]");+ const fallback = `cert_issuer acme ${ZEROSSL_ACME_DIRECTORY} {\n\temail ${email}\n}`;+ return only === "1" ? fallback : `cert_issuer acme\n${fallback}`;+}+/*** OMB_CLOUD_TUNNEL_TOKEN: the connector token of this home's Cloudflare tunnel, for a server with no inbound port. The* home runs cloudflared itself and OMB_PUBLIC_URL is the tunnel's address. Only cloudflared ever reads the token.@@ -227,7 +253,7 @@ 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) } : {}),+ ...(edgeTerminatesTls(env) ? { OMB_CLOUD_EDGE_STORAGE: edgeCertificateStorage(home), OMB_CLOUD_EDGE_CERT_ISSUERS: edgeCertIssuers(env) } : {}),};return { server, edge, edgeFiles: edgeConfigFiles(env), tunnelToken: edgeTunnelToken(env), secrets: cloudHomeSecrets(env), dropped };}diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex 9a62b7c54a..78e57b6806 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -1,5 +1,5 @@-import { spawn } from "node:child_process";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { spawn, spawnSync } from "node:child_process";+import { copyFileSync, 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";@@ -11,7 +11,7 @@ import {withoutIgnoredCloudKeys,} from "./cloud-home.ts";import {- cloudHomeChildEnvironments, cloudHomeDataDir, codeTrustProblem, edgeClientAddress, edgeHold, hardenHost, hasCapability, holdVolume, passwdIds, prepareCloudHomeData,+ cloudHomeChildEnvironments, cloudHomeDataDir, codeTrustProblem, edgeCertIssuers, edgeClientAddress, edgeHold, hardenHost, hasCapability, holdVolume, passwdIds, prepareCloudHomeData,readCloudSecretsFile, setprivArgs, spawnWithSecrets,} from "./cloud-home-start.ts";import { RESTART_EXIT_CODE, restartPolicy } from "./restart.ts";@@ -409,6 +409,74 @@ it("gives the edge only its routing name and the server the contract, never a gaexpect(passwdIds("root:x:0:0::/root:/bin/sh\n", "maus")).toBeNull();});+// The fallback CA's address is written into the edge's config, so nothing but a plain address may reach it.+const fallbackIssuers = "cert_issuer acme\ncert_issuer acme https://acme.zerossl.com/v2/DV90 {\n\temail [email protected]\n}";++it("gives a home that ends TLS a fallback CA only when its operator names the account, Let's Encrypt first", () => {+ const config = cloudHomeConfiguration(contract({ OMB_CLOUD_EDGE_TLS: "1" }))!;+ const edge = (extra: NodeJS.ProcessEnv) => cloudHomeChildEnvironments(config, { ...contract({ OMB_CLOUD_EDGE_TLS: "1" }), PATH: "/usr/bin", ...extra }, "/data").edge;+ expect(edge({}).OMB_CLOUD_EDGE_CERT_ISSUERS).toBe("");+ expect(edge({ OMB_CLOUD_EDGE_ACME_EMAIL: "" }).OMB_CLOUD_EDGE_CERT_ISSUERS).toBe("");+ expect(edge({ OMB_CLOUD_EDGE_ACME_EMAIL: " " }).OMB_CLOUD_EDGE_CERT_ISSUERS).toBe("");+ expect(edge({ OMB_CLOUD_EDGE_ACME_EMAIL: " [email protected] " }).OMB_CLOUD_EDGE_CERT_ISSUERS).toBe(fallbackIssuers);+ // Let's Encrypt's issuer has no address, so it keeps the account it already has on the volume.+ expect(fallbackIssuers.split("\n")[0]).toBe("cert_issuer acme");+ expect(edge({ OMB_CLOUD_EDGE_ACME_EMAIL: "[email protected]", OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY: "1" }).OMB_CLOUD_EDGE_CERT_ISSUERS)+ .toBe("cert_issuer acme https://acme.zerossl.com/v2/DV90 {\n\temail [email protected]\n}");+ expect(edge({ OMB_CLOUD_EDGE_ACME_EMAIL: "[email protected]", OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY: "0" }).OMB_CLOUD_EDGE_CERT_ISSUERS).toBe(fallbackIssuers);+ // The address is the edge's alone: the server never gets it.+ expect(cloudHomeChildEnvironments(config, { ...contract({ OMB_CLOUD_EDGE_TLS: "1" }), PATH: "/usr/bin", OMB_CLOUD_EDGE_ACME_EMAIL: "[email protected]" }, "/data").server)+ .not.toHaveProperty("OMB_CLOUD_EDGE_ACME_EMAIL");+ // Without edge TLS (Fly, or a server where something else ends TLS) it is not read at all.+ for (const extra of [{}, { FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }]) {+ const flyEdge = cloudHomeChildEnvironments(cloudHomeConfiguration(contract())!, { ...contract(), PATH: "/usr/bin", OMB_CLOUD_EDGE_ACME_EMAIL: "not an address", ...extra }, "/data").edge;+ expect(flyEdge).not.toHaveProperty("OMB_CLOUD_EDGE_CERT_ISSUERS");+ expect(flyEdge).not.toHaveProperty("OMB_CLOUD_EDGE_ACME_EMAIL");+ }+});++it("refuses a fallback CA setting the edge's config would read as more", () => {+ const invalid = /OMB_CLOUD_EDGE_ACME_EMAIL must be one plain address/;+ for (const value of ["certs", "certs@", "@example.test", "certs@example", "[email protected]\ncert_issuer internal", "[email protected] {", "a [email protected]", "a@[email protected]", "#[email protected]", "<<[email protected]", "a\"@example.test", `a${"b".repeat(260)}@example.test`]) {+ expect(() => edgeCertIssuers({ OMB_CLOUD_EDGE_ACME_EMAIL: value }), value).toThrow(invalid);+ }+ expect(() => edgeCertIssuers({ OMB_CLOUD_EDGE_ACME_EMAIL: "[email protected]", OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY: "yes" })).toThrow(/must be 1/);+ expect(() => edgeCertIssuers({ OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY: "1" })).toThrow(/needs OMB_CLOUD_EDGE_ACME_EMAIL/);+ expect(edgeCertIssuers({ OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY: "0" })).toBe("");+ expect(edgeCertIssuers({})).toBe("");+});++// `caddy validate` on the real template with what the launcher writes. Needs a Caddy: OMB_CADDY_BIN or one on the PATH (the+// image's own 2.10.2 runs the same check at build, in the Dockerfile). Skipped when there is none.+const caddyBin = process.env.OMB_CADDY_BIN || (spawnSync("caddy", ["version"], { stdio: "ignore" }).status === 0 ? "caddy" : "");+it.skipIf(!caddyBin)("renders a Caddyfile.tls that Caddy accepts, with Let's Encrypt alone unless the setting is there", () => {+ const dir = directory();+ for (const file of ["Caddyfile.tls", "edge-routes.caddy"]) copyFileSync(join(import.meta.dirname, "../deploy/fly", file), join(dir, file));+ const base = { PATH: "/usr/bin:/bin", HOME: dir, XDG_DATA_HOME: join(dir, "data"), XDG_CONFIG_HOME: join(dir, "config"), OMB_CLOUD_PUBLIC_HOST: "validate.example.com",+ OMB_CLOUD_EDGE_STORAGE: join(dir, "edge"), OMB_CLOUD_EDGE_TRUSTED_PROXIES: "", OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Forwarded-For", OMB_CLOUD_EDGE_HOLD: "0s" };+ const run = (command: string, issuers?: string) => {+ const result = spawnSync(caddyBin, [command, "--config", join(dir, "Caddyfile.tls"), "--adapter", "caddyfile"], { encoding: "utf8", env: { ...base, ...(issuers === undefined ? {} : { OMB_CLOUD_EDGE_CERT_ISSUERS: issuers }) } });+ expect(result.status, result.stderr).toBe(0);+ return result;+ };+ const issuersOf = (issuers?: string) => (JSON.parse(run("adapt", issuers).stdout) as { apps: { tls?: { automation?: { policies?: { issuers?: unknown[] }[] } } } }).apps.tls?.automation?.policies?.[0]?.issuers;+ // Unset and empty: the same config as today, and it validates.+ expect(issuersOf()).toBeUndefined();+ expect(issuersOf("")).toBeUndefined();+ expect(issuersOf(edgeCertIssuers({}))).toBeUndefined();+ run("validate"); run("validate", "");+ // A formatting warning would come at every boot of every home.+ for (const issuers of [undefined, ""]) expect(run("adapt", issuers).stderr).not.toMatch(/not formatted/);+ // Set: Let's Encrypt first, with no address, then the fallback with its account's.+ const rendered = edgeCertIssuers({ OMB_CLOUD_EDGE_ACME_EMAIL: "[email protected]" });+ run("validate", rendered);+ expect(issuersOf(rendered)).toEqual([{ module: "acme" }, { ca: "https://acme.zerossl.com/v2/DV90", email: "[email protected]", module: "acme" }]);+ // The live check's setting: the fallback alone.+ const only = edgeCertIssuers({ OMB_CLOUD_EDGE_ACME_EMAIL: "[email protected]", OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY: "1" });+ run("validate", only);+ expect(issuersOf(only)).toEqual([{ ca: "https://acme.zerossl.com/v2/DV90", email: "[email protected]", module: "acme" }]);+});+it("holds requests at the edge while the server starts only when the Admin asked for it (a plan that sleeps)", () => {const config = cloudHomeConfiguration(withGateway())!;expect(cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin" }, "/data").edge.OMB_CLOUD_EDGE_HOLD).toBe("0s");@@ -473,6 +541,9 @@ it("ships an edge and a Fly template that keep the server private", () => {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);expect(edgeFile("Caddyfile.tunnel")).toMatch(/^:8080 \{\n\timport edge-routes\.caddy\n\}\n\n:8812 \{\n\tbind 127\.0\.0\.1\n\timport edge-routes\.caddy\n\}\n/m);+ // Only the edge that ends TLS issues certificates, and its issuers are the launcher's to say (edgeCertIssuers).+ expect(edgeFile("Caddyfile.tls").match(/^\t\{\$OMB_CLOUD_EDGE_CERT_ISSUERS\}$/gm)).toHaveLength(1);+ for (const config of [edgeFile("Caddyfile"), edgeFile("Caddyfile.tunnel")]) expect(config).not.toContain("OMB_CLOUD_EDGE_CERT_ISSUERS");// The tunnel's listener, on loopback alone, believes Cloudflare's header; :8080 believes only what the launcher says.expect(edgeFile("Caddyfile.tunnel")).toMatch(/^\tservers 127\.0\.0\.1:8812 \{\n\t\ttrusted_proxies static 127\.0\.0\.1\/32\n\t\ttrusted_proxies_strict\n\t\tclient_ip_headers Cf-Connecting-IP\n\t\}$/m);expect(edgeFile("Caddyfile.tunnel").match(/^\s*(?:trusted_proxies|client_ip_headers)\b/gm)).toHaveLength(4);@@ -502,6 +573,8 @@ it("ships an edge and a Fly template that keep the server private", () => {expect(check).toBeGreaterThan(image.lastIndexOf("COPY "));expect(check).toBeLessThan(image.indexOf("CMD ["));expect(image).toContain("COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/Caddyfile.tunnel deploy/fly/edge-routes.caddy /app/cloud/");+ // The build's own Caddy validates Caddyfile.tls as the launcher renders it with a fallback CA.+ expect(image).toContain('OMB_CLOUD_EDGE_CERT_ISSUERS="$([email protected] node --input-type=module -e \'import { edgeCertIssuers } from "/app/dist-server/cloud-home-start.js"; process.stdout.write(edgeCertIssuers(process.env));\')" caddy validate --config /app/cloud/Caddyfile.tls');// 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/);