From b1fb77401ad883c4e1ef7ce6c0bc7ecb74dbabc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 02:22:09 +0000 Subject: [PATCH 01/65] feat(selfhost): one-box compose stack, Caddy, frps and object store (L22c) Brings the box runtime from the integration branch in plaintext mode: celld, Caddy, frps, the bundled object store, the mail collector and sam-mx. Without the egress fence, key agent, docker proxy and metadata proxy (and the files only they read: celld.env, egress-fence.nft, key-agent/agent.env, celld/start.sh), and without the key-rotation Caddy fragment. F11: the two local images (caddy, sam-mx) are never pulled (pull_policy: never) and are built only by an explicit `docker compose build` or when missing. The Caddy Dockerfile pins both images by digest and both modules by version, fetches modules only from proxy.golang.org with sum.golang.org verification and GOTOOLCHAIN=local, and fails unless the binary carries exactly those versions. Its build context is empty (.dockerignore), so Caddyfile edits never touch the build. F21: the gateway-route variant matcher reads the raw request target and accepts any encoding depth of every character of "api" and "self-host", backslash separators and absolute-form targets (L1), matches only an "api" segment followed by a "self-host" segment instead of any path containing "self-host" (L6), refuses dot-segment targets naming self-host in any encoding, and caddy-ratelimit limits frp connections per client address (L7, SAM_FRP_LOGIN_RATE_LIMIT_*). start.sh refuses any box port inside the lease range, as compose actually runs it (L5). Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/.env.example | 116 +++++++ deploy/selfhost/caddy/.dockerignore | 3 + deploy/selfhost/caddy/Caddyfile | 65 ++++ deploy/selfhost/caddy/Dockerfile | 38 +++ deploy/selfhost/caddy/keep-warm/off.caddy | 1 + deploy/selfhost/caddy/keep-warm/on.caddy | 31 ++ deploy/selfhost/caddy/log-redaction.caddy | 27 ++ .../selfhost/caddy/mail-collector/off.caddy | 1 + deploy/selfhost/caddy/mail-collector/on.caddy | 16 + deploy/selfhost/caddy/sam.d/frp.caddy | 66 ++++ deploy/selfhost/caddy/sam.d/node-ws.caddy | 104 ++++++ deploy/selfhost/caddy/start.sh | 85 +++++ .../caddy/tls/dns-googleclouddns.caddy | 12 + deploy/selfhost/caddy/tls/internal.caddy | 2 + deploy/selfhost/docker-compose.yml | 323 ++++++++++++++++++ deploy/selfhost/frps/frps.toml | 45 +++ deploy/selfhost/objectstore/init.sh | 11 + .../selfhost/caddy-logging-compose.test.ts | 117 +++++++ scripts/selfhost/caddy-start.test.ts | 92 +++++ .../selfhost/mail-collector-compose.test.ts | 69 ++++ scripts/selfhost/versions.test.ts | 83 ++++- scripts/selfhost/vitest.config.ts | 4 +- 22 files changed, 1309 insertions(+), 2 deletions(-) create mode 100644 deploy/selfhost/.env.example create mode 100644 deploy/selfhost/caddy/.dockerignore create mode 100644 deploy/selfhost/caddy/Caddyfile create mode 100644 deploy/selfhost/caddy/Dockerfile create mode 100644 deploy/selfhost/caddy/keep-warm/off.caddy create mode 100644 deploy/selfhost/caddy/keep-warm/on.caddy create mode 100644 deploy/selfhost/caddy/log-redaction.caddy create mode 100644 deploy/selfhost/caddy/mail-collector/off.caddy create mode 100644 deploy/selfhost/caddy/mail-collector/on.caddy create mode 100644 deploy/selfhost/caddy/sam.d/frp.caddy create mode 100644 deploy/selfhost/caddy/sam.d/node-ws.caddy create mode 100644 deploy/selfhost/caddy/start.sh create mode 100644 deploy/selfhost/caddy/tls/dns-googleclouddns.caddy create mode 100644 deploy/selfhost/caddy/tls/internal.caddy create mode 100644 deploy/selfhost/docker-compose.yml create mode 100644 deploy/selfhost/frps/frps.toml create mode 100644 deploy/selfhost/objectstore/init.sh create mode 100644 scripts/selfhost/caddy-logging-compose.test.ts create mode 100644 scripts/selfhost/caddy-start.test.ts create mode 100644 scripts/selfhost/mail-collector-compose.test.ts diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example new file mode 100644 index 0000000000..281fcefcb0 --- /dev/null +++ b/deploy/selfhost/.env.example @@ -0,0 +1,116 @@ +# EXPERIMENTAL single-box install for the SAM team's test box (README.md). Not a supported +# deployment option. +# +# Copy to .env, then `chmod 600 .env`: the bucket credential below controls the whole install +# (celld keeps Worker secrets in plaintext in the bucket's deploy manifests). + +# Base domain. Point a wildcard DNS record *.SAM_DOMAIN at this box. SAM serves api., app., +# ws-. and ws---. under it; the apex is not used. +SAM_DOMAIN=sam.example.com + +# TLS: `internal` (Caddy's local CA, local proofs only) or `dns-googleclouddns` (Let's Encrypt +# wildcard via DNS-01; needs GCP_PROJECT, and the VM's service account must be able to edit the +# Cloud DNS zone). Other providers: add caddy/tls/dns-.caddy and set CADDY_DNS_MODULE. +# ACME_EMAIL is optional (empty registers an account with no contact address). Set ACME_CA to +# https://acme-staging-v02.api.letsencrypt.org/directory for a first trial issuance, then unset +# it (Let's Encrypt production) and restart caddy. +SAM_TLS_MODE=internal +ACME_EMAIL= +# ACME_CA= +GCP_PROJECT= +# CADDY_DNS_MODULE=github.com/caddy-dns/googleclouddns@v1.1.0 + +# Optional services: `tunnel` runs frps for nodes; `local-store` runs the bundled object store +# (trials only); `mail-collector` and `mail-in` are described below. +COMPOSE_PROFILES=tunnel + +# Fleet bucket. Google Cloud Storage via Application Default Credentials (on GCE, the VM's +# service account needs roles/storage.objectAdmin on the bucket): +CELLD_BUCKET=gs://my-sam-bucket/celld +# Or, for a trial only, the bundled store: a community MinIO build; celld does not qualify it for +# production (README, Object store). Add local-store to COMPOSE_PROFILES and set: +# CELLD_BUCKET=s3://celld-fleet +# S3_ENDPOINT=http://127.0.0.1:9000 +# AWS_ACCESS_KEY_ID=sam-objectstore +# AWS_SECRET_ACCESS_KEY= # openssl rand -hex 24 + +# Loopback ports (host network). Change only on conflict, and only here: a port set in the shell +# also overrides this file for docker compose, and Caddy refuses to start if any of them lies in +# the reverse-tunnel range below. +# CELLD_PORT=8080 +# CELLD_INTERNAL_PORT=7001 +# FRPS_BIND_PORT=7000 +# OBJECTSTORE_PORT=9000 +# OBJECTSTORE_CONSOLE_PORT=9001 +# HTTP_PORT=80 +# HTTPS_PORT=443 +# MAIL_COLLECTOR_SMTP_PORT=1025 and MAIL_COLLECTOR_UI_PORT=8025 (below) are box ports too. + +# Presigned browser uploads (attachments, snapshots) go straight to the fleet bucket. Set the +# store's public HTTPS endpoint here and a credential scoped to //r2//* +# as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in .state/secrets.env (never the fleet credential). +# The deploy derives the bucket and key prefix. Unset: presigned uploads stay off. +# R2_S3_REGION is the store's SigV4 signing region: "auto" by default for a gs:// bucket, +# REQUIRED for an s3:// bucket (MinIO usually us-east-1): the deploy refuses R2_S3_ENDPOINT +# without it. +# R2_S3_ENDPOINT=https://storage.googleapis.com +# R2_S3_REGION=auto + +# Email sign-in (README, Email sign-in). Either an SMTP relay (SMTP_PASSWORD goes in +# .state/secrets.env): +# SMTP_HOST=smtp.example.com +# SMTP_TLS=starttls +# SMTP_PORT=587 +# SMTP_USERNAME= +# SMTP_FROM=sign-in@sam.example.com +# or, on a TEST install only, add `mail-collector` to COMPOSE_PROFILES: Mailpit catches every +# sign-in email for https://mail.SAM_DOMAIN, and anyone who can read it can sign in as any +# account. Its loopback ports and UI host label: +# MAIL_COLLECTOR_SMTP_PORT=1025 +# MAIL_COLLECTOR_UI_PORT=8025 +# MAIL_COLLECTOR_HOST_LABEL=mail + +# Inbound agent email (README, Inbound agent email): add `mail-in` to COMPOSE_PROFILES (needs +# SMTP_HOST or the mail collector for replies), an MX record agents.SAM_DOMAIN -> mx.SAM_DOMAIN +# and inbound tcp/25. Optional limits and settings: +# SAM_MX_MAX_MESSAGE_BYTES=5242880 +# SAM_MX_MAX_CONNECTIONS=20 +# SAM_MX_MAX_CONNECTIONS_PER_IP=3 +# SAM_MX_MAX_SESSION=15m +# SAM_MX_CONNECTIONS_PER_IP_PER_MINUTE=30 +# SAM_MX_MESSAGES_PER_CONNECTION=10 +# Smoke tests from the box only (skips SPF/DKIM/DMARC for these loopback networks): +# SAM_MX_TRUSTED_NETWORKS=127.0.0.1/32 + +# Loopback ports frps may bind for node tunnels (default 20000-29999, at most 20000 ports). The +# deploy script writes the resolved range to both the Worker and .state/gateway.env, so change +# it here only. The deploy fails if the range contains any port above or a size over the cap. +# REVERSE_TUNNEL_PORT_RANGE_START=20000 +# REVERSE_TUNNEL_PORT_RANGE_END=29999 +# frps drops a node that has not heartbeated for this many seconds (60-3600, default 90); the +# Worker gets the same value and never reissues a released port before twice this age. +# REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS=90 +# Optional: a longer minimum age before a released port is reissued (default and floor 2 x the +# heartbeat timeout). +# REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS=180 + +# Where `pnpm selfhost:deploy` keeps platform keys, gateway.env and the celld project. +# SAM_SELFHOST_STATE_DIR=./.state + +# frp connections Caddy accepts per client address per window at wss://api.SAM_DOMAIN/~!frp +# (each one is a Login the Worker checks). Nodes keep one connection each; raise it if many nodes +# share one public address (a NAT gateway). Window: 1s-99s, 1m-99m or 1h. +# SAM_FRP_LOGIN_RATE_LIMIT_EVENTS=60 +# SAM_FRP_LOGIN_RATE_LIMIT_WINDOW=1m + +# Keep-warm: Caddy pings celld's /health so a retired Worker isolate is restarted by the ping, +# not by a user's request. off turns it off; the interval must be 1s-6s. +# SAM_KEEP_WARM=on +# SAM_KEEP_WARM_INTERVAL=5s +# Caddy's access log is capped at about CADDY_LOG_MAX_SIZE x CADDY_LOG_MAX_FILES on disk. +# CADDY_LOG_MAX_SIZE=50m +# CADDY_LOG_MAX_FILES=5 + +# celld tuning (defaults shown). +# CELLD_LTX_RETENTION_SECS=86400 +# CELLD_FETCH_TIMEOUT_S=3600 diff --git a/deploy/selfhost/caddy/.dockerignore b/deploy/selfhost/caddy/.dockerignore new file mode 100644 index 0000000000..55ce9e7829 --- /dev/null +++ b/deploy/selfhost/caddy/.dockerignore @@ -0,0 +1,3 @@ +# The build needs nothing from this directory: the Dockerfile fetches pinned modules only. An +# empty context keeps Caddyfile edits (mounted at run time) from touching the image build. +* diff --git a/deploy/selfhost/caddy/Caddyfile b/deploy/selfhost/caddy/Caddyfile new file mode 100644 index 0000000000..0e2e473abc --- /dev/null +++ b/deploy/selfhost/caddy/Caddyfile @@ -0,0 +1,65 @@ +# One-box ingress for a celld-hosted SAM control plane. +# +# Every SAM hostname is one label under SAM_DOMAIN (api., app., ws-., ws---.), so +# one wildcard certificate covers them all. Caddy runs on the host network: that is what lets +# {remote_host} be the real client address (published Docker ports would show the bridge +# gateway), and lets it reach celld and frps on loopback. +{ + http_port {$HTTP_PORT:80} + https_port {$HTTPS_PORT:443} + admin off + + # Caddy's own log (errors, proxy failures, certificates) on stderr. Its error entries carry the + # request, so it gets the same redaction as the access log below. + log default { + output stderr + import log-redaction.caddy + } +} + +# Every route that proxies a client request (here and in sam.d/) imports this, so the client +# address SAM sees always comes from the connection and never from a client-sent header. +(sam_client_ip) { + header_up CF-Connecting-IP {remote_host} + header_up X-Real-IP {remote_host} + header_up X-Forwarded-For {remote_host} + header_up -True-Client-IP + header_up -CF-Ray +} + +*.{$SAM_DOMAIN} { + import tls/{$SAM_TLS_MODE:internal}.caddy + + # Access log for every SAM host (app., api., ws-*, mail.): one JSON line per request on + # stdout (`docker compose logs caddy`), with host, method, path, status, duration (seconds, + # for a WebSocket the connection's lifetime), sizes and client address. Headers and query + # strings are never logged (log-redaction.caddy). + log { + output stdout + import log-redaction.caddy + } + + # celld never compresses responses. + encode zstd gzip + + # The mail collector's UI on its own host when the `mail-collector` profile is on + # (caddy/start.sh); an empty file otherwise. + import mail-collector/{$SAM_MAIL_COLLECTOR:off}.caddy + + # Keeps celld's stateless Worker isolate warm (keep-warm/on.caddy) unless SAM_KEEP_WARM=off. + import keep-warm/{$SAM_KEEP_WARM:on}.caddy + + # Routes owned by the node transport (frp over wss, node WebSockets). Each is a + # `handle @matcher { ... }` block; the matcher-less handle below always sorts last. A + # fragment that proxies to celld or a node must `import sam_client_ip` in its proxy block. + import sam.d/*.caddy + + handle { + reverse_proxy 127.0.0.1:{$CELLD_PORT:8080} { + # SAM reads the client address from CF-Connecting-IP (rate limits, sign-in, + # heartbeat IP). celld builds request.url from X-Forwarded-Host/-Proto, which Caddy + # sets from the connection (CELLD_TRUST_FORWARDED_HEADERS=1). + import sam_client_ip + } + } +} diff --git a/deploy/selfhost/caddy/Dockerfile b/deploy/selfhost/caddy/Dockerfile new file mode 100644 index 0000000000..52330b705d --- /dev/null +++ b/deploy/selfhost/caddy/Dockerfile @@ -0,0 +1,38 @@ +# Caddy plus two modules: a DNS provider (DNS-01 for the wildcard certificate *.${SAM_DOMAIN}) +# and caddy-ratelimit (anonymous frp Login probes, sam.d/frp.caddy). +# +# Reproducible on purpose (docker-compose.yml builds it only on an explicit `docker compose build` +# or when the image is missing): +# - both images are pinned by digest; the builder's CADDY_VERSION fixes Caddy itself; +# - every module is pinned by version, fetched only from the public Go module proxy and verified +# against the Go checksum database (a published module version cannot change content); +# - GOTOOLCHAIN=local: a module asking for a newer Go fails the build instead of downloading one; +# - the build fails unless the binary carries exactly the requested module versions. +# Change the DNS provider with CADDY_DNS_MODULE=github.com/caddy-dns/@ in .env, +# add a matching tls/dns-.caddy snippet, then `docker compose build caddy`. +FROM caddy:2.11.9-builder@sha256:3db11aead97f1fdff9c563d0dd8e7fba2e4c7031bef40f3e44fd1982f3e8366b AS build +ARG CADDY_DNS_MODULE=github.com/caddy-dns/googleclouddns@v1.1.0 +ARG CADDY_RATELIMIT_MODULE=github.com/mholt/caddy-ratelimit@v0.1.0 +ENV GOPROXY=https://proxy.golang.org \ + GOSUMDB=sum.golang.org \ + GONOSUMDB= \ + GONOSUMCHECK= \ + GOPRIVATE= \ + GOINSECURE= \ + GOTOOLCHAIN=local +RUN set -eu; \ + for module in "$CADDY_DNS_MODULE" "$CADDY_RATELIMIT_MODULE"; do \ + case "$module" in \ + *@v[0-9]*) ;; \ + *) echo "module $module must be pinned as @" >&2; exit 1 ;; \ + esac; \ + done; \ + xcaddy build --output /usr/bin/caddy --with "$CADDY_DNS_MODULE" --with "$CADDY_RATELIMIT_MODULE"; \ + go version -m /usr/bin/caddy > /tmp/build-info; \ + for module in "$CADDY_DNS_MODULE" "$CADDY_RATELIMIT_MODULE"; do \ + grep -Eq "^[[:space:]]+dep[[:space:]]+${module%@*}[[:space:]]+${module#*@}[[:space:]]+h1:" /tmp/build-info \ + || { echo "caddy was not built with $module" >&2; cat /tmp/build-info >&2; exit 1; }; \ + done + +FROM caddy:2.11.9@sha256:ce773ec7a742ce15ee6bf2bb5f65882b9e2a4487b10733e6f1484f86e6b5d8bc +COPY --from=build /usr/bin/caddy /usr/bin/caddy diff --git a/deploy/selfhost/caddy/keep-warm/off.caddy b/deploy/selfhost/caddy/keep-warm/off.caddy new file mode 100644 index 0000000000..bb96287964 --- /dev/null +++ b/deploy/selfhost/caddy/keep-warm/off.caddy @@ -0,0 +1 @@ +# SAM_KEEP_WARM=off: no keep-warm health check (Caddyfile). diff --git a/deploy/selfhost/caddy/keep-warm/on.caddy b/deploy/selfhost/caddy/keep-warm/on.caddy new file mode 100644 index 0000000000..45958ada11 --- /dev/null +++ b/deploy/selfhost/caddy/keep-warm/on.caddy @@ -0,0 +1,31 @@ +# Keep-warm (self-host stopgap, README.md "Cold starts"). On every 30 s pool tick (REAP_INTERVAL, +# not configurable) celld 0.6.3 retires one stateless Worker isolate that hosts no cells whenever no +# JS turn is running at that instant (celld_logic::isolate::retire), so a quiet box has no warm +# isolate and the next request waits 1.5-2.4 s while a new one loads the bundle. Caddy's active +# health check sends GET /health to celld every SAM_KEEP_WARM_INTERVAL (default 5s) for as long as +# Caddy runs. A ping cannot stop a retirement, but the next ping pays the restart, so only a request +# arriving between a tick and the restarted isolate waits: about (interval / 2 + restart time) of +# every 30 s. Measured on the test box (T14): 1 of 14 first-requests-after-idle cold, vs 8 of 8. +# +# The check lives on a route that never matches a request (`expression false`): an active +# health check runs for every provisioned reverse_proxy whether or not traffic reaches it, and +# its verdict only gates this unused route, so a failed or slow /health can never take the real +# proxy below out of service. /health reads no storage and is excluded from SAM's request log. +# Health checks are not requests to the site, so they do not appear in the access log. +# +# Upstream: drop this once celld can keep isolates warm itself. +@sam_keep_warm expression false +handle @sam_keep_warm { + reverse_proxy 127.0.0.1:{$CELLD_PORT:8080} { + health_uri /health + health_interval {$SAM_KEEP_WARM_INTERVAL:5s} + health_timeout 10s + health_headers { + # celld builds request.url from X-Forwarded-Host (CELLD_TRUST_FORWARDED_HEADERS=1); + # /health is routed on the API host. + Host api.{$SAM_DOMAIN} + X-Forwarded-Host api.{$SAM_DOMAIN} + X-Forwarded-Proto https + } + } +} diff --git a/deploy/selfhost/caddy/log-redaction.caddy b/deploy/selfhost/caddy/log-redaction.caddy new file mode 100644 index 0000000000..a21298f1e9 --- /dev/null +++ b/deploy/selfhost/caddy/log-redaction.caddy @@ -0,0 +1,27 @@ +# Shared by the access log and Caddy's own log (Caddyfile). What a log line may contain about a +# request: host, method, path, protocol, client address and port, TLS details, status, sizes and +# duration. What it may not: any request or response header (cookies, Authorization, SAM's +# X-SAM-* gateway headers, the gateway secret), any query string (terminal and port-access +# tokens, OAuth codes and state travel there), or a credential that a route carries in its path. +# Caddy already redacts Cookie, Set-Cookie, Authorization and Proxy-Authorization by default; +# deleting the header maps outright also covers every other header, including ones forward_auth +# copies onto the request. `headers` is where reverse_proxy's debug entries put response headers. +# +# Credentials in paths (keep in sync with the routes; scripts/selfhost/caddy-logging-compose.test.ts): +# /ai/proxy//... apps/api/src/routes/ai-proxy-passthrough.ts +# /api/bootstrap/ apps/api/src/routes/bootstrap.ts +# /api/projects/invite-links/ apps/api/src/routes/projects/members.ts +# /projects/invite/ apps/web/src/App.tsx (the app's HTML document) +# /p//////... services/interactive-preview.ts +format filter { + wrap json + request>headers delete + resp_headers delete + headers delete + user_id delete + request>uri multi_regexp { + regexp "^(/ai/proxy/|/api/bootstrap/|/api/projects/invite-links/|/projects/invite/)[^/?]*" "${1}" + regexp "^/p/[^?]*" "/p/" + regexp "\?.*$" "?" + } +} diff --git a/deploy/selfhost/caddy/mail-collector/off.caddy b/deploy/selfhost/caddy/mail-collector/off.caddy new file mode 100644 index 0000000000..426f58604c --- /dev/null +++ b/deploy/selfhost/caddy/mail-collector/off.caddy @@ -0,0 +1 @@ +# Mail collector off (the default): mail.SAM_DOMAIN is not routed to it. diff --git a/deploy/selfhost/caddy/mail-collector/on.caddy b/deploy/selfhost/caddy/mail-collector/on.caddy new file mode 100644 index 0000000000..7e75026d77 --- /dev/null +++ b/deploy/selfhost/caddy/mail-collector/on.caddy @@ -0,0 +1,16 @@ +# Mail collector UI (compose profile `mail-collector`, scripts/selfhost/mail-settings.ts). +# Anyone who can read the collector can sign in to SAM as any account, so it is served only +# behind basic auth with the generated password. start.sh hashes that password before Caddy +# starts; only the hash is in the config. Mailpit listens on loopback and checks the same +# credentials itself (MP_UI_AUTH, .state/mail-collector-ui.env). +@sam_mail_collector host {$MAIL_COLLECTOR_HOST_LABEL}.{$SAM_DOMAIN} +handle @sam_mail_collector { + basic_auth { + {$MAIL_COLLECTOR_UI_USER} {$MAIL_COLLECTOR_UI_HASH} + } + # Mailpit checks the same credentials itself (MP_UI_AUTH), so Authorization is passed on; + # cookies for other SAM hosts are not. + reverse_proxy 127.0.0.1:{$MAIL_COLLECTOR_UI_PORT} { + header_up -Cookie + } +} diff --git a/deploy/selfhost/caddy/sam.d/frp.caddy b/deploy/selfhost/caddy/sam.d/frp.caddy new file mode 100644 index 0000000000..0eac84c043 --- /dev/null +++ b/deploy/selfhost/caddy/sam.d/frp.caddy @@ -0,0 +1,66 @@ +# Reverse-tunnel transport: nodes' frpc dial wss://api.{SAM_DOMAIN}/~!frp (frp's fixed +# WebSocket path). Caddy terminates TLS with the box's public certificate (frpc verifies it, +# useSystemCa) and hands the socket to frps on loopback. +# +# Each new connection is one frp Login that frps asks the Worker to check, so anonymous probes +# are rate limited per client address (caddy-ratelimit, built into the image by caddy/Dockerfile): +# SAM_FRP_LOGIN_RATE_LIMIT_EVENTS connections per SAM_FRP_LOGIN_RATE_LIMIT_WINDOW, validated by +# start.sh. A node keeps one connection (work connections are multiplexed over it), so only +# reconnects count. Over the limit Caddy answers 429 and frpc retries later. +@sam_frp { + host api.{$SAM_DOMAIN} + path /~!frp +} +handle @sam_frp { + route { + rate_limit { + zone sam_frp_login { + key {remote_host} + events {$SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:60} + window {$SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:1m} + } + } + reverse_proxy 127.0.0.1:{$FRPS_BIND_PORT:7000} { + import sam_client_ip + } + } +} + +# Internal gateway endpoints (frps plugin, forward_auth, inbound email) live under +# /api/self-host/gateway (apps/api/src/selfhost/reverse-tunnel/gateway.ts) and are reached by +# frps, Caddy and sam-mx on loopback only, straight to celld. They are never served on the +# public listener, on any host. The path matcher compares the cleaned, decoded path, case- +# insensitively: doubled slashes, dot segments and single percent-encoding all land here. +@sam_gateway_internal path /api/self-host /api/self-host/* +handle @sam_gateway_internal { + respond "Not found" 404 +} + +# Other spellings that a URL parser behind Caddy could still turn into that prefix, on a +# non-workspace host. Matched on the RAW request target (scheme and authority of an absolute-form +# target allowed), so every encoding depth is seen: each character of "api" and "self-host" may be +# literal or percent-encoded any number of times (%73, %2573, %252573 ...), separators may be /, \ +# or their encodings, and dot segments and ;params may sit between the two segments. Only an +# "api" first segment followed by a "self-host" segment matches, never a path that merely contains +# the words (/docs/self-hosting, /api/projects//files/self-host/...). +# Workspace hosts (ws-*) are exempt: the Worker sends every ws-* request to the workspace proxy +# before any route, and a preview app may legitimately serve such paths. +@sam_gateway_internal_spelling { + not expression `{host}.matches("(?i)^ws-[a-z0-9]+(--[0-9]+)?[.]")` + expression `{http.request.uri}.matches("(?i)^([a-z][a-z0-9+.-]*://[^/?#]*)?((/|[\\\\]|%(25)*(2f|5c))|([.]|%(25)*2e))*(a|%(25)*[46]1)(p|%(25)*[57]0)(i|%(25)*[46]9)(;[^/?#]*)?((/|[\\\\]|%(25)*(2f|5c))|([.]|%(25)*2e)|;[^/?#]*)*(s|%(25)*[57]3)(e|%(25)*[46]5)(l|%(25)*[46]c)(f|%(25)*[46]6)(-|%(25)*2d)(h|%(25)*[46]8)(o|%(25)*[46]f)(s|%(25)*[57]3)(t|%(25)*[57]4)([/;?#%]|[\\\\]|$)")` +} +handle @sam_gateway_internal_spelling { + respond "Not found" 404 +} + +# Dot segments (., .., %2e in any depth, with / or \ separators) reorder segments, so the "api" +# segment need not come first: a raw target with a dot segment that names "self-host" anywhere in +# any encoding is refused too. Browsers and HTTP clients resolve dot segments before sending, so +# no legitimate request carries one. +@sam_gateway_internal_dot_segments { + not expression `{host}.matches("(?i)^ws-[a-z0-9]+(--[0-9]+)?[.]")` + expression `{http.request.uri}.matches("(?i)^([a-z][a-z0-9+.-]*://[^/?#]*)?[^?#]*(/|[\\\\]|%(25)*(2f|5c))([.]|%(25)*2e)([.]|%(25)*2e)?((/|[\\\\]|%(25)*(2f|5c))|[?#]|$)") && {http.request.uri}.matches("(?i)^[^?#]*(s|%(25)*[57]3)(e|%(25)*[46]5)(l|%(25)*[46]c)(f|%(25)*[46]6)(-|%(25)*2d)(h|%(25)*[46]8)(o|%(25)*[46]f)(s|%(25)*[57]3)(t|%(25)*[57]4)")` +} +handle @sam_gateway_internal_dot_segments { + respond "Not found" 404 +} diff --git a/deploy/selfhost/caddy/sam.d/node-ws.caddy b/deploy/selfhost/caddy/sam.d/node-ws.caddy new file mode 100644 index 0000000000..4fed231575 --- /dev/null +++ b/deploy/selfhost/caddy/sam.d/node-ws.caddy @@ -0,0 +1,104 @@ +# Node WebSockets on the reverse-tunnel transport: terminal, agent, boot log, port-preview +# sockets (ws-[--].{SAM_DOMAIN}) and the node log stream +# (api.{SAM_DOMAIN}/api/nodes//logs/stream). +# +# celld cannot return a WebSocket the Worker obtained from an outbound fetch, so Caddy carries +# these sockets. The Worker still makes every decision: forward_auth re-runs SAM's own ws-* / +# logs-stream authentication (session, terminal token, port-access cookie or token, public +# ports, ownership, workspace status) and answers either +# - a refusal (401, 302 port-token -> cookie redirect, 403, 404, 503 ...), which Caddy sends +# to the client unchanged, or +# - 200 with the loopback upstream (X-SAM-Upstream = 127.0.0.1:), the node-agent +# URI to request, and the exact Authorization/Cookie/X-SAM-* headers SAM would have sent. +# Plain HTTP (including port previews) is not matched here and goes to celld as usual. +# +# `route` keeps the steps in the order written (forward_auth, then rewrite, then proxy). + +@sam_node_ws_port { + expression `{host}.matches("^ws-[A-Za-z0-9]+--[0-9]+\\.")` + header_regexp Connection (?i)upgrade + header_regexp Upgrade (?i)^websocket$ +} +handle @sam_node_ws_port { + # Client-supplied SAM routing/credential headers never reach SAM or the node. + request_header -X-SAM-* + # A workspace app must not set cookies on the preview host (sam_port_access), exactly as the + # Worker strips Set-Cookie from every port response. Two rules, because reverse_proxy's + # header_down is not applied to a 101 upgrade: header_down for ordinary node responses, and + # this response-writer rule for the upgraded socket only. Neither touches SAM's own 302 + # port-token -> cookie redirect, which forward_auth returns. + header { + -Set-Cookie + match status 101 + } + route { + # Captured before forward_auth overrides Host: header_up ops are not ordered. + vars sam_ws_host {host} + forward_auth 127.0.0.1:{$CELLD_PORT:8080} { + uri /api/self-host/gateway/node-websocket + # celld (CELLD_TRUST_FORWARDED_HEADERS=1) builds request.url from X-Forwarded-Host, + # so it must name the API host; the socket's own host travels separately. + header_up Host api.{$SAM_DOMAIN} + header_up X-Forwarded-Host api.{$SAM_DOMAIN} + header_up X-SAM-Gateway-Original-Host {vars.sam_ws_host} + header_up X-SAM-Gateway-Secret {$REVERSE_TUNNEL_GATEWAY_SECRET} + import sam_client_ip + copy_headers X-SAM-Upstream X-SAM-Upstream-Uri X-SAM-Upstream-Authorization X-SAM-Upstream-Cookie X-SAM-Node-Id X-SAM-Workspace-Id + } + rewrite * {http.request.header.X-SAM-Upstream-Uri} + reverse_proxy {http.request.header.X-SAM-Upstream} { + import sam_client_ip + header_up Authorization {http.request.header.X-SAM-Upstream-Authorization} + header_up Cookie {http.request.header.X-SAM-Upstream-Cookie} + header_up X-Forwarded-Host {vars.sam_ws_host} + header_up X-Forwarded-Proto https + header_up -X-SAM-Upstream + header_up -X-SAM-Upstream-Uri + header_up -X-SAM-Upstream-Authorization + header_up -X-SAM-Upstream-Cookie + # Defence in depth: the gateway's own headers never reach a node. + header_up -X-SAM-Gateway-Secret + header_up -X-SAM-Gateway-Original-Host + header_down -Set-Cookie + } + } +} + +@sam_node_ws { + expression `{host}.matches("^ws-[A-Za-z0-9]+\\.") || ({host} == "api." + {env.SAM_DOMAIN} && {path}.matches("^/api/nodes/[A-Za-z0-9_-]+/logs/stream$"))` + header_regexp Connection (?i)upgrade + header_regexp Upgrade (?i)^websocket$ +} +handle @sam_node_ws { + request_header -X-SAM-* + route { + # Captured before forward_auth overrides Host: header_up ops are not ordered. + vars sam_ws_host {host} + forward_auth 127.0.0.1:{$CELLD_PORT:8080} { + uri /api/self-host/gateway/node-websocket + # celld (CELLD_TRUST_FORWARDED_HEADERS=1) builds request.url from X-Forwarded-Host, + # so it must name the API host; the socket's own host travels separately. + header_up Host api.{$SAM_DOMAIN} + header_up X-Forwarded-Host api.{$SAM_DOMAIN} + header_up X-SAM-Gateway-Original-Host {vars.sam_ws_host} + header_up X-SAM-Gateway-Secret {$REVERSE_TUNNEL_GATEWAY_SECRET} + import sam_client_ip + copy_headers X-SAM-Upstream X-SAM-Upstream-Uri X-SAM-Upstream-Authorization X-SAM-Upstream-Cookie X-SAM-Node-Id X-SAM-Workspace-Id + } + rewrite * {http.request.header.X-SAM-Upstream-Uri} + reverse_proxy {http.request.header.X-SAM-Upstream} { + import sam_client_ip + header_up Authorization {http.request.header.X-SAM-Upstream-Authorization} + header_up Cookie {http.request.header.X-SAM-Upstream-Cookie} + header_up X-Forwarded-Host {vars.sam_ws_host} + header_up X-Forwarded-Proto https + header_up -X-SAM-Upstream + header_up -X-SAM-Upstream-Uri + header_up -X-SAM-Upstream-Authorization + header_up -X-SAM-Upstream-Cookie + # Defence in depth: the gateway's own headers never reach a node. + header_up -X-SAM-Gateway-Secret + header_up -X-SAM-Gateway-Original-Host + } + } +} diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh new file mode 100644 index 0000000000..b6d2896eb5 --- /dev/null +++ b/deploy/selfhost/caddy/start.sh @@ -0,0 +1,85 @@ +#!/bin/sh +# Starts Caddy after checking its settings (each refusal exits 64 with a message). +# - Mail collector on (SAM_MAIL_COLLECTOR=on in .state/mail-collector.env, written by +# `pnpm selfhost:deploy`): the collector UI password is hashed here first, so the Caddy config +# and the Caddy process see only the hash. Refuses the collector without a password: its UI +# must never be served unauthenticated. +# - Keep-warm and the frp Login rate limit: refuses values Caddy would misread. +# - Refuses any box port inside the reverse-tunnel lease range. +set -eu +case "${SAM_MAIL_COLLECTOR:-off}" in +off) ;; +on) + password="${MAIL_COLLECTOR_UI_PASSWORD:-}" + if [ "${#password}" -lt 32 ] || [ -z "${MAIL_COLLECTOR_UI_USER:-}" ]; then + echo 'caddy: the mail collector is on without its UI password; run pnpm selfhost:deploy --init' >&2 + exit 64 + fi + MAIL_COLLECTOR_UI_HASH="$(printf '%s\n' "$password" | caddy hash-password)" + export MAIL_COLLECTOR_UI_HASH + unset MAIL_COLLECTOR_UI_PASSWORD password + ;; +*) + echo "caddy: SAM_MAIL_COLLECTOR must be on or off" >&2 + exit 64 + ;; +esac +# Keep-warm (keep-warm/on.caddy). A bad value must fail here with a clear message, not as a +# missing import file or a Caddy duration parse error. +case "${SAM_KEEP_WARM:-on}" in +on | off) ;; +*) + echo "caddy: SAM_KEEP_WARM must be on or off" >&2 + exit 64 + ;; +esac +case "${SAM_KEEP_WARM_INTERVAL:-5s}" in +[1-6]s) ;; +*) + echo "caddy: SAM_KEEP_WARM_INTERVAL must be 1s to 6s (a longer interval widens the cold window after each 30 s celld pool tick)" >&2 + exit 64 + ;; +esac +# frp Login rate limit (sam.d/frp.caddy). Caddy would read a bad value as a parse error. +case "${SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:-60}" in +'' | *[!0-9]* | 0*) + echo "caddy: SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be a positive integer" >&2 + exit 64 + ;; +esac +case "${SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:-1m}" in +[1-9]s | [1-9][0-9]s | [1-9]m | [1-9][0-9]m | 1h) ;; +*) + echo "caddy: SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be 1s-99s, 1m-99m or 1h" >&2 + exit 64 + ;; +esac +# No box listener may lie inside the reverse-tunnel lease range (gateway.env). The deploy checks +# the same (scripts/selfhost/box-settings.ts resolveTunnelPortRange), but compose takes a port from +# the shell before the .env, so this checks the values the stack really runs with. A port inside +# the range could be leased to a node: the Worker and Caddy would then send that node's traffic, +# with its credentials, to celld's unauthenticated operator API or another box service. +start="${REVERSE_TUNNEL_PORT_RANGE_START:-}" +end="${REVERSE_TUNNEL_PORT_RANGE_END:-}" +case "$start:$end" in +*[!0-9:]* | :* | *:) + echo "caddy: REVERSE_TUNNEL_PORT_RANGE_START/END missing from gateway.env; run pnpm selfhost:deploy --init" >&2 + exit 64 + ;; +esac +for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT OBJECTSTORE_PORT \ + OBJECTSTORE_CONSOLE_PORT MAIL_COLLECTOR_SMTP_PORT MAIL_COLLECTOR_UI_PORT; do + eval "port=\"\${$name:-}\"" + case "$port" in + '' | *[!0-9]*) + echo "caddy: $name must be set to a port number (docker-compose.yml passes every box port)" >&2 + exit 64 + ;; + esac + if [ "$port" -ge "$start" ] && [ "$port" -le "$end" ]; then + echo "caddy: $name ($port) lies inside the reverse-tunnel range $start-$end; a node could be leased it. Change the port or REVERSE_TUNNEL_PORT_RANGE_START/END, then pnpm selfhost:deploy --init" >&2 + exit 64 + fi +done +unset start end name port +exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile diff --git a/deploy/selfhost/caddy/tls/dns-googleclouddns.caddy b/deploy/selfhost/caddy/tls/dns-googleclouddns.caddy new file mode 100644 index 0000000000..1098ea62b0 --- /dev/null +++ b/deploy/selfhost/caddy/tls/dns-googleclouddns.caddy @@ -0,0 +1,12 @@ +# Let's Encrypt wildcard certificate through a DNS-01 challenge against Google Cloud DNS. +# Credentials: Application Default Credentials (the VM's service account on GCE needs +# roles/dns.admin on the zone's project). GCP_PROJECT is the project that owns the zone. +# ACME_EMAIL may be empty (an account with no contact). ACME_CA defaults to Let's Encrypt +# production; point it at https://acme-staging-v02.api.letsencrypt.org/directory for a first +# trial run so a misconfiguration cannot spend the production rate limit. +tls {$ACME_EMAIL} { + ca {$ACME_CA:https://acme-v02.api.letsencrypt.org/directory} + dns googleclouddns { + gcp_project {$GCP_PROJECT} + } +} diff --git a/deploy/selfhost/caddy/tls/internal.caddy b/deploy/selfhost/caddy/tls/internal.caddy new file mode 100644 index 0000000000..55238f00f0 --- /dev/null +++ b/deploy/selfhost/caddy/tls/internal.caddy @@ -0,0 +1,2 @@ +# Local CA (caddy's own). For local proofs only: browsers and celld's outbound fetch do not trust it. +tls internal diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml new file mode 100644 index 0000000000..deca8eaf61 --- /dev/null +++ b/deploy/selfhost/docker-compose.yml @@ -0,0 +1,323 @@ +# One-box self-hosted SAM control plane on celld (https://celld.dev). EXPERIMENTAL: see README.md. +# +# browser / nodes --443--> caddy --127.0.0.1:CELLD_PORT--> celld (API Worker + web UI assets) +# | | \--127.0.0.1:--> frps --> node +# \--frp over wss, node WS------> frps (127.0.0.1:FRPS_BIND_PORT) +# celld --> fleet bucket (GCS, S3, or the bundled store) +# +# caddy, celld and frps share the host network on purpose: the Worker's fetch to a node's +# loopback lease port runs in celld's network namespace, and Caddy forward_auth proxies node +# WebSockets to the same port. Everything except Caddy (and sam-mx on port 25) listens on +# 127.0.0.1 only. +# +# Plaintext mode: celld keeps every Worker secret in plaintext in the fleet bucket's deploy +# manifests, and nothing restricts the Worker's outbound connections on the box yet (README.md, +# "Not included yet"). Treat the bucket credential and the box as one secret. +# +# Usage (README.md): cp .env.example .env && chmod 600 .env && edit it; +# `pnpm selfhost:deploy --init` (platform keys + .state/gateway.env); `docker compose build`; +# `docker compose up -d`; then `pnpm selfhost:deploy`. +# +# Images: pulled images are pinned by digest. The two built here (caddy, sam-mx) pin their base +# images by digest and every module by version, and are built only by an explicit +# `docker compose build` (or when the image does not exist yet); `pnpm selfhost:upgrade` rebuilds +# a service only when its build inputs changed. The pinned celld version must match CELLD_VERSION +# in scripts/selfhost/versions.ts, which the deploy script uses for `celld deploy`. +name: sam-selfhost + +services: + celld: + image: ghcr.io/denoland/celld:v0.6.3@sha256:22bca1b40a9e4c434cc149d8913d7eaafa9792961a8c05f9fecf921d416216dc + network_mode: host + depends_on: + objectstore-init: + condition: service_completed_successfully + required: false # only with the local-store profile + environment: + CELLD_BUCKET: ${CELLD_BUCKET:?set CELLD_BUCKET in .env} + # Empty means unset: gs:// buckets take no endpoint and use Application Default Credentials + # (on GCE, the VM's service account through the metadata server). + S3_ENDPOINT: ${S3_ENDPOINT:-} + AWS_REGION: ${AWS_REGION:-us-east-1} + AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID:-} + AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-} + CELLD_ADDR: 127.0.0.1:${CELLD_PORT:-8080} + # Unauthenticated operator API (work, eviction, state, shutdown): loopback only. + CELLD_INTERNAL_ADDR: 127.0.0.1:${CELLD_INTERNAL_PORT:-7001} + CELLD_WATCH: /var/lib/celld + # Caddy replaces X-Forwarded-Host/-Proto, so request.url is https:///... + CELLD_TRUST_FORWARDED_HEADERS: '1' + # Delete superseded LTX epochs; without it the bucket grows on every cell activation. + CELLD_LTX_RETENTION_SECS: ${CELLD_LTX_RETENTION_SECS:-86400} + # Outbound fetch timeout. celld's default (120 s) cuts Worker-proxied streams mid-body. + # Worker-proxied node responses (file transfers, port previews) are cut at this cap. + CELLD_FETCH_TIMEOUT_S: ${CELLD_FETCH_TIMEOUT_S:-3600} + RUST_LOG: ${CELLD_RUST_LOG:-info} + volumes: + # A cache on one node: the bucket is the durable copy. + - celld-data:/var/lib/celld + # Above CELLD_SHUTDOWN_TOTAL_MS (40 s) so a stop is a clean lease handoff. + stop_grace_period: 50s + # celld docs: restart without an attempt limit. An immediate restart can hit + # "Address already in use"; Docker's restart backoff covers that. + restart: unless-stopped + + caddy: + # Built only by `docker compose build caddy` (or when the image is missing): caddy/Dockerfile + # pins both base images by digest and both modules by version. caddy/.dockerignore keeps the + # build context empty, so editing the Caddyfile never changes the build. + build: + context: ./caddy + args: + CADDY_DNS_MODULE: ${CADDY_DNS_MODULE:-github.com/caddy-dns/googleclouddns@v1.1.0} + image: sam-selfhost-caddy:local + pull_policy: never + network_mode: host + # Internet-facing and holds the DNS-01 identity: only the capability to bind 80/443. + cap_drop: [ALL] + cap_add: [NET_BIND_SERVICE] + depends_on: [celld] + # Validates its settings (start.sh: mail collector password, keep-warm, frp login rate limit, + # and that no box port lies inside the reverse-tunnel range) before starting Caddy. + entrypoint: ['/bin/sh', '/etc/caddy/start.sh'] + # REVERSE_TUNNEL_GATEWAY_SECRET (sent on forward_auth) and the lease port range. Written by + # `pnpm selfhost:deploy --init`. + # mail-collector.env: SAM_MAIL_COLLECTOR=on|off and the collector UI password (on only). + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/gateway.env + required: true + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector.env + required: false + environment: + SAM_DOMAIN: ${SAM_DOMAIN:?set SAM_DOMAIN in .env} + SAM_TLS_MODE: ${SAM_TLS_MODE:?set SAM_TLS_MODE in .env (internal or dns-)} + ACME_EMAIL: ${ACME_EMAIL:-} + ACME_CA: ${ACME_CA:-https://acme-v02.api.letsencrypt.org/directory} + GCP_PROJECT: ${GCP_PROJECT:-} + # Every box listener (scripts/selfhost/box-settings.ts BOX_RESERVED_PORTS), with the values + # the other services get from the same interpolation. start.sh refuses to start Caddy when + # one lies inside the reverse-tunnel range from gateway.env, so a shell override passed + # straight to `docker compose` cannot put a box port in the range the deploy checked. + HTTP_PORT: ${HTTP_PORT:-80} + HTTPS_PORT: ${HTTPS_PORT:-443} + CELLD_PORT: ${CELLD_PORT:-8080} + CELLD_INTERNAL_PORT: ${CELLD_INTERNAL_PORT:-7001} + FRPS_BIND_PORT: ${FRPS_BIND_PORT:-7000} + OBJECTSTORE_PORT: ${OBJECTSTORE_PORT:-9000} + OBJECTSTORE_CONSOLE_PORT: ${OBJECTSTORE_CONSOLE_PORT:-9001} + MAIL_COLLECTOR_SMTP_PORT: ${MAIL_COLLECTOR_SMTP_PORT:-1025} + MAIL_COLLECTOR_UI_PORT: ${MAIL_COLLECTOR_UI_PORT:-8025} + # Keep-warm for celld's stateless Worker isolate (caddy/keep-warm/on.caddy): on unless set + # to off; the interval (1s-6s) sets how long a cold window follows each 30 s celld pool tick. + # start.sh validates both. + SAM_KEEP_WARM: ${SAM_KEEP_WARM:-on} + SAM_KEEP_WARM_INTERVAL: ${SAM_KEEP_WARM_INTERVAL:-5s} + # frp connections (each one a Login the Worker checks) per client address per window, at + # wss://api.SAM_DOMAIN/~!frp (caddy/sam.d/frp.caddy). Nodes multiplex over one connection, + # so the default leaves room for a NAT gateway full of nodes reconnecting at once. + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: ${SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:-60} + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: ${SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:-1m} + # The access log goes to stdout. Docker's default json-file driver never rotates, so cap + # this service's log: about CADDY_LOG_MAX_SIZE x CADDY_LOG_MAX_FILES on disk. + logging: + driver: json-file + options: + max-size: ${CADDY_LOG_MAX_SIZE:-50m} + max-file: '${CADDY_LOG_MAX_FILES:-5}' + volumes: + - ./caddy:/etc/caddy:ro + - caddy-data:/data + - caddy-config:/config + restart: unless-stopped + + frps: + profiles: [tunnel] + image: ghcr.io/fatedier/frps:v0.72.0@sha256:17abb20dd392557a44070d9726954630c0eb1f7a9bd6ead5ae9150d165179ea4 + network_mode: host + command: ['-c', '/etc/frp/frps.toml'] + # REVERSE_TUNNEL_GATEWAY_SECRET (frps server-plugin auth) and the lease port range. + # Written by `pnpm selfhost:deploy --init`. + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/gateway.env + required: true + environment: + FRPS_BIND_PORT: ${FRPS_BIND_PORT:-7000} + CELLD_PORT: ${CELLD_PORT:-8080} + SAM_DOMAIN: ${SAM_DOMAIN:?set SAM_DOMAIN in .env} + # REVERSE_TUNNEL_PORT_RANGE_START/END come from gateway.env: the deploy script writes the + # same resolved range there and into the Worker's vars (scripts/selfhost/box-settings.ts). + volumes: + - ./frps:/etc/frp:ro + restart: unless-stopped + + # Mail collector for TEST installs (profile `mail-collector`, off by default): catches every + # email SAM sends (sign-in codes) so it can be read at https://mail.SAM_DOMAIN behind basic + # auth (caddy/mail-collector/on.caddy). Anyone who can read it can sign in as any account. + # SMTP and the UI listen on loopback only; the deploy points the Worker at the SMTP port + # (scripts/selfhost/mail-settings.ts) and refuses the profile without the generated UI password. + mail-collector: + profiles: [mail-collector] + # Mailpit v1.33.1 + image: axllent/mailpit:v1.33.1@sha256:aef2aacc11f075ec0fb6874275ee4a421e688e11a96ebb296134d1735c7761ce + network_mode: host + user: '65534:65534' + # MP_UI_AUTH=collector:: Mailpit requires it for its UI, API and send API + # too, so nothing on the box (celld included) reads codes on loopback without it. Written by + # `pnpm selfhost:deploy --init`; compose refuses to start the collector without the file. + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector-ui.env + required: true + read_only: true + tmpfs: [/tmp] + cap_drop: [ALL] + security_opt: ['no-new-privileges:true'] + command: + - --smtp + - 127.0.0.1:${MAIL_COLLECTOR_SMTP_PORT:-1025} + - --listen + - 127.0.0.1:${MAIL_COLLECTOR_UI_PORT:-8025} + # Messages live in /tmp (tmpfs) and are gone on restart; codes expire in minutes anyway. + - --max-age + - 1d + - --disable-version-check + - --smtp-disable-rdns + - --block-remote-css-and-fonts + restart: unless-stopped + + # Inbound agent email (profile `mail-in`, off by default): sam-mx (./sam-mx) accepts SMTP on + # port 25 for agent+@agents.SAM_DOMAIN only, requires aligned SPF or DKIM (DMARC pass) for + # the From domain, and hands each message during the SMTP session to the Worker's loopback + # gateway route (POST /api/self-host/gateway/inbound-email, which Caddy hides from the internet). + # Refusals are SMTP replies (550/552/451): it never relays, bounces, or sends mail. Replies to + # senders go out through the Worker's SMTP relay (SMTP_* or the mail-collector profile), which + # the deploy requires when this profile is on. Needs the MX record and an inbound tcp/25 + # firewall rule (README "Inbound agent email"). + sam-mx: + profiles: [mail-in] + # Built only by `docker compose build sam-mx` (or when the image is missing): sam-mx/Dockerfile + # pins both base images by digest; go.sum pins every module. + build: ./sam-mx + image: sam-selfhost-sam-mx:local + pull_policy: never + # Host network: it calls celld on 127.0.0.1, and the sender's address must be the real one for + # SPF and the per-address limits. + network_mode: host + user: '${SAM_MX_UID:-7102}:${SAM_MX_UID:-7102}' + # The binary's file capability binds port 25; every other capability is dropped. + cap_drop: [ALL] + cap_add: [NET_BIND_SERVICE] + security_opt: ['no-new-privileges:true'] + read_only: true + # Parses untrusted mail before authentication: bound its memory and processes so a flood + # cannot push celld or Caddy into the OOM killer. SAM_MX_MAX_CONNECTIONS (20) x 5 MiB + # messages, plus the copies the checks make, fits well inside this. + mem_limit: ${SAM_MX_MEM_LIMIT:-512m} + pids_limit: 128 + depends_on: [celld] + # Room for SAM_MX_SHUTDOWN_GRACE (8 s) to drain in-flight deliveries before SIGKILL. + stop_grace_period: 10s + # REVERSE_TUNNEL_GATEWAY_SECRET, the gateway route's shared secret. Written by + # `pnpm selfhost:deploy --init`. + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/gateway.env + required: true + environment: + SAM_DOMAIN: ${SAM_DOMAIN:?set SAM_DOMAIN in .env} + CELLD_PORT: ${CELLD_PORT:-8080} + SAM_MX_LISTEN: ${SAM_MX_LISTEN:-:25} + SAM_MX_HOSTNAME: ${SAM_MX_HOSTNAME:-} + SAM_MX_MAX_MESSAGE_BYTES: ${SAM_MX_MAX_MESSAGE_BYTES:-} + SAM_MX_MAX_CONNECTIONS: ${SAM_MX_MAX_CONNECTIONS:-} + SAM_MX_MAX_CONNECTIONS_PER_IP: ${SAM_MX_MAX_CONNECTIONS_PER_IP:-} + SAM_MX_MAX_SESSION: ${SAM_MX_MAX_SESSION:-} + # The Go runtime collects harder as it nears this, below mem_limit. + GOMEMLIMIT: ${SAM_MX_GOMEMLIMIT:-400MiB} + SAM_MX_CONNECTIONS_PER_IP_PER_MINUTE: ${SAM_MX_CONNECTIONS_PER_IP_PER_MINUTE:-} + SAM_MX_MESSAGES_PER_CONNECTION: ${SAM_MX_MESSAGES_PER_CONNECTION:-} + SAM_MX_GATEWAY_TIMEOUT: ${SAM_MX_GATEWAY_TIMEOUT:-} + # Strict SPF/DKIM alignment unless `true` (deploy/selfhost/sam-mx/config.go RelaxedAlignment). + SAM_MX_RELAXED_ALIGNMENT: ${SAM_MX_RELAXED_ALIGNMENT:-} + # Oldest Date a message authenticated by DKIM alone may carry (default 168h). + SAM_MX_DKIM_MAX_AGE: ${SAM_MX_DKIM_MAX_AGE:-} + # Drain time for in-flight deliveries on stop; keep it below stop_grace_period. + SAM_MX_SHUTDOWN_GRACE: ${SAM_MX_SHUTDOWN_GRACE:-} + # Loopback CIDRs whose mail skips SPF/DKIM/DMARC (smoke tests from the box itself). Empty + # by default; the receiver refuses any non-loopback network here. + SAM_MX_TRUSTED_NETWORKS: ${SAM_MX_TRUSTED_NETWORKS:-} + # Optional STARTTLS certificate and key, mounted read-only by an override file. + SAM_MX_TLS_CERT: ${SAM_MX_TLS_CERT:-} + SAM_MX_TLS_KEY: ${SAM_MX_TLS_KEY:-} + logging: + driver: json-file + options: + max-size: ${SAM_MX_LOG_MAX_SIZE:-20m} + max-file: '${SAM_MX_LOG_MAX_FILES:-3}' + restart: unless-stopped + + # Bundled object store for boxes without an external bucket. celld does not qualify it for + # production (MinIO community fork; it passes celld's storage test). Prefer GCS/S3/R2/Azure. + objectstore: + profiles: [local-store] + # pgsty/minio RELEASE.2026-08-04T00-00-00Z (minio/minio images are no longer published). + image: pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 + network_mode: host + command: + [ + 'server', + '/data', + '--address', + '127.0.0.1:${OBJECTSTORE_PORT:-9000}', + '--console-address', + '127.0.0.1:${OBJECTSTORE_CONSOLE_PORT:-9001}', + ] + # Compose interpolates every service, including ones whose profile is off, so a `:?` here + # would stop a gs:// or s3:// install that never runs this store. The store checks instead: + # it refuses an unset credential (MinIO would fall back to minioadmin), MinIO's well-known + # default, and a secret under 8 characters. /usr/bin/docker-entrypoint.sh is the image's + # own ENTRYPOINT at the pinned digest. + entrypoint: + - /bin/sh + - -c + - >- + case "$$MINIO_ROOT_USER:$$MINIO_ROOT_PASSWORD" in + :* | *: | minioadmin:* | *:minioadmin) + echo 'objectstore: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env (not minioadmin)' >&2; exit 64;; + esac; + test "$${#MINIO_ROOT_PASSWORD}" -ge 8 || + { echo 'objectstore: AWS_SECRET_ACCESS_KEY must be at least 8 characters' >&2; exit 64; }; + exec /usr/bin/docker-entrypoint.sh "$$@" + - objectstore + environment: + MINIO_ROOT_USER: ${AWS_ACCESS_KEY_ID:-} + MINIO_ROOT_PASSWORD: ${AWS_SECRET_ACCESS_KEY:-} + volumes: + - objectstore-data:/data + healthcheck: + test: ['CMD', 'mc', 'ready', 'local'] + interval: 5s + retries: 30 + stop_grace_period: 30s + restart: unless-stopped + + objectstore-init: + profiles: [local-store] + image: pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 + network_mode: host + depends_on: + objectstore: + condition: service_healthy + entrypoint: ['sh', '/init/init.sh'] + environment: + OBJECTSTORE_URL: http://127.0.0.1:${OBJECTSTORE_PORT:-9000} + CELLD_BUCKET: ${CELLD_BUCKET:?set CELLD_BUCKET in .env} + AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID:-} + AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-} + volumes: + - ./objectstore/init.sh:/init/init.sh:ro + restart: 'no' + +volumes: + celld-data: + caddy-data: + caddy-config: + objectstore-data: diff --git a/deploy/selfhost/frps/frps.toml b/deploy/selfhost/frps/frps.toml new file mode 100644 index 0000000000..2c940c0a38 --- /dev/null +++ b/deploy/selfhost/frps/frps.toml @@ -0,0 +1,45 @@ +# frps for the reverse-tunnel node transport (VM_AGENT_TRANSPORT="reverse-tunnel"). +# Validated with frp 0.72.0. frps renders this file as a Go template over its environment +# (so no template braces may appear in comments either). Variables: +# FRPS_BIND_PORT, CELLD_PORT, REVERSE_TUNNEL_GATEWAY_SECRET, +# REVERSE_TUNNEL_PORT_RANGE_START, REVERSE_TUNNEL_PORT_RANGE_END, +# REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS +# +# - frps listens on loopback only. Nodes reach it as frp over wss through Caddy on 443 +# (caddy/sam.d/frp.caddy); there is no TLS here because Caddy terminates it. +# - Every node proxy binds on loopback, only inside the lease range. The Worker (celld, host +# network) and Caddy (forward_auth WebSockets) reach nodes at 127.0.0.1:{leasePort}. +# - The real gate is the SAM server plugin: it checks the node's per-node credential, that its +# node incarnation is live, and that it binds exactly its own leased port, on every Login, +# NewProxy, heartbeat (Ping) and work connection (NewWorkConn, bound to the lease of the +# control session that owns its run id). allowPorts and maxPortsPerClient are a second fence. +# - auth.token stays empty on purpose. With auth.method token, frp uses ONE token for every +# client: every node would have to hold it, so it cannot tell one node from another, and the +# plugin already authenticates each node with its own credential on every op. frp also uses +# the token as the control-channel encryption key; a key every node knows adds nothing over +# the TLS Caddy terminates. Per-node tokens are not possible (frps checks one token, and a +# mismatched key breaks the encrypted control channel). +# - frps sends the plugin `addr` userinfo as HTTP basic auth; the password is the gateway +# secret. The plugin route answers 404 when the Worker has no secret, so frps then refuses +# every node (fail closed). The secret must be URL-safe (the generator makes it hex). +bindAddr = "127.0.0.1" +bindPort = {{ .Envs.FRPS_BIND_PORT }} +proxyBindAddr = "127.0.0.1" +allowPorts = [ + { start = {{ .Envs.REVERSE_TUNNEL_PORT_RANGE_START }}, end = {{ .Envs.REVERSE_TUNNEL_PORT_RANGE_END }} }, +] +maxPortsPerClient = 1 +# Caddy is the only TLS layer; frps sees plain WebSocket from it. +transport.tls.force = false +# A node that stops heartbeating is dropped after this long (frpc heartbeats every 30 s). The +# deploy script writes the same value to the Worker, which will not reissue a released lease +# port until twice this long has passed, so a new node's traffic cannot reach the old frpc. +transport.heartbeatTimeout = {{ .Envs.REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS }} +log.to = "console" +log.level = "info" + +[[httpPlugins]] +name = "sam-node-authz" +addr = "http://frps:{{ .Envs.REVERSE_TUNNEL_GATEWAY_SECRET }}@127.0.0.1:{{ .Envs.CELLD_PORT }}" +path = "/api/self-host/gateway/frps-plugin" +ops = ["Login", "NewProxy", "Ping", "NewWorkConn"] diff --git a/deploy/selfhost/objectstore/init.sh b/deploy/selfhost/objectstore/init.sh new file mode 100644 index 0000000000..d5b12df3e7 --- /dev/null +++ b/deploy/selfhost/objectstore/init.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Creates the celld fleet bucket in the bundled store. Idempotent. +set -eu +bucket="${CELLD_BUCKET#s3://}" +bucket="${bucket%%/*}" +case "$CELLD_BUCKET" in + s3://*) ;; + *) echo "objectstore-init: CELLD_BUCKET must be s3://[/prefix] with the local store" >&2; exit 1 ;; +esac +mc alias set local "$OBJECTSTORE_URL" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" >/dev/null +mc mb --ignore-existing "local/$bucket" diff --git a/scripts/selfhost/caddy-logging-compose.test.ts b/scripts/selfhost/caddy-logging-compose.test.ts new file mode 100644 index 0000000000..58ff47c9b3 --- /dev/null +++ b/scripts/selfhost/caddy-logging-compose.test.ts @@ -0,0 +1,117 @@ +/** + * Static wiring for Caddy's access log and the keep-warm health check (the behaviour itself is + * proven against the real Caddy image in live/access-log-keep-warm.live.test.ts): compose passes + * the keep-warm settings with their defaults and caps the Caddy log on disk, and both Caddy + * loggers import the one redaction filter. + */ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; + +const REPO = resolve(import.meta.dirname, '../..'); +const SELFHOST = resolve(REPO, 'deploy/selfhost'); + +interface Service { + environment?: Record; + logging?: { driver?: string; options?: Record }; +} + +const compose = parse(readFileSync(`${SELFHOST}/docker-compose.yml`, 'utf8')) as { + services: Record; +}; +const caddy = compose.services.caddy; +const caddyfile = readFileSync(`${SELFHOST}/caddy/Caddyfile`, 'utf8'); +const redaction = readFileSync(`${SELFHOST}/caddy/log-redaction.caddy`, 'utf8'); +const keepWarm = readFileSync(`${SELFHOST}/caddy/keep-warm/on.caddy`, 'utf8'); + +/** Route-definition strings with a path parameter named like a credential. */ +const CREDENTIAL_ROUTE = + /(?:\.(?:get|post|put|patch|delete|all|on)\(|path=)\s*['"`]([^'"`]*\/:(?:[a-z]*token|sig|signature|secret|key|code|jwt|nonce)\b[^'"`]*)['"`]/gi; + +/** Each known credential route and the logged path prefix the redaction filter rewrites. */ +const KNOWN_CREDENTIAL_ROUTES: Record = { + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages': '/ai/proxy/', + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages/count_tokens': + '/ai/proxy/', + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/openai/v1/chat/completions': '/ai/proxy/', + 'apps/api/src/routes/bootstrap.ts /:token': '/api/bootstrap/', + 'apps/api/src/routes/projects/members.ts /invite-links/:token': '/api/projects/invite-links/', + 'apps/api/src/routes/projects/members.ts /invite-links/:token/request': + '/api/projects/invite-links/', + 'apps/web/src/App.tsx /projects/invite/:token': '/projects/invite/', +}; + +const PATH_CREDENTIAL_PREFIXES = [ + '/ai/proxy/', + '/api/bootstrap/', + '/api/projects/invite-links/', + '/projects/invite/', +]; + +function routeFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return routeFiles(path); + return path.endsWith('.ts') && !path.endsWith('.test.ts') ? [path] : []; + }); +} + +describe('Caddy logging and keep-warm wiring', () => { + it('passes keep-warm on by default, at 5 s', () => { + expect(caddy?.environment?.SAM_KEEP_WARM).toBe('${SAM_KEEP_WARM:-on}'); + expect(caddy?.environment?.SAM_KEEP_WARM_INTERVAL).toBe('${SAM_KEEP_WARM_INTERVAL:-5s}'); + }); + + it('caps the Caddy log on disk', () => { + expect(caddy?.logging?.driver).toBe('json-file'); + expect(caddy?.logging?.options?.['max-size']).toBe('${CADDY_LOG_MAX_SIZE:-50m}'); + expect(caddy?.logging?.options?.['max-file']).toBe('${CADDY_LOG_MAX_FILES:-5}'); + }); + + it('applies the one redaction filter to the access log and to Caddy own log', () => { + expect(caddyfile.match(/import log-redaction\.caddy/g)).toHaveLength(2); + expect(caddyfile).toMatch(/log default \{\s*output stderr\s*import log-redaction\.caddy/); + expect(caddyfile).toMatch(/\tlog \{\s*output stdout\s*import log-redaction\.caddy/); + }); + + it('the redaction filter drops headers, query strings and path credentials', () => { + expect(redaction).toMatch(/^\trequest>headers delete$/m); + expect(redaction).toMatch(/^\tresp_headers delete$/m); + expect(redaction).toMatch(/^\theaders delete$/m); + expect(redaction).toContain('\t\tregexp "\\?.*$" "?"'); + expect(redaction).toContain('\t\tregexp "^/p/[^?]*" "/p/"'); + for (const prefix of PATH_CREDENTIAL_PREFIXES) { + expect(redaction).toMatch(new RegExp(`regexp "\\^\\([^"]*\\|?${prefix}\\|?[^"]*\\)`)); + } + }); + + // Every route whose path carries a credential-like parameter must be redacted in the logs. + // A new one fails here until it is added to caddy/log-redaction.caddy and to this list. + it('every route with a credential in its path is on the redaction list', () => { + const found = [ + ...routeFiles(join(REPO, 'apps/api/src/routes')), + join(REPO, 'apps/web/src/App.tsx'), + ] + .flatMap((file) => + [...readFileSync(file, 'utf8').matchAll(CREDENTIAL_ROUTE)].map( + (m) => `${relative(REPO, file)} ${m[1]}` + ) + ) + .sort(); + expect(found.length).toBeGreaterThanOrEqual(6); // the scan itself works + expect(found).toEqual(Object.keys(KNOWN_CREDENTIAL_ROUTES).sort()); + for (const prefix of Object.values(KNOWN_CREDENTIAL_ROUTES)) { + expect(PATH_CREDENTIAL_PREFIXES).toContain(prefix); + } + }); + + it('keeps the keep-warm check on a route that never serves a request', () => { + expect(caddyfile).toContain('import keep-warm/{$SAM_KEEP_WARM:on}.caddy'); + expect(keepWarm).toMatch(/^@sam_keep_warm expression false$/m); + expect(keepWarm).toContain('handle @sam_keep_warm {'); + expect(keepWarm).toContain('health_uri /health'); + expect(keepWarm).toContain('health_interval {$SAM_KEEP_WARM_INTERVAL:5s}'); + }); +}); diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts new file mode 100644 index 0000000000..9915c4621c --- /dev/null +++ b/scripts/selfhost/caddy-start.test.ts @@ -0,0 +1,92 @@ +/** + * deploy/selfhost/caddy/start.sh, the Caddy entrypoint docker-compose.yml runs, under /bin/sh with + * a stand-in `caddy` on PATH that records how it was started. Real Caddy and its busybox shell run + * the same script in live/access-log-keep-warm.live.test.ts. + * + * F21 L5: compose takes each port from the shell before the .env, so the deploy's range check can + * be sidestepped by `CELLD_INTERNAL_PORT=20001 docker compose up`. start.sh sees the ports the + * stack really runs with and refuses to start Caddy (the only way in for a node) when one lies + * inside the lease range from gateway.env. + */ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { BOX_RESERVED_PORTS } from './box-settings.js'; + +const START = resolve(import.meta.dirname, '../../deploy/selfhost/caddy/start.sh'); +let bin: string; + +beforeAll(() => { + bin = mkdtempSync(join(tmpdir(), 'sam-caddy-start-')); + const fake = join(bin, 'caddy'); + writeFileSync(fake, '#!/bin/sh\necho "caddy $*"\n'); + chmodSync(fake, 0o755); +}); +afterAll(() => rmSync(bin, { recursive: true, force: true })); + +/** The environment compose gives Caddy by default, plus gateway.env's range. */ +function composeEnv(): Record { + return { + ...Object.fromEntries( + Object.entries(BOX_RESERVED_PORTS).map(([name, port]) => [name, String(port)]) + ), + REVERSE_TUNNEL_PORT_RANGE_START: '20000', + REVERSE_TUNNEL_PORT_RANGE_END: '29999', + SAM_KEEP_WARM: 'on', + SAM_KEEP_WARM_INTERVAL: '5s', + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '60', + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '1m', + }; +} + +function startSh(env: Record): { status: number | null; out: string } { + const run = spawnSync('/bin/sh', [START], { + env: { PATH: `${bin}:/usr/bin:/bin`, ...env }, + encoding: 'utf8', + }); + return { status: run.status, out: `${run.stdout}${run.stderr}` }; +} + +describe('caddy/start.sh', () => { + it('starts Caddy with the box defaults', () => { + const run = startSh(composeEnv()); + expect(run.status, run.out).toBe(0); + expect(run.out).toContain('caddy run --config /etc/caddy/Caddyfile --adapter caddyfile'); + }); + + it.each(Object.keys(BOX_RESERVED_PORTS))( + 'refuses to start when %s lies inside the lease range', + (name) => { + const run = startSh({ ...composeEnv(), [name]: '20001' }); + expect(run.status).toBe(64); + expect(run.out).toContain(`${name} (20001) lies inside the reverse-tunnel range 20000-29999`); + expect(run.out).not.toContain('caddy run'); + } + ); + + it('accepts the range edges just outside a port (control)', () => { + const run = startSh({ + ...composeEnv(), + REVERSE_TUNNEL_PORT_RANGE_START: '7002', + REVERSE_TUNNEL_PORT_RANGE_END: '7999', + }); + expect(run.status, run.out).toBe(0); + }); + + it.each([ + [{ REVERSE_TUNNEL_PORT_RANGE_START: '' }, /RANGE_START\/END missing from gateway.env/], + [{ CELLD_INTERNAL_PORT: '' }, /CELLD_INTERNAL_PORT must be set to a port number/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '0' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '6x' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '2d' }, /SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be/], + [{ SAM_KEEP_WARM_INTERVAL: '9s' }, /SAM_KEEP_WARM_INTERVAL must be 1s to 6s/], + ])('refuses %j', (override, message) => { + const run = startSh({ ...composeEnv(), ...override }); + expect(run.status).toBe(64); + expect(run.out).toMatch(message); + }); +}); diff --git a/scripts/selfhost/mail-collector-compose.test.ts b/scripts/selfhost/mail-collector-compose.test.ts new file mode 100644 index 0000000000..f7d54c9c2c --- /dev/null +++ b/scripts/selfhost/mail-collector-compose.test.ts @@ -0,0 +1,69 @@ +/** + * The mail collector shows every sign-in code, so its exposure in docker-compose.yml is pinned: + * off by default (its own profile), loopback listeners only, no published ports, its own UI + * authentication required, a digest-pinned image, and Caddy started through start.sh (which + * refuses to serve the collector without its password). + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; + +interface Service { + profiles?: string[]; + image?: string; + command?: string[]; + ports?: unknown[]; + network_mode?: string; + user?: string; + read_only?: boolean; + cap_drop?: string[]; + entrypoint?: string[]; + env_file?: Array<{ path: string; required: boolean }>; +} + +const compose = parse( + readFileSync(resolve(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'), 'utf8') +) as { services: Record }; +const collector = compose.services['mail-collector']; +const caddy = compose.services.caddy; + +function flagValue(command: string[], flag: string): string | undefined { + const at = command.indexOf(flag); + return at >= 0 ? command[at + 1] : undefined; +} + +describe('mail-collector compose service', () => { + it('exists only behind its own profile', () => { + expect(collector?.profiles).toEqual(['mail-collector']); + }); + + it('listens on loopback only and publishes no ports', () => { + const command = collector?.command ?? []; + expect(flagValue(command, '--smtp')).toMatch(/^127\.0\.0\.1:/); + expect(flagValue(command, '--listen')).toMatch(/^127\.0\.0\.1:/); + expect(collector?.ports).toBeUndefined(); + }); + + it('requires its own UI authentication file, and refuses to start without it', () => { + expect(collector?.env_file).toEqual([ + { path: '${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector-ui.env', required: true }, + ]); + }); + + it('runs unprivileged from a digest-pinned image', () => { + expect(collector?.image).toMatch(/^axllent\/mailpit:v[\d.]+@sha256:[0-9a-f]{64}$/); + expect(collector?.user).toBe('65534:65534'); + expect(collector?.read_only).toBe(true); + expect(collector?.cap_drop).toEqual(['ALL']); + }); + + it('starts Caddy through start.sh with the collector switch file', () => { + expect(caddy?.entrypoint).toEqual(['/bin/sh', '/etc/caddy/start.sh']); + expect(caddy?.env_file).toContainEqual({ + path: '${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector.env', + required: false, + }); + }); +}); diff --git a/scripts/selfhost/versions.test.ts b/scripts/selfhost/versions.test.ts index b95060e601..a7af900e29 100644 --- a/scripts/selfhost/versions.test.ts +++ b/scripts/selfhost/versions.test.ts @@ -1,9 +1,47 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; import { celldReleaseTarget } from './celld-binary.js'; -import { CELLD_RELEASE_SHA256 } from './versions.js'; +import { CELLD_RELEASE_SHA256, CELLD_VERSION } from './versions.js'; + +const SELFHOST = resolve(import.meta.dirname, '../../deploy/selfhost'); +const read = (path: string) => readFileSync(resolve(SELFHOST, path), 'utf8'); +const COMPOSE = read('docker-compose.yml'); + +interface Service { + image?: string; + build?: string | { context: string; args?: Record }; + pull_policy?: string; +} +const services = (parse(COMPOSE) as { services: Record }).services; + +/** Locally built images and their Dockerfiles. */ +const LOCAL: Record = { + 'sam-selfhost-caddy:local': 'caddy/Dockerfile', + 'sam-selfhost-sam-mx:local': 'sam-mx/Dockerfile', +}; describe('pinned versions', () => { + it('deploys with the same celld version the compose stack runs', () => { + const image = /image:\s*ghcr\.io\/denoland\/celld:v([0-9.]+)@sha256:[0-9a-f]{64}/.exec(COMPOSE); + expect(image?.[1]).toBe(CELLD_VERSION); + }); + + it('pins every pulled compose image by digest, and every Dockerfile base image', () => { + const images = Object.values(services).map((service) => service.image ?? ''); + const pulled = images.filter((image) => !(image in LOCAL)); + expect(pulled.length).toBeGreaterThanOrEqual(4); + for (const image of pulled) expect(image).toMatch(/@sha256:[0-9a-f]{64}$/); + for (const dockerfilePath of Object.values(LOCAL)) { + const froms = [...read(dockerfilePath).matchAll(/^FROM\s+(\S+)/gm)].map((m) => m[1]); + expect(froms.length, dockerfilePath).toBeGreaterThanOrEqual(2); + for (const from of froms) expect(from, dockerfilePath).toMatch(/@sha256:[0-9a-f]{64}$/); + } + }); + it('has a checksum for every release target it can select', () => { for (const [os, cpu] of [ ['linux', 'x64'], @@ -15,3 +53,46 @@ describe('pinned versions', () => { expect(() => celldReleaseTarget('win32', 'x64')).toThrow(/set CELLD_BIN/); }); }); + +// F11 (#2666): image builds are explicit and reproducible. The behaviour (the binary carries the +// pinned modules; the upgrade builds only on changed inputs) is proven by the live suite's image +// build and upgrade.test.ts; this pins the static wiring. +describe('locally built images', () => { + it('are the only services with a build section, never pulled from a registry', () => { + const built = Object.entries(services).filter(([, service]) => service.build !== undefined); + expect(built.map(([, service]) => service.image).sort()).toEqual(Object.keys(LOCAL).sort()); + for (const [name, service] of built) expect(service.pull_policy, name).toBe('never'); + }); + + it('pins every Caddy module by version and verifies the build carries exactly those', () => { + const dockerfile = read('caddy/Dockerfile'); + const modules = [...dockerfile.matchAll(/^ARG (CADDY_[A-Z_]+_MODULE)=(\S+)$/gm)]; + expect(modules.map((m) => m[1])).toEqual(['CADDY_DNS_MODULE', 'CADDY_RATELIMIT_MODULE']); + for (const [, , module] of modules) expect(module).toMatch(/^[\w./-]+@v\d+\.\d+\.\d+$/); + // Modules come from the public proxy, checked against the Go checksum database, with no + // toolchain download; the build refuses an unpinned module and checks the binary's modules. + expect(dockerfile).toContain('GOPROXY=https://proxy.golang.org'); + expect(dockerfile).toContain('GOSUMDB=sum.golang.org'); + expect(dockerfile).toContain('GOTOOLCHAIN=local'); + expect(dockerfile).toContain('must be pinned as @'); + expect(dockerfile).toContain('go version -m /usr/bin/caddy'); + // Compose's default for the DNS module is the Dockerfile's, so both builds agree. + const caddyBuild = services.caddy?.build as { args: Record }; + const dnsDefault = modules.find((m) => m[1] === 'CADDY_DNS_MODULE')?.[2]; + expect(caddyBuild.args.CADDY_DNS_MODULE).toBe(`\${CADDY_DNS_MODULE:-${dnsDefault}}`); + }); + + it('sends Caddy an empty build context, so Caddyfile edits never change the image', () => { + const ignore = read('caddy/.dockerignore') + .split('\n') + .filter((line) => line.trim() && !line.startsWith('#')); + expect(ignore).toEqual(['*']); + expect(read('caddy/Dockerfile')).not.toMatch(/^(COPY|ADD)\s+(?!--from=)/m); + }); + + it('builds sam-mx from go.sum-pinned modules', () => { + const dockerfile = read('sam-mx/Dockerfile'); + expect(dockerfile).toMatch(/^COPY go\.mod go\.sum \.\/$/m); + expect(read('sam-mx/go.sum').trim().length).toBeGreaterThan(0); + }); +}); diff --git a/scripts/selfhost/vitest.config.ts b/scripts/selfhost/vitest.config.ts index 64c1075eff..bd142ba7c6 100644 --- a/scripts/selfhost/vitest.config.ts +++ b/scripts/selfhost/vitest.config.ts @@ -4,6 +4,8 @@ export default defineConfig({ test: { root: import.meta.dirname, include: ['**/*.test.ts'], - exclude: ['**/node_modules/**'], + // The live suite (real Caddy, frp and celld in Docker) has its own config: + // pnpm selfhost:live-test. + exclude: ['live/**', '**/node_modules/**'], }, }); From ed1c92ca2e9100bad533e9b606005258b6da9bfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 02:22:10 +0000 Subject: [PATCH 02/65] fix(selfhost): check box ports as docker compose runs them (F21 L5) Compose takes a variable from the shell before the .env, so `CELLD_INTERNAL_PORT=20001 docker compose up` put celld's operator API inside the lease range the deploy had checked against the .env only. The deploy (and upgrade's box loader) now apply shell overrides of every BOX_RESERVED_PORTS name before the range check and report each one. The deploy harness strips those names from the test runner's environment so the suite stays hermetic. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/box-settings.test.ts | 60 +++++++++++++++++++++++++++ scripts/selfhost/box-settings.ts | 23 ++++++++++ scripts/selfhost/deploy-harness.ts | 8 +++- scripts/selfhost/deploy.test.ts | 14 +++++++ scripts/selfhost/deploy.ts | 8 +++- 5 files changed, 111 insertions(+), 2 deletions(-) diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index 2f80af0c3e..a3fd26401e 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -12,6 +12,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; import { BOX_RESERVED_PORTS, @@ -24,6 +25,7 @@ import { resolveTunnelSettings, trimSlashes, tunnelWorkerVars, + withComposePortOverrides, } from './box-settings.js'; import { syncGatewayEnv } from './deploy-steps.js'; import { parseDotenv } from './secret-files.js'; @@ -219,6 +221,64 @@ describe('presignVars', () => { }); }); +const COMPOSE_TEXT = readFileSync( + join(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'), + 'utf8' +); + +describe('BOX_RESERVED_PORTS', () => { + it('matches the defaults docker-compose.yml actually uses', () => { + const defaults = [...COMPOSE_TEXT.matchAll(/\$\{([A-Z_]+):-(\d+)\}/g)].map( + (m) => [m[1]!, Number(m[2])] as const + ); + for (const [name, port] of Object.entries(BOX_RESERVED_PORTS)) { + const used = defaults.filter(([found]) => found === name).map(([, value]) => value); + expect(used.length, name).toBeGreaterThan(0); + // Every interpolation of the port in the file falls back to the same default. + expect(new Set(used), name).toEqual(new Set([port])); + } + }); + + // F21 L5: caddy/start.sh can only check the ports compose passes it. + it('are all passed to Caddy, whose start.sh refuses any inside the lease range', () => { + const compose = parse(COMPOSE_TEXT) as { + services: { caddy: { environment: Record } }; + }; + const startSh = readFileSync( + join(import.meta.dirname, '../../deploy/selfhost/caddy/start.sh'), + 'utf8' + ); + for (const [name, port] of Object.entries(BOX_RESERVED_PORTS)) { + expect(compose.services.caddy.environment[name], name).toBe(`\${${name}:-${port}}`); + expect(startSh, name).toMatch(new RegExp(`\\b${name}\\b`)); + } + }); +}); + +describe('withComposePortOverrides (F21 L5)', () => { + it('applies a shell port override, as docker compose does, and reports it', () => { + const { box, overridden } = withComposePortOverrides( + { CELLD_INTERNAL_PORT: '7001', SAM_DOMAIN: 'box.example' }, + { CELLD_INTERNAL_PORT: '20001', SAM_DOMAIN: 'other.example', PATH: '/usr/bin' } + ); + expect(overridden).toEqual(['CELLD_INTERNAL_PORT']); + expect(box).toEqual({ CELLD_INTERNAL_PORT: '20001', SAM_DOMAIN: 'box.example' }); + // ...so the range check sees the port compose will really bind. + expect(() => resolveTunnelPortRange(box)).toThrow(/contains CELLD_INTERNAL_PORT \(20001\)/); + }); + + it('control: without a shell override the .env value is checked and passes', () => { + const { box, overridden } = withComposePortOverrides({ CELLD_INTERNAL_PORT: '7001' }, {}); + expect(overridden).toEqual([]); + expect(resolveTunnelPortRange(box)).toEqual({ start: 20000, end: 29999 }); + }); + + it('also catches a shell port for a name the .env never set', () => { + const { box } = withComposePortOverrides({}, { FRPS_BIND_PORT: '25000' }); + expect(() => resolveTunnelPortRange(box)).toThrow(/contains FRPS_BIND_PORT \(25000\)/); + }); +}); + describe('gatewayEnvAction', () => { const settings = resolveTunnelSettings({}); const current = renderGatewayEnv(SECRET, settings); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index 928bb374f1..e743865c00 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -41,6 +41,29 @@ export const BOX_RESERVED_PORTS: Readonly> = { MAIL_COLLECTOR_UI_PORT: DEFAULT_MAIL_COLLECTOR_UI_PORT, }; +/** + * The box settings with the port values docker compose will actually run with. Compose takes a + * variable from the shell before the .env file, so `CELLD_INTERNAL_PORT=20001 docker compose up` + * runs celld's operator API on 20001 whatever the .env says. The deploy and upgrade run in the + * operator's shell, so they apply the same override to every box port before checking the lease + * range, and report each one. (caddy/start.sh repeats the check inside the running stack, for a + * compose command run from another shell.) + */ +export function withComposePortOverrides( + box: Readonly>, + hostEnv: NodeJS.ProcessEnv +): { box: Record; overridden: string[] } { + const effective: Record = { ...box }; + const overridden: string[] = []; + for (const name of Object.keys(BOX_RESERVED_PORTS)) { + const value = hostEnv[name]; + if (value === undefined || value === box[name]) continue; + effective[name] = value; + overridden.push(name); + } + return { box: effective, overridden }; +} + export interface PortRange { start: number; end: number; diff --git a/scripts/selfhost/deploy-harness.ts b/scripts/selfhost/deploy-harness.ts index c3f16cfc5c..e654c5edd6 100644 --- a/scripts/selfhost/deploy-harness.ts +++ b/scripts/selfhost/deploy-harness.ts @@ -6,6 +6,8 @@ import { spawn } from 'node:child_process'; import { writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; +import { BOX_RESERVED_PORTS } from './box-settings.js'; + const DEPLOY = resolve(import.meta.dirname, 'deploy.ts'); /** The repository's own tsx, not `npx tsx` (npx resolution costs seconds under load). */ const TSX = resolve(import.meta.dirname, '../../node_modules/.bin/tsx'); @@ -34,7 +36,11 @@ export function runTsx( env: NodeJS.ProcessEnv = {} ): Promise<{ status: number; out: string }> { return new Promise((done, fail) => { - const child = spawn(TSX, [script, ...args], { env: { ...process.env, ...env } }); + // The deploy honours shell port overrides as docker compose does (withComposePortOverrides), + // so the test runner's own environment must not leak any: only `env` sets them. + const inherited = { ...process.env }; + for (const name of Object.keys(BOX_RESERVED_PORTS)) delete inherited[name]; + const child = spawn(TSX, [script, ...args], { env: { ...inherited, ...env } }); let out = ''; child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())); child.stderr.on('data', (chunk: Buffer) => (out += chunk.toString())); diff --git a/scripts/selfhost/deploy.test.ts b/scripts/selfhost/deploy.test.ts index c31cff28fa..7d1e723d2a 100644 --- a/scripts/selfhost/deploy.test.ts +++ b/scripts/selfhost/deploy.test.ts @@ -160,4 +160,18 @@ describe('selfhost:deploy', { timeout: CHILD_TEST_TIMEOUT_MS }, () => { expect(result.status).toBe(1); expect(result.out).toContain('VM_AGENT_REQUIRED_VERSION is generated'); }); + + // F21 L5: `CELLD_INTERNAL_PORT=20001 docker compose up` would run celld's operator API inside the + // lease range whatever the .env says; the deploy run from the same shell must refuse it. + it('refuses a box port that a shell override puts inside the lease range', async () => { + const envFile = writeBox(dir, ['CELLD_INTERNAL_PORT=7001']); + const refused = await runDeploy(envFile, ['--init'], { CELLD_INTERNAL_PORT: '20001' }); + expect(refused.status).not.toBe(0); + expect(refused.out).toContain('CELLD_INTERNAL_PORT from the shell environment overrides'); + expect(refused.out).toMatch(/contains CELLD_INTERNAL_PORT \(20001\); a node could bind it/); + expect(existsSync(join(state, 'gateway.env'))).toBe(false); + // Control: the same box without the override initialises. + const init = await runDeploy(envFile, ['--init']); + expect(init.status, init.out).toBe(0); + }); }); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 3434bfbda7..859c5b8d01 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -53,6 +53,7 @@ import { STORAGE_SECRET_KEYS, type TunnelSettings, tunnelWorkerVars, + withComposePortOverrides, } from './box-settings.js'; import { verifyNewVersionServes } from './celld-adopt.js'; import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; @@ -192,7 +193,12 @@ function readDeployInputs(): DeployInputs { const envFile = resolve(values['env-file'] ?? join(REPO_ROOT, 'deploy/selfhost/.env')); // The .env holds the bucket credential, which can read every deployed secret. assertPrivateFile(envFile); - const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // Box ports as docker compose will run them: a shell override beats the .env (F21 L5). + const { box, overridden } = withComposePortOverrides( + parseDotenv(readFileSync(envFile, 'utf8'), envFile), + process.env + ); + for (const name of overridden) log(`${name} from the shell environment overrides ${envFile}`); // Same default and base directory docker compose uses for SAM_SELFHOST_STATE_DIR. const stateDir = resolve( dirname(envFile), From 57e400a4094e34fbe55ecb5aae79e57e46334533 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 02:22:10 +0000 Subject: [PATCH 03/65] fix(selfhost): upgrade rebuilds an image only when its build inputs changed (F11) `selfhost:upgrade` ran `docker compose up -d --build` whenever any compose input changed, rebuilding (with network access) on every such upgrade. It now compares each locally built service's build section in docker-compose.yml at both refs and the files in its build context (a context whose .dockerignore is `*` counts only its Dockerfile), builds only the changed services the box runs with an explicit `docker compose build `, and restarts with a plain `up -d`. The printed rollback rebuilds the same way. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/image-rebuilds.ts | 76 +++++++++++++ scripts/selfhost/upgrade-lib.ts | 129 ++++++++++++++++------ scripts/selfhost/upgrade.test.ts | 172 +++++++++++++++++++++++++++-- 3 files changed, 336 insertions(+), 41 deletions(-) create mode 100644 scripts/selfhost/image-rebuilds.ts diff --git a/scripts/selfhost/image-rebuilds.ts b/scripts/selfhost/image-rebuilds.ts new file mode 100644 index 0000000000..4adf8f31ca --- /dev/null +++ b/scripts/selfhost/image-rebuilds.ts @@ -0,0 +1,76 @@ +/** + * Which locally built images a self-host upgrade must rebuild (F11). `selfhost:upgrade` used to + * run `docker compose up -d --build` whenever any compose input changed; a build fetches base + * images and modules from the network, so it now runs only for a service whose image would differ. + */ +import { posix } from 'node:path'; + +import { parse as parseYaml } from 'yaml'; + +/** The compose file, relative to the repository root (what `git show :` reads). */ +export const COMPOSE_PATH = 'deploy/selfhost/docker-compose.yml'; + +interface ComposeBuildService { + build?: string | { context?: string; dockerfile?: string; args?: unknown }; +} + +/** Each locally built service's build section, from a docker-compose.yml text (null: none). */ +function buildSections(compose: string | null): Map { + const sections = new Map(); + if (compose === null) return sections; + const parsed = parseYaml(compose) as { services?: Record } | null; + for (const [name, service] of Object.entries(parsed?.services ?? {})) { + if (service?.build !== undefined) sections.set(name, service.build); + } + return sections; +} + +/** Whether a .dockerignore sends nothing to the build: its only pattern is `*`. */ +function ignoresEverything(dockerignore: string | null): boolean { + const patterns = (dockerignore ?? '') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')); + return patterns.length === 1 && patterns[0] === '*'; +} + +/** + * The locally built services whose image this upgrade must rebuild, from the files that changed + * between the two refs and docker-compose.yml at each: a service is rebuilt when its build section + * changed (context, Dockerfile, build args such as the pinned Caddy module versions) or a file in + * its build context did. A context whose .dockerignore is exactly `*` sends nothing to the build + * (caddy/), so only its Dockerfile and .dockerignore count; README files never do. + * + * Every other upgrade leaves the images alone (F11): a build fetches base images and modules from + * the network, so it runs only when the image it would produce differs. + */ +export function imageRebuilds( + changed: readonly string[], + composeFrom: string | null, + composeTo: string, + readFileAtTo: (path: string) => string | null = () => null +): string[] { + const before = buildSections(composeFrom); + const rebuilds: string[] = []; + for (const [service, build] of buildSections(composeTo)) { + if (JSON.stringify(before.get(service)) !== JSON.stringify(build)) { + rebuilds.push(service); + continue; + } + const contextRel = typeof build === 'string' ? build : (build?.context ?? '.'); + const context = posix.join(posix.dirname(COMPOSE_PATH), contextRel); + const dockerfileName = + (typeof build === 'object' ? build?.dockerfile : undefined) ?? 'Dockerfile'; + const dockerfile = posix.join(context, dockerfileName); + const ignore = posix.join(context, '.dockerignore'); + const emptyContext = ignoresEverything(readFileAtTo(ignore)); + const touched = changed.some( + (file) => + file === dockerfile || + file === ignore || + (!emptyContext && file.startsWith(`${context}/`) && !file.endsWith('.md')) + ); + if (touched) rebuilds.push(service); + } + return rebuilds; +} diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 416b3a2143..21cf4e6226 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -7,11 +7,13 @@ * new code. It never regenerates platform keys. Every deploy call gets this box's * `--env-file` and `--state-dir` (and `--secrets` when given): without them the deploy would * read the checkout's default .env and .state, a different box. - * 4. Restart the stack (`docker compose up -d --build`) only when compose inputs changed: a - * non-README file under deploy/selfhost/, a compose file the box's COMPOSE_FILE selects, or a - * generated file in .state/ that step 3 changed. - * This must precede step 5: deploy refuses to update the Worker while gateway.env differs - * from what the running frps and Caddy read. + * 4. Rebuild a locally built image (caddy, sam-mx) only when its build inputs changed + * (imageRebuilds: its build section in docker-compose.yml or a file in its build context), + * with an explicit `docker compose build `; then restart the stack + * (`docker compose up -d`, never `--build`) only when compose inputs changed: a non-README file + * under deploy/selfhost/, a compose file the box's COMPOSE_FILE selects, or a generated file + * in .state/ that step 3 changed. This must precede step 5: deploy refuses to update the + * Worker while gateway.env differs from what the running frps and Caddy read. * 5. `pnpm selfhost:deploy`: applies D1 migrations (celld d1 migrations apply) and publishes the * Worker with `celld deploy`, which applies Durable Object migrations (celld accepts only * `new_sqlite_classes`); it waits for /health itself. @@ -33,7 +35,9 @@ import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { withComposePortOverrides } from './box-settings.js'; import { log, REPO_ROOT } from './deploy-steps.js'; +import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; import { assertPrivateFile, parseDotenv, replacePrivateFile } from './secret-files.js'; export const SELFHOST_DIR = join(REPO_ROOT, 'deploy/selfhost'); @@ -74,6 +78,8 @@ export interface UpgradeOptions { export interface UpgradeResult { from: string; to: string; + /** Locally built services this upgrade rebuilt (explicitly, before the restart). */ + imagesRebuilt: string[]; composeRestarted: boolean; migrationsChanged: boolean; rollback: string[]; @@ -131,7 +137,11 @@ export function loadBox( ): BoxContext { if (!existsSync(envFile)) throw new Error(`${envFile} does not exist`); assertPrivateFile(envFile); - const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // Ports as docker compose runs them (a shell override beats the .env), as deploy.ts reads them. + const { box } = withComposePortOverrides( + parseDotenv(readFileSync(envFile, 'utf8'), envFile), + process.env + ); if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); return { box, @@ -194,16 +204,21 @@ function rollbackSteps( from: string, migrationsChanged: boolean, composeChanged: boolean, - boxArgs: readonly string[] = [] + boxArgs: readonly string[] = [], + imagesRebuilt: readonly string[] = [] ): string[] { const compose = (args: string[]) => ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '); const deploy = ['pnpm selfhost:deploy', ...boxArgs.map(shellWord)].join(' '); + // The images the upgrade rebuilt are rebuilt again from the old ref, never with `up --build`. + const rebuild = imagesRebuilt.length > 0 ? [compose(['build', ...imagesRebuilt])] : []; if (!migrationsChanged) { return [ `git checkout ${from}`, 'pnpm install --frozen-lockfile', - ...(composeChanged ? [`${deploy} --init`, compose(['up', '-d', '--build'])] : []), + ...(composeChanged || rebuild.length > 0 + ? [`${deploy} --init`, ...rebuild, compose(['up', '-d'])] + : []), deploy, ]; } @@ -216,6 +231,7 @@ function rollbackSteps( '# bucket contents into it, put your pre-upgrade .state back, then:', `git checkout ${from}`, 'pnpm install --frozen-lockfile', + ...rebuild, compose(['up', '-d']), ]; } @@ -262,41 +278,69 @@ function resolveUpgradeTarget(git: Git, ref: string): string { } } +/** What an upgrade between two refs must do, decided before the checkout. */ +interface UpgradePlan { + to: string; + composeFilesChanged: boolean; + /** Locally built services whose build inputs changed (imageRebuilds). */ + rebuilds: string[]; + boxArgs: string[]; +} + +/** What a (possibly failed) upgrade has done so far, for the rollback it prints. */ +interface UpgradeProgress { + stateChanged: boolean; + imagesRebuilt: string[]; +} + +function restartReason(composeFilesChanged: boolean, stateChanged: boolean): string { + if (composeFilesChanged) return 'compose files'; + return stateChanged ? 'generated state' : 'images'; +} + /** - * Checks out `to`, runs `--init` (it may rewrite generated compose inputs), restarts the stack - * when its inputs changed, deploys and checks health. Returns whether the stack was restarted. - * Sets `progress.stateChanged` as soon as it knows, so a failure later can still say so. + * Checks out `to`, runs `--init` (it may rewrite generated compose inputs), rebuilds the images + * whose build inputs changed, restarts the stack when its inputs changed, deploys and checks + * health. Returns whether the stack was restarted. Records in `progress` what it has done as soon + * as it knows, so a failure later can still say so. */ async function applyUpgrade( ctx: BoxContext, opts: UpgradeOptions, git: Git, - to: string, - composeFilesChanged: boolean, - boxArgs: string[], - progress: { stateChanged: boolean } + plan: UpgradePlan, + progress: UpgradeProgress ): Promise { const pnpm = (args: string[]) => check(ctx.run('pnpm', args), `pnpm ${args.join(' ')}`); - git(['checkout', '--detach', to]); + const docker = (args: string[]) => + check(ctx.run('docker', composeArgs(ctx, args)), `docker compose ${args.join(' ')}`); + git(['checkout', '--detach', plan.to]); pnpm(['install', '--frozen-lockfile']); const before = stateFingerprint(ctx.stateDir); - pnpm(['selfhost:deploy', '--init', ...boxArgs]); + pnpm(['selfhost:deploy', '--init', ...plan.boxArgs]); const stateChanged = stateFingerprint(ctx.stateDir) !== before; progress.stateChanged = stateChanged; + if (plan.rebuilds.length > 0) { + // Only services the box runs (its COMPOSE_PROFILES): sam-mx is not built on a box without + // inbound mail. + const active = new Set(docker(['config', '--services']).split('\n').filter(Boolean)); + progress.imagesRebuilt = plan.rebuilds.filter((service) => active.has(service)); + if (progress.imagesRebuilt.length > 0) { + ctx.log(`rebuilding ${progress.imagesRebuilt.join(', ')} (build inputs changed)`); + docker(['build', ...progress.imagesRebuilt]); + } + } let composeRestarted = false; - if (composeFilesChanged || stateChanged) { + if (plan.composeFilesChanged || stateChanged || progress.imagesRebuilt.length > 0) { ctx.log( - `restarting the stack (${composeFilesChanged ? 'compose files' : 'generated state'} changed)` - ); - check( - ctx.run('docker', composeArgs(ctx, ['up', '-d', '--build'])), - 'docker compose up -d --build' + `restarting the stack (${restartReason(plan.composeFilesChanged, stateChanged)} changed)` ); + docker(['up', '-d']); composeRestarted = true; } else { ctx.log('compose inputs unchanged; the stack keeps running'); } - pnpm(['selfhost:deploy', ...boxArgs]); + pnpm(['selfhost:deploy', ...plan.boxArgs]); if (!(await opts.checkHealth())) throw new Error('the API is not healthy after the upgrade'); return composeRestarted; } @@ -317,13 +361,27 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise const to = resolveUpgradeTarget(git, opts.to); if (pendingFrom === null && head === to) { ctx.log('already at that ref; nothing to do'); - return { from, to, composeRestarted: false, migrationsChanged: false, rollback: [] }; + return { + from, + to, + imagesRebuilt: [], + composeRestarted: false, + migrationsChanged: false, + rollback: [], + }; } const changed = git(['diff', '--name-only', from, to]).split('\n').filter(Boolean); // Resuming: the failed run may have restarted the stack on files this diff no longer shows. const composeFilesChanged = pendingFrom !== null || composeInputsChanged(changed, ctx.composeFiles); const migrationsChanged = changed.some((f) => f.startsWith(MIGRATIONS_DIR)); + const fileAt = (ref: string, path = COMPOSE_PATH): string | null => { + const shown = ctx.run('git', ['show', `${ref}:${path}`]); + return shown.status === 0 ? shown.stdout : null; + }; + const composeTo = fileAt(to); + if (composeTo === null) throw new Error(`${to} has no ${COMPOSE_PATH}`); + const rebuilds = imageRebuilds(changed, fileAt(from), composeTo, (path) => fileAt(to, path)); if (pendingFrom !== null) { ctx.log(`resuming an unfinished upgrade that started from ${pendingFrom.slice(0, 12)}`); } @@ -340,16 +398,14 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise mkdirSync(ctx.stateDir, { recursive: true, mode: 0o700 }); replacePrivateFile(pendingPath, `${JSON.stringify({ from })}\n`); } - const progress = { stateChanged: false }; + const progress: UpgradeProgress = { stateChanged: false, imagesRebuilt: [] }; let composeRestarted: boolean; try { composeRestarted = await applyUpgrade( ctx, opts, git, - to, - composeFilesChanged, - boxArgs, + { to, composeFilesChanged, rebuilds, boxArgs }, progress ); } catch (error) { @@ -360,15 +416,24 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise from, migrationsChanged, composeFilesChanged || progress.stateChanged, - boxArgs + boxArgs, + progress.imagesRebuilt ); for (const step of rollback) ctx.log(` ${step}`); throw error; } rmSync(pendingPath, { force: true }); - const rollback = rollbackSteps(ctx, from, migrationsChanged, composeRestarted, boxArgs); + const { imagesRebuilt } = progress; + const rollback = rollbackSteps( + ctx, + from, + migrationsChanged, + composeRestarted, + boxArgs, + imagesRebuilt + ); ctx.log(`upgraded to ${to}; healthy. To roll back:`); for (const step of rollback) ctx.log(` ${step}`); - return { from, to, composeRestarted, migrationsChanged, rollback }; + return { from, to, imagesRebuilt, composeRestarted, migrationsChanged, rollback }; } diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 1a0ade0dd3..16a6446494 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -2,8 +2,9 @@ * selfhost:upgrade orchestration (upgrade-lib.ts) with git, pnpm and docker answered by a fake * runner. Asserts the order of the steps, that no backup is taken, that the stack restarts only * when compose inputs change (files in deploy/selfhost/, selected compose files or generated - * .state/ files), that a failed upgrade can be retried, and that the printed rollback selects the - * same box and matches whether the upgrade carried a D1 migration. + * .state/ files), that an image is rebuilt only by an explicit `docker compose build` of a service + * whose build inputs changed (never `up --build`), that a failed upgrade can be retried, and that + * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -11,6 +12,7 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { imageRebuilds } from './image-rebuilds.js'; import { type BoxContext, composeFilesFor, @@ -32,6 +34,29 @@ let failDeploy: boolean; let initRewritesState: boolean; /** What the fake checkout has checked out (`git checkout --detach` moves it). */ let head: string; +/** docker-compose.yml at each ref, and the services `docker compose config --services` lists. */ +let composeAt: Record; +let activeServices: string[]; + +const COMPOSE = (dnsModule = 'github.com/caddy-dns/googleclouddns@v1.1.0') => ` +services: + celld: + image: ghcr.io/denoland/celld@sha256:${'1'.repeat(64)} + caddy: + build: + context: ./caddy + args: + CADDY_DNS_MODULE: \${CADDY_DNS_MODULE:-${dnsModule}} + image: sam-selfhost-caddy:local + sam-mx: + profiles: [mail-in] + build: ./sam-mx + image: sam-selfhost-sam-mx:local +`; +/** Files at the target ref that the upgrade reads (the caddy context's .dockerignore). */ +const FILES_AT_TO: Record = { + 'deploy/selfhost/caddy/.dockerignore': '# empty context\n*\n', +}; function run(command: string, args: string[]): RunResult { const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); @@ -42,6 +67,18 @@ function run(command: string, args: string[]): RunResult { if (args[0] === 'checkout') head = args[2] ?? head; if (args[0] === 'rev-parse') return ok(TO); if (args[0] === 'diff') return ok(diff.join('\n')); + if (args[0] === 'show') { + const [ref = '', path = ''] = (args[1] ?? '').split(':'); + const text = + path === 'deploy/selfhost/docker-compose.yml' + ? composeAt[ref] + : ref === TO + ? FILES_AT_TO[path] + : undefined; + return text === undefined || text === null + ? { status: 128, stdout: '', stderr: 'does not exist' } + : ok(text); + } steps.push(line); return ok(); } @@ -50,6 +87,7 @@ function run(command: string, args: string[]): RunResult { if (deploy && args.includes('--init') && initRewritesState) { writeFileSync(join(root, 'state/gateway.env'), 'FRPS_PORT_RANGE=21000-21999\n'); } + if (command === 'docker' && args.includes('config')) return ok(activeServices.join('\n')); if (deploy && !args.includes('--init') && failDeploy) { return { status: 1, stdout: '', stderr: 'migration 0219 failed' }; } @@ -82,6 +120,8 @@ beforeEach(() => { failDeploy = false; initRewritesState = false; head = FROM; + composeAt = { [FROM]: COMPOSE(), [TO]: COMPOSE() }; + activeServices = ['celld', 'caddy']; }); afterEach(() => rmSync(root, { recursive: true, force: true })); @@ -115,7 +155,7 @@ describe('runUpgrade', () => { diff = ['deploy/selfhost/docker-compose.yml', 'deploy/selfhost/README.md']; const result = await upgrade(); const order = compact(); - const up = order.indexOf('docker compose up -d --build'); + const up = order.indexOf('docker compose up -d'); expect(up).toBeGreaterThan(order.indexOf(`pnpm selfhost:deploy --init ${BOX_ARGS}`)); expect(up).toBeLessThan(order.indexOf(`pnpm selfhost:deploy ${BOX_ARGS}`)); expect(result.composeRestarted).toBe(true); @@ -191,7 +231,7 @@ describe('runUpgrade', () => { 'pnpm install --frozen-lockfile', `pnpm selfhost:deploy --init ${BOX_ARGS}`, // The failed run may have restarted the stack already, so the retry restarts it too. - 'docker compose up -d --build', + 'docker compose up -d', `pnpm selfhost:deploy ${BOX_ARGS}`, ]); expect(retry.from).toBe(FROM); @@ -226,7 +266,7 @@ describe('runUpgrade', () => { await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); const printed = logs.join('\n').replaceAll(root, ''); expect(printed).toContain(`pnpm selfhost:deploy ${BOX_ARGS} --init`); - expect(printed).toMatch(/docker compose .* up -d --build/); + expect(printed).toMatch(/docker compose .* up -d$/m); // A fresh box at FROM for the success case. rmSync(join(root, 'state', UPGRADE_PENDING_FILE)); @@ -235,7 +275,7 @@ describe('runUpgrade', () => { failDeploy = false; const rollback = (await upgrade()).rollback.map((step) => step.replaceAll(root, '')); expect(rollback).toContain(`pnpm selfhost:deploy ${BOX_ARGS} --init`); - expect(rollback.some((step) => /^docker compose .* up -d --build$/.test(step))).toBe(true); + expect(rollback.some((step) => /^docker compose .* up -d$/.test(step))).toBe(true); }); it('fails when the API is unhealthy after the deploy', async () => { @@ -271,7 +311,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { expect(restartCommand()).toBe( `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + - `--env-file /real.env up -d --build` + `--env-file /real.env up -d` ); }); @@ -280,7 +320,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const ctx = boxFromEnv([]); await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); expect(restartCommand()).toBe( - `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} --env-file /real.env up -d --build` + `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} --env-file /real.env up -d` ); }); @@ -292,7 +332,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { expect(composeSteps.map((step) => step.replaceAll(root, ''))).toEqual([ `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + - `--env-file /real.env up -d --build`, + `--env-file /real.env up -d`, ]); }); @@ -324,6 +364,120 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { (await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true })).composeRestarted ).toBe(false); }); + + // F11: the explicit build selects the same box as every other compose command. + it('rebuilds with every selected compose file and the box .env, forward and in the rollback', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + const ctx = boxFromEnv(['COMPOSE_FILE=docker-compose.yml:docker-compose.override.yml']); + const result = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); + const build = + `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + + `--env-file /real.env build caddy`; + expect(steps).toContain(build); + const rollback = result.rollback.map((step) => step.replaceAll(root, '')); + expect(rollback.indexOf(build)).toBeGreaterThan(-1); + expect(rollback.indexOf(build)).toBeLessThan(rollback.findIndex((s) => s.endsWith(' up -d'))); + }); +}); + +// F11: an image build fetches base images and modules from the network, so it must be explicit +// and happen only when the image it produces differs. +describe('runUpgrade image builds', () => { + const dockerSteps = () => compact().filter((step) => step.startsWith('docker')); + + it('rebuilds caddy explicitly, then restarts without --build, when its Dockerfile changed', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + const result = await upgrade(); + expect(dockerSteps()).toEqual([ + 'docker compose config --services', + 'docker compose build caddy', + 'docker compose up -d', + ]); + const order = compact(); + expect(order.indexOf('docker compose build caddy')).toBeGreaterThan( + order.indexOf(`pnpm selfhost:deploy --init ${BOX_ARGS}`) + ); + expect(order.indexOf('docker compose up -d')).toBeLessThan( + order.indexOf(`pnpm selfhost:deploy ${BOX_ARGS}`) + ); + expect(result.imagesRebuilt).toEqual(['caddy']); + // Rolling back rebuilds the old image the same explicit way. + expect(result.rollback.map((step) => step.replaceAll(root, ''))).toEqual([ + `git checkout ${FROM}`, + 'pnpm install --frozen-lockfile', + `pnpm selfhost:deploy ${BOX_ARGS} --init`, + 'docker compose -f compose.yml --env-file /box.env build caddy', + 'docker compose -f compose.yml --env-file /box.env up -d', + `pnpm selfhost:deploy ${BOX_ARGS}`, + ]); + }); + + it('rebuilds caddy when the compose build args changed (a new pinned module)', async () => { + diff = ['deploy/selfhost/docker-compose.yml']; + composeAt[TO] = COMPOSE('github.com/caddy-dns/googleclouddns@v1.2.0'); + expect((await upgrade()).imagesRebuilt).toEqual(['caddy']); + }); + + it('does not rebuild caddy for a Caddyfile change: its build context is empty', async () => { + diff = ['deploy/selfhost/caddy/Caddyfile', 'deploy/selfhost/caddy/sam.d/frp.caddy']; + const result = await upgrade(); + expect(dockerSteps()).toEqual(['docker compose up -d']); + expect(result.imagesRebuilt).toEqual([]); + expect(result.composeRestarted).toBe(true); + }); + + it('does not build sam-mx on a box that does not run it (mail-in profile off)', async () => { + diff = ['deploy/selfhost/sam-mx/session.go']; + const result = await upgrade(); + expect(dockerSteps()).toEqual(['docker compose config --services', 'docker compose up -d']); + expect(result.imagesRebuilt).toEqual([]); + }); + + it('builds sam-mx when the box runs it and its source changed (control)', async () => { + diff = ['deploy/selfhost/sam-mx/session.go']; + activeServices = ['celld', 'caddy', 'sam-mx']; + expect((await upgrade()).imagesRebuilt).toEqual(['sam-mx']); + expect(dockerSteps()).toContain('docker compose build sam-mx'); + }); + + it('prints the rebuild in the rollback when the deploy after it fails', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + failDeploy = true; + await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); + const printed = logs.join('\n').replaceAll(root, ''); + expect(printed).toContain( + 'docker compose -f compose.yml --env-file /box.env build caddy' + ); + }); + + it('never passes --build to docker compose', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile', 'deploy/selfhost/docker-compose.yml']; + await upgrade(); + expect(steps.some((step) => step.includes('--build'))).toBe(false); + }); +}); + +describe('imageRebuilds', () => { + it('counts every file of a context that sends its files to the build', () => { + expect(imageRebuilds(['deploy/selfhost/sam-mx/go.sum'], COMPOSE(), COMPOSE())).toEqual([ + 'sam-mx', + ]); + }); + + it('ignores README files and unrelated paths', () => { + expect( + imageRebuilds( + ['deploy/selfhost/sam-mx/README.md', 'apps/api/src/index.ts'], + COMPOSE(), + COMPOSE() + ) + ).toEqual([]); + }); + + it('rebuilds a service that had no build section at the old ref', () => { + expect(imageRebuilds([], null, COMPOSE())).toEqual(['caddy', 'sam-mx']); + }); }); describe('composeFilesFor', () => { From ba0403fba79cbd6876e5be33eb325a8d3ec221b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 02:22:14 +0000 Subject: [PATCH 04/65] feat(selfhost): GCP node trust bootstrap (pnpm selfhost:gcp-bootstrap) The integration branch's gcp-bootstrap.sh, trimmed to the node trust a plaintext box needs: the install-dedicated workload identity pool, the issuer-scoped OIDC provider, the node service account and its bindings, and the credential JSON to paste in Admin -> Credentials. Without the Cloud KMS key for sealed secrets (--kms, --kms-only, key versions) and without --teardown and its created-resources record, which only teardown read. Adds the selfhost:gcp-bootstrap and selfhost:live-test scripts. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/gcp-bootstrap.sh | 196 ++++++++++++++ package.json | 2 + scripts/selfhost/gcp-bootstrap.test.ts | 243 ++++++++++++++++++ scripts/selfhost/testdata/fake-gcloud-iam.mjs | 67 +++++ 4 files changed, 508 insertions(+) create mode 100755 deploy/selfhost/gcp-bootstrap.sh create mode 100644 scripts/selfhost/gcp-bootstrap.test.ts create mode 100644 scripts/selfhost/testdata/fake-gcloud-iam.mjs diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh new file mode 100755 index 0000000000..c93d56a962 --- /dev/null +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -0,0 +1,196 @@ +#!/usr/bin/env bash +# One-command Google Cloud trust for nodes of a self-hosted SAM install (pnpm selfhost:gcp-bootstrap). +# EXPERIMENTAL, like the rest of deploy/selfhost (README.md). +# +# Creates or reuses, in one GCP project: +# - a workload identity pool dedicated to this install, +# - an OIDC provider in it that trusts only this install's token issuer +# (https://api., the `iss` SAM signs with: getIssuer() in apps/api/src/services/jwt.ts), +# - a node service account with roles/compute.instanceAdmin.v1 and roles/compute.securityAdmin, +# - the binding that lets identities from that pool impersonate the service account, +# - the APIs nodes need, including Cloud Billing (read-only list prices for the machine catalog), +# then prints the platform cloud credential to add in Admin -> Credentials (Cloud Provider, GCP). +# It does not create the box VM, its firewall, the fleet bucket or DNS (README.md, Prerequisites). +# +# Every resource is described first and created only when missing. A provider that already +# trusts a different issuer is never retargeted; pick another --pool-id. +# +# Run it once the install answers (after the first `pnpm selfhost:deploy`): it checks the issuer +# the install advertises. +# +# Usage: +# pnpm selfhost:gcp-bootstrap -- --project --api-url https://api. [--dry-run] +# Options: +# --pool-id default: sam-<8 hex of sha256(issuer)>, unique per install +# --provider-id default: sam-api +# --service-account default: sam-nodes (account id, before @) +# --skip-issuer-check do not fetch /.well-known/openid-configuration first +# --dry-run print every gcloud command that would change something; change nothing +set -euo pipefail + +PROJECT="" +API_URL="" +POOL_ID="" +PROVIDER_ID="sam-api" +SA_ID="sam-nodes" +DRY_RUN=0 +CHECK_ISSUER=1 + +die() { echo "gcp-bootstrap: $*" >&2; exit 1; } + +while [ $# -gt 0 ]; do + case "$1" in + --) shift ;; + --project) PROJECT="${2:-}"; shift 2 ;; + --api-url) API_URL="${2:-}"; shift 2 ;; + --pool-id) POOL_ID="${2:-}"; shift 2 ;; + --provider-id) PROVIDER_ID="${2:-}"; shift 2 ;; + --service-account) SA_ID="${2:-}"; shift 2 ;; + --skip-issuer-check) CHECK_ISSUER=0; shift ;; + --dry-run) DRY_RUN=1; shift ;; + -h|--help) sed -n '2,28p' "$0"; exit 0 ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +# grep checks below are line by line: refuse any value with a newline before they run. +for value in "$PROJECT" "$API_URL" "$POOL_ID" "$PROVIDER_ID" "$SA_ID"; do + case "$value" in *$'\n'*|*$'\r'*) die "arguments must not contain line breaks" ;; esac +done +[ -n "$PROJECT" ] || die "--project is required" +[ -n "$API_URL" ] || die "--api-url is required (https://api.)" +ISSUER="${API_URL%/}" +case "$ISSUER" in + https://api.*) ;; + *) die "--api-url must be https://api. (the issuer SAM signs tokens with), got: $API_URL" ;; +esac +# The issuer is interpolated into a CEL condition: allow only URL-safe characters. +printf '%s' "$ISSUER" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]+)?$' \ + || die "--api-url must be a bare origin such as https://api.example.com, got: $API_URL" +printf '%s' "$PROJECT" | grep -Eq '^[a-z][a-z0-9-]{4,28}[a-z0-9]$' || die "invalid --project: $PROJECT" + +if command -v sha256sum >/dev/null 2>&1; then hash_cmd=(sha256sum); else hash_cmd=(shasum -a 256); fi +INSTALL_HASH="$(printf '%s' "$ISSUER" | "${hash_cmd[@]}" | cut -c1-8)" +[ -n "$POOL_ID" ] || POOL_ID="sam-${INSTALL_HASH}" +printf '%s' "$POOL_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --pool-id: $POOL_ID" +printf '%s' "$PROVIDER_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --provider-id: $PROVIDER_ID" +printf '%s' "$SA_ID" | grep -Eq '^[a-z][a-z0-9-]{5,29}$' || die "invalid --service-account: $SA_ID" +SA_EMAIL="${SA_ID}@${PROJECT}.iam.gserviceaccount.com" +CONDITION="assertion.iss == '${ISSUER}'" + +# Read-only calls run in every mode; changes go through `change`. +change() { + if [ "$DRY_RUN" -eq 1 ]; then + printf 'would run: gcloud'; printf ' %q' "$@"; printf '\n' + else + gcloud "$@" + fi +} +exists() { gcloud "$@" >/dev/null 2>&1; } +# IAM bindings on a just-created service account can fail until it propagates: retry briefly. +change_retry() { + local attempt + for attempt in 1 2 3 4 5; do + change "$@" && return 0 + [ "$attempt" -lt 5 ] && sleep "${GCP_BOOTSTRAP_RETRY_SECONDS:-5}" + done + return 1 +} + +command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH" + +# The OIDC provider trusts the issuer the install advertises: check it before trusting it. +if [ "$CHECK_ISSUER" -eq 1 ]; then + discovery="$(curl -fsS --max-time 10 "${ISSUER}/.well-known/openid-configuration" 2>/dev/null)" \ + || die "could not read ${ISSUER}/.well-known/openid-configuration: the node setup trusts this install's token issuer, so it runs once the install answers (after \`pnpm selfhost:deploy\`; README order). --skip-issuer-check skips the check if you are sure ${ISSUER} is right." + issuer_re="$(printf '%s' "$ISSUER" | sed 's/[.]/\\./g')" + printf '%s' "$discovery" | grep -Eq "\"issuer\"[[:space:]]*:[[:space:]]*\"${issuer_re}\"" \ + || die "the install at ${ISSUER} does not advertise issuer ${ISSUER}; check --api-url" +fi + +PROJECT_NUMBER="$(gcloud projects describe "$PROJECT" --format='value(projectNumber)' 2>/dev/null)" \ + || die "cannot read project ${PROJECT}; run 'gcloud auth login' as a project owner" +[ -n "$PROJECT_NUMBER" ] || die "project ${PROJECT} has no project number" + +echo "Project ${PROJECT} (${PROJECT_NUMBER}), issuer ${ISSUER}, pool ${POOL_ID}" + +# cloudbilling: read-only Compute Engine list prices for the node catalog (no IAM role needed; +# without it every GCP machine shows "Price unavailable"; box round R14). +change services enable compute.googleapis.com iam.googleapis.com iamcredentials.googleapis.com \ + sts.googleapis.com cloudbilling.googleapis.com --project="$PROJECT" + +# A deleted pool still describes (state DELETED) and keeps its id for 30 days: reusing it as +# "exists" would then try to create a provider in a deleted pool (R13 D5). +if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" \ + --location=global --format='value(state)' 2>/dev/null)"; then + [ "$pool_state" != "DELETED" ] \ + || die "workload identity pool ${POOL_ID} was deleted (Google keeps a deleted pool for 30 days, and its id cannot be reused until it is purged). Either undelete it: gcloud iam workload-identity-pools undelete ${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --pool-id and put the new values in the platform credential (Admin -> Credentials)." + echo "pool ${POOL_ID}: exists" +else + change iam workload-identity-pools create "$POOL_ID" --project="$PROJECT" --location=global \ + --display-name="SAM ${ISSUER#https://api.}" \ + --description="Dedicated to the SAM install whose token issuer is ${ISSUER}" +fi + +if provider_state="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(state)' 2>/dev/null)"; then + [ "$provider_state" != "DELETED" ] \ + || die "provider ${POOL_ID}/${PROVIDER_ID} was deleted (Google keeps it for 30 days). Undelete it: gcloud iam workload-identity-pools providers undelete ${PROVIDER_ID} --workload-identity-pool=${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --provider-id ." + current="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(oidc.issuerUri)')" + [ "$current" = "$ISSUER" ] \ + || die "provider ${POOL_ID}/${PROVIDER_ID} already trusts ${current}, not ${ISSUER}; refusing to retarget it. Use another --pool-id." + echo "provider ${PROVIDER_ID}: exists, issuer ${ISSUER}" +else + # Only this install's issuer is admitted (attributeCondition), and only tokens addressed to + # this provider: SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). Mapping + # matches the guided setup (gcp-setup.ts). + change iam workload-identity-pools providers create-oidc "$PROVIDER_ID" --project="$PROJECT" \ + --location=global --workload-identity-pool="$POOL_ID" --display-name="SAM API" \ + --issuer-uri="$ISSUER" \ + --allowed-audiences="https://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" \ + --attribute-mapping="google.subject=assertion.sub,attribute.sam_user=assertion.user_id,attribute.sam_project=assertion.project_id" \ + --attribute-condition="$CONDITION" +fi + +if exists iam service-accounts describe "$SA_EMAIL" --project="$PROJECT"; then + echo "service account ${SA_EMAIL}: exists" +else + change iam service-accounts create "$SA_ID" --project="$PROJECT" --display-name="SAM nodes" \ + --description="Creates and deletes SAM workspace VMs and their firewall rules for ${ISSUER}" +fi + +for role in roles/compute.instanceAdmin.v1 roles/compute.securityAdmin; do + change_retry projects add-iam-policy-binding "$PROJECT" --member="serviceAccount:${SA_EMAIL}" \ + --role="$role" --condition=None --quiet --format=none +done + +# Scope: the whole pool. That is this one install only, because the pool is created for it and +# its only provider admits tokens whose issuer is this install's API origin (the condition +# above, checked again on every run). Any provider added to this pool later would inherit the +# service account, so do not add providers to it. +change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ + --role=roles/iam.workloadIdentityUser \ + --member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" \ + --condition=None --quiet --format=none + +[ "$DRY_RUN" -eq 1 ] && echo "Dry run: nothing was changed." +# The shape parseGcpCredential (apps/api/src/services/provider-credential-codecs.ts) reads. +cat < Credentials -> Add Credential, +Type "Cloud Provider", Provider "GCP", any label. Paste this as the API Token, with ZONE +replaced by the Compute Engine zone nodes use by default (for example europe-west1-b): + +{"version":1,"provider":"gcp","authType":"workload-identity","gcpProjectId":"${PROJECT}","gcpProjectNumber":"${PROJECT_NUMBER}","serviceAccountEmail":"${SA_EMAIL}","wifPoolId":"${POOL_ID}","wifProviderId":"${PROVIDER_ID}","defaultZone":"ZONE"} + +The values in it: + Project ID: ${PROJECT} + Project number: ${PROJECT_NUMBER} + Pool ID: ${POOL_ID} + Provider ID: ${PROVIDER_ID} + Service account email: ${SA_EMAIL} +Then add machines to the installation pool in Admin -> Infrastructure. +EOF diff --git a/package.json b/package.json index 97ad0ee0f9..a89147232a 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,9 @@ "setup:local": "tsx scripts/deploy/setup-local-dev.ts", "selfhost:deploy": "tsx scripts/selfhost/deploy.ts", "selfhost:create-account": "tsx scripts/selfhost/create-account.ts", + "selfhost:gcp-bootstrap": "bash deploy/selfhost/gcp-bootstrap.sh", "selfhost:test": "vitest run --config scripts/selfhost/vitest.config.ts", + "selfhost:live-test": "vitest run --config scripts/selfhost/live/vitest.config.ts", "selfhost:upgrade": "tsx scripts/selfhost/upgrade.ts", "quality:preflight": "tsx scripts/quality/check-preflight-evidence.ts", "test:acp-c2-remote-service": "node tests/fixtures/acp-c2-remote-service.test.mjs", diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts new file mode 100644 index 0000000000..6659f26b6c --- /dev/null +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -0,0 +1,243 @@ +/** + * deploy/selfhost/gcp-bootstrap.sh against a fake `gcloud` and `curl` on PATH. The fake keeps + * Google Cloud state as files, so a second run sees what the first created. + */ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { parseGcpCredential } from '../../apps/api/src/services/provider-credential-codecs'; + +// Every case runs bash and a node-based fake gcloud many times. +vi.setConfig({ testTimeout: 60_000 }); + +const SCRIPT = resolve(import.meta.dirname, '../../deploy/selfhost/gcp-bootstrap.sh'); +const ISSUER = 'https://api.vmtest.example.org'; + +// The fake keeps Google Cloud state in $STATE/gcp.json and appends every call to $STATE/calls. +const FAKE_GCLOUD = `#!/usr/bin/env bash +exec node ${JSON.stringify(resolve(import.meta.dirname, 'testdata/fake-gcloud-iam.mjs'))} "$@" +`; +const FAKE_CURL = `#!/usr/bin/env bash +printf '{"issuer":"%s","jwks_uri":"%s/.well-known/jwks.json"}' "$FAKE_ISSUER" "$FAKE_ISSUER" +`; + +let state: string; +let bin: string; + +beforeEach(() => { + state = mkdtempSync(join(tmpdir(), 'gcp-bootstrap-state-')); + bin = mkdtempSync(join(tmpdir(), 'gcp-bootstrap-bin-')); + writeFileSync(join(bin, 'gcloud'), FAKE_GCLOUD); + writeFileSync(join(bin, 'curl'), FAKE_CURL); + chmodSync(join(bin, 'gcloud'), 0o755); + chmodSync(join(bin, 'curl'), 0o755); +}); + +function run(args: string[], advertisedIssuer = ISSUER, env: NodeJS.ProcessEnv = {}) { + const result = spawnSync('bash', [SCRIPT, ...args], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + STATE: state, + FAKE_ISSUER: advertisedIssuer, + ...env, + }, + }); + return { ...result, calls: calls() }; +} + +interface FakeGcp { + pools: Record; + providers: Record; + accounts: Record; + bindings: string[]; +} + +function gcp(): FakeGcp { + return JSON.parse(readFileSync(join(state, 'gcp.json'), 'utf8')) as FakeGcp; +} + +function setGcp(update: (db: FakeGcp) => void): void { + const db = gcp(); + update(db); + writeFileSync(join(state, 'gcp.json'), JSON.stringify(db)); +} + +function calls(): string[] { + try { + return readFileSync(join(state, 'calls'), 'utf8').trim().split('\n'); + } catch { + return []; + } +} + +const MUTATING = + /^(services enable|iam workload-identity-pools( providers)? create|iam service-accounts create|projects add-iam-policy-binding|iam service-accounts add-iam-policy-binding)/; + +describe('pnpm selfhost:gcp-bootstrap', () => { + it('creates the pool, issuer-scoped provider, service account and bindings, and prints the five form values', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', `${ISSUER}/`]); + expect(result.status, result.stderr).toBe(0); + + const provider = result.calls.find((c) => c.includes('providers create-oidc'))!; + expect(provider).toContain(`--issuer-uri=${ISSUER}`); + expect(provider).toContain(`--attribute-condition=assertion.iss == '${ISSUER}'`); + expect(provider).toContain( + '--allowed-audiences=https://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/' + ); + const roles = result.calls.filter((c) => c.startsWith('projects add-iam-policy-binding')); + expect(roles.map((c) => /--role=(\S+)/.exec(c)?.[1])).toEqual([ + 'roles/compute.instanceAdmin.v1', + 'roles/compute.securityAdmin', + ]); + const impersonation = result.calls.find((c) => + c.startsWith('iam service-accounts add-iam-policy-binding') + )!; + expect(impersonation).toContain('--role=roles/iam.workloadIdentityUser'); + expect(impersonation).toMatch( + /principalSet:\/\/iam\.googleapis\.com\/projects\/123456789012\/locations\/global\/workloadIdentityPools\/sam-[0-9a-f]{8}\/\*/ + ); + + // Cloud Billing: the node catalog's GCP list prices (box round R14). + const services = result.calls.find((c) => c.startsWith('services enable'))!; + expect(services.split(' ')).toEqual( + expect.arrayContaining(['compute.googleapis.com', 'cloudbilling.googleapis.com']) + ); + + expect(result.stdout).toMatch(/Project ID:\s+sam-vm-test/); + expect(result.stdout).toMatch(/Project number:\s+123456789012/); + expect(result.stdout).toMatch(/Pool ID:\s+sam-[0-9a-f]{8}/); + expect(result.stdout).toMatch(/Provider ID:\s+sam-api/); + expect(result.stdout).toMatch( + /Service account email:\s+sam-nodes@sam-vm-test\.iam\.gserviceaccount\.com/ + ); + }); + + it('prints where the credential goes in SAM and JSON the credential parser accepts (box round R12)', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('Admin -> Credentials -> Add Credential'); + expect(result.stdout).not.toContain('Integrations'); + const json = /^\{"version":1,"provider":"gcp".*\}$/m.exec(result.stdout)?.[0]; + expect(json).toBeDefined(); + // The operator replaces ZONE; the result is what the app stores and parses for every node. + const parsed = parseGcpCredential(json!.replace('"ZONE"', '"europe-west1-b"')); + expect(parsed).toMatchObject({ + authType: 'workload-identity', + gcpProjectId: 'sam-vm-test', + gcpProjectNumber: '123456789012', + serviceAccountEmail: 'sam-nodes@sam-vm-test.iam.gserviceaccount.com', + wifProviderId: 'sam-api', + defaultZone: 'europe-west1-b', + }); + expect(parsed.authType === 'workload-identity' && parsed.wifPoolId).toMatch( + /^sam-[0-9a-f]{8}$/ + ); + }); + + it('is idempotent: a second run creates nothing new and prints the same values', () => { + const first = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(first.status, first.stderr).toBe(0); + const before = calls().length; + const second = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(second.status, second.stderr).toBe(0); + const secondCalls = second.calls.slice(before); + expect(secondCalls.filter((c) => / create/.test(c))).toEqual([]); + expect(second.stdout.split('Add the installation')[1]).toBe( + first.stdout.split('Add the installation')[1] + ); + }); + + it('dry run changes nothing and shows what it would run', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--dry-run']); + expect(result.status, result.stderr).toBe(0); + expect(result.calls.filter((c) => MUTATING.test(c))).toEqual([]); + expect(result.stdout).toContain('would run: gcloud iam workload-identity-pools create'); + expect(result.stdout).toContain('Dry run: nothing was changed.'); + }); + + it('refuses to retarget a provider that already trusts another install', () => { + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-shared']); + const other = 'https://api.other.example.org'; + const result = run( + ['--project', 'sam-vm-test', '--api-url', other, '--pool-id', 'sam-shared'], + other + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain(`already trusts ${ISSUER}`); + expect(gcp().providers['sam-api'].issuer).toBe(ISSUER); + }); + + it('refuses an install whose discovery document names a different issuer', () => { + const result = run( + ['--project', 'sam-vm-test', '--api-url', ISSUER], + 'https://api.elsewhere.org' + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('does not advertise issuer'); + expect(result.calls.filter((c) => MUTATING.test(c))).toEqual([]); + }); + + it('a soft-deleted pool of the same id: stops with the undelete command, creates nothing (R13 D5)', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + const pool = Object.keys(gcp().pools)[0] ?? ''; + // Someone deleted it; Google keeps the id, and describe still answers, for 30 days. + setGcp((db) => { + const entry = db.pools[pool]; + if (entry) entry.state = 'DELETED'; + delete db.providers['sam-api']; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain(`workload identity pool ${pool} was deleted`); + expect(result.stderr).toContain( + `gcloud iam workload-identity-pools undelete ${pool} --project=sam-vm-test --location=global` + ); + expect(result.stderr).toContain('--pool-id'); + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services')) + ).toEqual([]); + expect(gcp().providers).toEqual({}); + }); + + it('a soft-deleted provider: stops with its undelete command', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + const entry = db.providers['sam-api']; + if (entry) entry.state = 'DELETED'; + }); + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'gcloud iam workload-identity-pools providers undelete sam-api' + ); + }); + + it('with the install not up yet: says to run it after the deploy', () => { + writeFileSync(join(bin, 'curl'), '#!/usr/bin/env bash\nexit 7\n'); + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('after `pnpm selfhost:deploy`'); + expect(result.stderr).toContain('--skip-issuer-check'); + expect(result.calls).toEqual([]); + }); + + it('creates only the node trust: no KMS key, VM, bucket or firewall', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + expect(result.calls.filter((c) => /^(kms|compute|storage)\b/.test(c))).toEqual([]); + expect(result.stdout).not.toContain('SAM_GCP_KMS_KEY'); + }); + + it('refuses an API URL that is not https://api.', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', "https://app.x.org' || true"]); + expect(result.status).not.toBe(0); + expect(result.calls).toEqual([]); + }); +}); diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs new file mode 100644 index 0000000000..b721fc0410 --- /dev/null +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -0,0 +1,67 @@ +#!/usr/bin/env node +// Fake `gcloud` for gcp-bootstrap.test.ts: the IAM and workload identity commands +// deploy/selfhost/gcp-bootstrap.sh runs. State is one JSON file ($STATE/gcp.json), so a later run +// sees what an earlier one did; every call is appended to $STATE/calls. +import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const STATE = process.env.STATE; +const args = process.argv.slice(2); +appendFileSync(join(STATE, 'calls'), `${args.join(' ')}\n`); +const file = join(STATE, 'gcp.json'); +const db = existsSync(file) + ? JSON.parse(readFileSync(file, 'utf8')) + : { pools: {}, providers: {}, accounts: {}, bindings: [] }; +const save = () => writeFileSync(file, JSON.stringify(db, null, 2)); +const flag = (name) => { + const hit = args.find((a) => a.startsWith(`--${name}=`)); + if (hit) return hit.slice(name.length + 3); + const i = args.indexOf(`--${name}`); + return i >= 0 ? args[i + 1] : undefined; +}; +const words = args.filter((a, i) => !a.startsWith('--') && (args[i - 1] ?? '') !== '--project'); +const cmd = words.slice(0, 4).join(' '); +const fail = (message) => { + process.stderr.write(`ERROR: ${message}\n`); + process.exit(1); +}; +const out = (text) => process.stdout.write(`${text}\n`); +const format = flag('format') ?? ''; + +if (cmd.startsWith('projects describe')) out('123456789012'); +else if (cmd.startsWith('services enable')) save(); +else if (cmd.startsWith('iam workload-identity-pools providers')) { + const [, , , op, id] = words; + if (op === 'describe') { + if (!db.providers[id]) fail('not found'); + if (format.includes('issuerUri')) out(db.providers[id].issuer); + if (format.includes('state')) out(db.providers[id].state ?? 'ACTIVE'); + } else if (op === 'create-oidc') { + db.providers[id] = { issuer: flag('issuer-uri') }; + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('iam workload-identity-pools')) { + const [, , op, id] = words; + if (op === 'describe') { + // A deleted pool still describes, with state DELETED, for 30 days (as Google keeps it). + if (!db.pools[id]) fail('not found'); + if (format.includes('state')) out(db.pools[id].state ?? 'ACTIVE'); + } else if (op === 'create') { + db.pools[id] = { description: flag('description') }; + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('iam service-accounts add-iam-policy-binding')) save(); +else if (cmd.startsWith('iam service-accounts')) { + const [, , op, id] = words; + const email = id.includes('@') ? id : `${id}@${flag('project')}.iam.gserviceaccount.com`; + if (op === 'describe') { + if (!db.accounts[email]) fail('not found'); + } else if (op === 'create') { + db.accounts[email] = { description: flag('description') }; + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('projects add-iam-policy-binding')) { + const entry = `project:${words[2]} ${flag('role')} ${flag('member')}`; + if (!db.bindings.includes(entry)) db.bindings.push(entry); + save(); +} else fail(`fake gcloud: unexpected: ${args.join(' ')}`); From a20f5938f93865d8e86ef784270e6a28f9e2d70a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 02:22:23 +0000 Subject: [PATCH 05/65] docs(selfhost): short operator README for the experimental box Replaces the integration branch's ~1,400-line README with a short operator note, marked as an experimental test-box setup and not a supported deployment: prerequisites, the fresh-install sequence, upgrade (no automatic backup), image builds, R2_S3_REGION for s3:// stores, the lease port range and gateway secret, the frp rate limit, email, and what is not included yet. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 167 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 deploy/selfhost/README.md diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md new file mode 100644 index 0000000000..4424b10468 --- /dev/null +++ b/deploy/selfhost/README.md @@ -0,0 +1,167 @@ +# Self-hosted SAM on one box (celld) + +> **Experimental, not a supported deployment option.** This directory exists for the SAM team's +> own test box. It changes without notice, has no upgrade guarantees, and lacks security layers a +> real deployment needs (see [Not included yet](#not-included-yet)). The supported way to run SAM +> is the Cloudflare deployment described on the docs site. + +One Linux VM runs the whole control plane with Docker Compose (`docker-compose.yml`): + +| Service | What it does | +| ---------------- | --------------------------------------------------------------------------- | +| `celld` | Runs the API Worker and serves the web UI, on `127.0.0.1:8080` | +| `caddy` | TLS on 80/443 for `*.SAM_DOMAIN`, proxies to celld; carries node WebSockets | +| `frps` | Reverse tunnels from workspace nodes (profile `tunnel`), loopback only | +| `objectstore` | Bundled MinIO for trials (profile `local-store`) | +| `mail-collector` | Catches sign-in email for test installs (profile `mail-collector`) | +| `sam-mx` | Inbound agent email on port 25 (profile `mail-in`) | + +Workspace nodes are cloud VMs that dial back to `wss://api.SAM_DOMAIN/~!frp`; they need no public +DNS of their own. The fleet bucket (`CELLD_BUCKET`) is the durable copy of everything celld stores. + +## Prerequisites + +- A Linux VM (GCE is what the team tests) with Docker Engine and the Compose plugin, Node.js 22, + pnpm 9 and git, and a checkout of this repository. +- A domain with a wildcard record `*.SAM_DOMAIN` pointing at the VM. SAM serves `api.`, `app.`, + `ws-.` and `ws---.` under it; the apex is unused. +- Inbound TCP 80 and 443 to the VM (and 25 for inbound agent email). +- A fleet bucket: `gs://` (the VM's service account needs `roles/storage.objectAdmin` on it), + any `s3://` store, or the bundled store for a trial (`local-store` profile). +- TLS: `SAM_TLS_MODE=dns-googleclouddns` gets a Let's Encrypt wildcard through Cloud DNS (the VM's + service account needs `roles/dns.admin` on the zone's project, `GCP_PROJECT` names it). + `internal` uses Caddy's own CA, for local proofs only. +- A way to send sign-in codes: an SMTP relay (`SMTP_*`), or the mail collector on a test box. +- For GCP workspace nodes: `gcloud`, authenticated as an owner of the nodes' project. + +Nothing here creates the VM, its firewall, DNS records or the bucket. + +## Fresh install + +From the repository root on the VM: + +1. `pnpm install --frozen-lockfile` +2. `cp deploy/selfhost/.env.example deploy/selfhost/.env && chmod 600 deploy/selfhost/.env`, then + edit it. The comments in `.env.example` explain every setting. The bucket credential in it can + read every Worker secret, so the file must stay private (the scripts refuse a readable one). +3. Optional: secrets for the Worker go in `deploy/selfhost/.state/secrets.env` (mode 0600), for + example `SMTP_PASSWORD=...` and `BOOTSTRAP_OWNER_EMAIL=you@example.com`. With an owner email set, + only that address can claim the new install by signing in with an emailed code. +4. `pnpm selfhost:deploy --init`: generates the platform keys (`.state/platform-keys.json`; back + it up), `.state/gateway.env` (the reverse-tunnel gateway secret and lease port range) and the + mail-collector files. Run it again after changing the port range or turning a profile on. +5. `docker compose -f deploy/selfhost/docker-compose.yml --env-file deploy/selfhost/.env build`: + builds the two local images (`caddy`, and `sam-mx` when `mail-in` is on). See + [Image builds](#image-builds). +6. `docker compose -f deploy/selfhost/docker-compose.yml --env-file deploy/selfhost/.env up -d` + (or run `docker compose build` / `up -d` from inside `deploy/selfhost/`, which reads `.env`). +7. `pnpm selfhost:deploy`: builds the web UI, the API Worker's dependencies and the vm-agent + (in a pinned Go image), publishes the vm-agent to the bucket, applies D1 migrations and runs + `celld deploy`, then waits until the new version answers. +8. Sign in at `https://app.SAM_DOMAIN`. To add someone, or a first administrator without + `BOOTSTRAP_OWNER_EMAIL`: `pnpm selfhost:create-account --email someone@example.com [--superadmin]`. +9. GCP nodes: `pnpm selfhost:gcp-bootstrap -- --project --api-url https://api.SAM_DOMAIN`. + It runs after step 7 because it checks the token issuer the running install advertises. It + creates a workload identity pool and provider trusting only this install, and a node service + account, then prints the credential JSON to paste in **Admin -> Credentials** (Cloud Provider, + GCP). Add machines to the installation pool in **Admin -> Infrastructure**. + +`pnpm selfhost:deploy --dry-run` prints the Worker configuration it would deploy, secrets redacted. + +## Upgrade + +```sh +pnpm selfhost:upgrade --to +``` + +It refuses a checkout with uncommitted changes, checks the ref out, runs `deploy --init`, rebuilds +only the images whose build inputs changed, restarts the stack only when compose inputs changed, +deploys, checks health and prints how to roll back. + +**It takes no backup.** Copy the fleet bucket and `deploy/selfhost/.state` yourself first. An +upgrade that carries a D1 migration cannot be rolled back by redeploying the old ref; only your +own pre-upgrade copy restores it. + +## Image builds + +`caddy` and `sam-mx` are built on the box; every other image is pulled by digest. Builds are +explicit: `docker compose build [service]` (or `up` when the image does not exist yet), never on +an ordinary `up`, and `selfhost:upgrade` rebuilds a service only when its Dockerfile, its build +context or its build section in `docker-compose.yml` changed. Both Dockerfiles pin their base +images by digest. Caddy's modules (the DNS provider, `CADDY_DNS_MODULE`, and caddy-ratelimit) are +pinned by version and verified against the Go checksum database, and the build fails unless the +binary carries exactly those versions; `sam-mx` modules are pinned by `go.sum`. + +A build still downloads from the network (Docker Hub, the Go module proxy, Alpine packages). The +content is pinned, so a changed upstream fails the build rather than changing the image. After +changing `CADDY_DNS_MODULE`, run `docker compose build caddy`. + +## Settings worth knowing + +**Object store and presigned uploads.** Uploads (attachments, snapshots) go from the browser +straight to the fleet bucket when `R2_S3_ENDPOINT` is set and `.state/secrets.env` holds a +credential scoped to the R2 prefix (`R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`; never the fleet +credential, which the deploy refuses). **For an `s3://` bucket `R2_S3_REGION` is required** (the +store's SigV4 signing region, for MinIO usually `us-east-1`): the deploy refuses `R2_S3_ENDPOINT` +without it. A `gs://` bucket defaults to `auto`. The bundled store is a community MinIO build that +celld does not qualify for production. + +**Reverse-tunnel ports and the gateway secret.** frps binds one loopback port per node from +`REVERSE_TUNNEL_PORT_RANGE_START`..`_END` (default 20000-29999). The deploy writes the resolved +range to both the Worker and `.state/gateway.env`, and refuses a range that contains a box port +(`CELLD_PORT`, `CELLD_INTERNAL_PORT`, `FRPS_BIND_PORT`, `OBJECTSTORE_*`, `HTTP(S)_PORT`, +`MAIL_COLLECTOR_*`): a node leased one of those would receive traffic meant for it. Docker Compose +takes a port from the shell before `.env`, so the deploy checks shell overrides too, and Caddy's +`start.sh` refuses to start when a port it is given lies in the range. Set ports in `.env`, not +the shell. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and +Caddy present to the Worker's loopback-only gateway routes (`/api/self-host/gateway/*`, which +Caddy answers with 404 from outside). When `gateway.env` changes, the deploy stops until the +stack is restarted (`docker compose up -d`), so the Worker never assumes settings frps is not +running. + +**frp login rate limit.** Caddy accepts `SAM_FRP_LOGIN_RATE_LIMIT_EVENTS` (default 60) new frp +connections per client address per `SAM_FRP_LOGIN_RATE_LIMIT_WINDOW` (default `1m`) and answers +429 above it. A node keeps one connection; raise the limit if many nodes share an address. + +**Email sign-in.** Either an SMTP relay (`SMTP_HOST`, `SMTP_TLS`, `SMTP_PORT`, `SMTP_USERNAME`, +`SMTP_FROM` in `.env`, `SMTP_PASSWORD` in `.state/secrets.env`), or, on a test box only, the +`mail-collector` profile: Mailpit catches every message and shows it at +`https://mail.SAM_DOMAIN` behind basic auth (user `collector`, password generated by +`deploy --init` into `.state/mail-collector-ui-password`). Anyone who can read the collector can +sign in as any account. The deploy refuses both at once, and the profile without `--init`. + +**Inbound agent email.** Add `mail-in` to `COMPOSE_PROFILES`, an MX record +`agents.SAM_DOMAIN -> mx.SAM_DOMAIN` and inbound TCP 25. `sam-mx` accepts mail for +`agent+@agents.SAM_DOMAIN` only, requires aligned SPF or DKIM, and hands each message to the +Worker's loopback gateway route. Replies go out through the SMTP relay (or the collector), which +the deploy requires when the profile is on. + +**Cold starts.** celld retires an idle Worker isolate on its 30 s pool tick, and the next request +waits 1.5-2.4 s while a new one loads. Caddy pings `/health` every `SAM_KEEP_WARM_INTERVAL` +(default 5s) so the ping pays that cost instead of a user. `SAM_KEEP_WARM=off` turns it off. + +**Logs.** `docker compose logs caddy` is the access log: one JSON line per request, with no +headers, query strings or path credentials. `docker compose logs celld` is the Worker's output. + +## Not included yet + +This version runs in plaintext mode: celld keeps every Worker secret in plaintext in the fleet +bucket's deploy manifests, so the bucket credential is the install's master key. Also missing: + +- **Egress fence**: nothing stops Worker code from reaching loopback services, the private + network or the cloud metadata server on the box. +- **Sealed secrets**: no key agent or KMS-backed encryption of the Worker's secrets. +- **Guided credential login** (sandboxed agent sign-in on the box). +- **Hosted git.** +- **Backup, restore and teardown** commands. Back up the fleet bucket and `.state/` yourself. + +Do not put data on this box that you could not afford to lose or leak. + +## Tests + +- `pnpm selfhost:test`: deploy, upgrade, account and configuration logic, compose wiring, pinned + versions, `caddy/start.sh` (no Docker needed). +- `pnpm selfhost:live-test`: the box's real Caddy image (built from `caddy/Dockerfile`), frp and + celld in Docker with host networking: gateway 404s and path tricks, the frp rate limit, header + stripping, logging, keep-warm, the mail collector, frpc certificate checks, celld's guarded + fetch and shared in-flight reads. CI runs it only when self-host paths change. From 6c92cffc3312c964aed5a3652a8938bfb9f3012c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 02:29:37 +0000 Subject: [PATCH 06/65] test(selfhost): Docker live suite for the box runtime, CI job on self-host paths (D9) Brings the live suite from the integration branch: caddy-fragments, access-log-keep-warm, mail-collector, frpc-tls, celld-redirect and shared-flight-cancel, with the harness and celld lab. Caddy runs from the image deploy/selfhost/caddy/Dockerfile builds, through start.sh, as compose runs it. New cases: encoded letters at any depth, backslash separators, dot segments and absolute-form targets never reach the gateway route (L1); public paths naming self-host still reach celld (L6); frp connections over the per-address limit get 429 (L7); start.sh refuses a box port inside the lease range and bad rate-limit values (L5). shared-flight-cancel loses its key agent case (sealed secrets are held) and talks to a plain slow upstream instead. CI: a Self-host Live (Docker) job runs `pnpm selfhost:live-test` only when deploy/selfhost, scripts/selfhost or apps/api/src/selfhost change, not for packages/cloud-init and not nightly. Validate Deploy Scripts builds the API's workspace dependencies first (the GCP bootstrap test parses with the real credential codec). Dependabot watches the Caddy Dockerfile's digests. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 5 + .github/workflows/ci.yml | 46 ++ scripts/quality/ci-suite-selection.test.ts | 24 +- scripts/quality/dependency-governance.test.ts | 2 + .../live/access-log-keep-warm.live.test.ts | 313 +++++++++++ .../live/caddy-fragments.live.test.ts | 492 ++++++++++++++++++ scripts/selfhost/live/celld-lab.ts | 216 ++++++++ .../selfhost/live/celld-redirect.live.test.ts | 161 ++++++ scripts/selfhost/live/frpc-tls.live.test.ts | 245 +++++++++ scripts/selfhost/live/harness.ts | 204 ++++++++ .../selfhost/live/mail-collector.live.test.ts | 349 +++++++++++++ .../live/shared-flight-cancel.live.test.ts | 399 ++++++++++++++ scripts/selfhost/live/vitest.config.ts | 17 + 13 files changed, 2471 insertions(+), 2 deletions(-) create mode 100644 scripts/selfhost/live/access-log-keep-warm.live.test.ts create mode 100644 scripts/selfhost/live/caddy-fragments.live.test.ts create mode 100644 scripts/selfhost/live/celld-lab.ts create mode 100644 scripts/selfhost/live/celld-redirect.live.test.ts create mode 100644 scripts/selfhost/live/frpc-tls.live.test.ts create mode 100644 scripts/selfhost/live/harness.ts create mode 100644 scripts/selfhost/live/mail-collector.live.test.ts create mode 100644 scripts/selfhost/live/shared-flight-cancel.live.test.ts create mode 100644 scripts/selfhost/live/vitest.config.ts diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d0d55d6777..a426a15579 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -56,3 +56,8 @@ updates: directory: '/deploy/selfhost/sam-mx' schedule: interval: weekly + # Self-hosted Caddy build (caddy builder + runtime, both pinned by digest). + - package-ecosystem: 'docker' + directory: '/deploy/selfhost/caddy' + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a5dd923f9..cdf93e7859 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,8 @@ jobs: browser-install: ${{ steps.filter.outputs.browser-install }} go-modules: ${{ steps.filter.outputs.go-modules }} selfhost-email: ${{ github.event_name == 'push' && 'true' || steps.filter.outputs.selfhost-email }} + # Path-filtered on main pushes too: the live suite runs only for self-host changes (D9). + selfhost-live: ${{ steps.filter.outputs.selfhost-live }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 @@ -337,6 +339,12 @@ jobs: - 'apps/api/tests/workers/smtp-client-workerd.test.ts' - 'apps/api/tests/workers/support/smtp-native-entry.ts' - '.github/workflows/selfhost-email-tests.yml' + # Self-host box runtime: the Docker live suite (landing plan D9). Self-host paths + # only: not packages/cloud-init (whose frpc.toml one live test renders) and not nightly. + selfhost-live: + - 'deploy/selfhost/**' + - 'scripts/selfhost/**' + - 'apps/api/src/selfhost/**' # One job for the PR-body and PR-content checks. They used to be three jobs that each # spent a runner slot on checkout and install for a few seconds of work. Each check @@ -872,6 +880,12 @@ jobs: - name: Enforce source file size limits run: pnpm quality:file-sizes + # The self-host scripts and their tests load API modules (the GCP credential parser, the + # shared-flight helper) that import workspace packages through their built dist/, as + # `pnpm selfhost:deploy` does after building them (deploy.ts buildApiDependencies). + - name: Build the API Worker's workspace dependencies + run: pnpm exec turbo run build --filter=@simple-agent-manager/api^... + - name: Type check deployment scripts run: | pnpm exec tsc --project scripts/deploy/tsconfig.json --noEmit @@ -1128,6 +1142,7 @@ jobs: - pulumi-infra - vm-agent-test - selfhost-email + - selfhost-live - cli-test - vm-agent-integration - devcontainer @@ -1222,6 +1237,37 @@ jobs: if: needs.changes.outputs.selfhost-email == 'true' && !github.event.pull_request.draft uses: ./.github/workflows/selfhost-email-tests.yml + # The box runtime on real software (scripts/selfhost/live): Caddy built from + # deploy/selfhost/caddy/Dockerfile running the box's Caddyfile and start.sh (gateway 404s and + # path tricks, frp rate limit, X-SAM-* stripping, access log, keep-warm, mail collector), the + # pinned frpc/frps with the frpc.toml cloud-init renders, and the pinned celld (guarded fetch, + # shared in-flight reads). Needs Docker with host networking; no sudo or nftables. + selfhost-live: + name: Self-host Live (Docker) + needs: [changes] + if: (github.event_name == 'pull_request' || github.repository == 'raphaeltm/simple-agent-manager') && !github.event.pull_request.draft && needs.changes.outputs.selfhost-live == 'true' + timeout-minutes: 30 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # celld bundles API modules (worker-core's shared-flight) through their built dist/. + - name: Build the API Worker's workspace dependencies + run: pnpm exec turbo run build --filter=@simple-agent-manager/api^... + + - name: Run self-host live tests + run: pnpm selfhost:live-test + cli-test: name: CLI Test needs: [changes] diff --git a/scripts/quality/ci-suite-selection.test.ts b/scripts/quality/ci-suite-selection.test.ts index aa8213807f..67da4ec98b 100644 --- a/scripts/quality/ci-suite-selection.test.ts +++ b/scripts/quality/ci-suite-selection.test.ts @@ -672,10 +672,30 @@ describe('runner budget (jobs a ready PR starts)', () => { }); // 32: the Self-host Email job (landing plan F12) runs only on self-host email paths. - it('a PR that matches every filter starts at most 32 jobs (27 before: four more Workers shards, then Self-host Email)', () => { + // 33: the Self-host Live job (landing plan D9) runs only on self-host paths. + it('a PR that matches every filter starts at most 33 jobs (27 before: four more Workers shards, Self-host Email, Self-host Live)', () => { expect( jobCount(simulate({ eventName: 'pull_request', filters: allFilters() })) - ).toBeLessThanOrEqual(32); + ).toBeLessThanOrEqual(33); + }); + + it('the Self-host Live job starts only for self-host paths (D9)', () => { + const live = (paths: string[]) => + simulate({ eventName: 'pull_request', filters: filtersFor(paths) }).get('selfhost-live'); + for (const path of [ + 'deploy/selfhost/caddy/Caddyfile', + 'scripts/selfhost/deploy.ts', + 'apps/api/src/selfhost/build.ts', + ]) { + expect(live([path]), path).toBe('success'); + } + for (const path of [ + 'packages/cloud-init/src/reverse-tunnel.ts', + 'apps/api/src/index.ts', + 'packages/worker-core/src/shared-flight.ts', + ]) { + expect(live([path]), path).not.toBe('success'); + } }); it('a draft PR starts 6 jobs', () => { diff --git a/scripts/quality/dependency-governance.test.ts b/scripts/quality/dependency-governance.test.ts index d3922cfaee..a2bcaf5603 100644 --- a/scripts/quality/dependency-governance.test.ts +++ b/scripts/quality/dependency-governance.test.ts @@ -133,6 +133,7 @@ describe('dependency governance', () => { 'apps/api/Dockerfile.compose-builder', 'apps/api/Dockerfile.sandbox', 'apps/api/Dockerfile.vm-agent-container', + 'deploy/selfhost/caddy/Dockerfile', 'deploy/selfhost/sam-mx/Dockerfile', 'scripts/e2e/workspace-mock/Dockerfile', ]); @@ -140,6 +141,7 @@ describe('dependency governance', () => { expect(refs.every((ref) => /@sha256:[a-f0-9]{64}$/.test(ref))).toBe(true); expect([...extractDependabotDirectories('docker')].sort()).toEqual([ '/apps/api', + '/deploy/selfhost/caddy', '/deploy/selfhost/sam-mx', '/scripts/e2e/workspace-mock', ]); diff --git a/scripts/selfhost/live/access-log-keep-warm.live.test.ts b/scripts/selfhost/live/access-log-keep-warm.live.test.ts new file mode 100644 index 0000000000..3377aa1ef2 --- /dev/null +++ b/scripts/selfhost/live/access-log-keep-warm.live.test.ts @@ -0,0 +1,313 @@ +/** + * Live: Caddy's access log, its redaction, and the keep-warm health check + * (deploy/selfhost/caddy/Caddyfile, log-redaction.caddy, keep-warm/), on the box's Caddy image + * (built from caddy/Dockerfile) started through start.sh exactly as docker-compose.yml starts it, in front of a stub celld that + * records what reaches it. + * + * Checked: one access-log line per request on stdout, with host, method, path, status and + * duration; no header value (cookie, Authorization, X-SAM-*), no query string and no gateway + * secret in the access log or in Caddy's own log, including a proxy-error entry; keep-warm sends + * GET /health on the API host, a failing /health leaves real traffic untouched, SAM_KEEP_WARM=off + * sends nothing, and start.sh refuses invalid keep-warm and frp rate-limit settings and a box + * port inside the reverse-tunnel lease range. + */ +import { execFileSync, spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { createServer, type Server } from 'node:http'; +import { request as httpsRequest } from 'node:https'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { + caddyBoxEnv, + caddyImage, + freePort, + LIVE_TUNNEL_RANGE, + REPO_ROOT, + sleep, + waitFor, +} from './harness'; + +const DOMAIN = 'sam.test'; +const CADDY_DIR = `${REPO_ROOT}/deploy/selfhost/caddy`; +const GATEWAY_SECRET = `gw${randomBytes(24).toString('hex')}`; +const SECRETS = { + cookie: `ck${randomBytes(12).toString('hex')}`, + bearer: `br${randomBytes(12).toString('hex')}`, + samHeader: `xs${randomBytes(12).toString('hex')}`, + query: `qy${randomBytes(12).toString('hex')}`, + responseCookie: `rc${randomBytes(12).toString('hex')}`, +}; + +interface Hit { + host: string; + url: string; +} + +interface Stack { + container: string; + https: number; + stdout: () => string; + stderr: () => string; +} + +let celld: Server; +let celldPort = 0; +let healthStatus = 200; +const hits: Hit[] = []; +const stacks: Stack[] = []; + +function caddyArgs(name: string, env: Record): string[] { + return [ + 'run', + '-d', + '--name', + name, + '--network', + 'host', + '-v', + `${CADDY_DIR}:/etc/caddy:ro`, + '--cap-drop', + 'ALL', + '--cap-add', + 'NET_BIND_SERVICE', + '--entrypoint', + '/bin/sh', + ...Object.entries(env).flatMap(([key, value]) => ['-e', `${key}=${value}`]), + caddyImage(), + '/etc/caddy/start.sh', + ]; +} + +async function baseEnv(extra: Record): Promise> { + return { + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + CELLD_PORT: String(celldPort), + REVERSE_TUNNEL_GATEWAY_SECRET: GATEWAY_SECRET, + ...extra, + }; +} + +async function startCaddy(extra: Record): Promise { + const env = await baseEnv(extra); + const container = `sam-live-log-${randomBytes(4).toString('hex')}`; + execFileSync('docker', caddyArgs(container, env)); + const read = () => spawnSync('docker', ['logs', container], { encoding: 'utf8' }); + const stack: Stack = { + container, + https: Number(env.HTTPS_PORT), + stdout: () => read().stdout ?? '', + stderr: () => read().stderr ?? '', + }; + stacks.push(stack); + await waitFor( + 'Caddy to serve TLS', + async () => { + try { + // Any HTTP answer means Caddy serves TLS; a stack whose upstream is down answers 502. + return (await get(stack, `app.${DOMAIN}`, '/ready')).status > 0; + } catch { + return false; + } + }, + 120_000, + stack.stderr + ); + return stack; +} + +function get( + stack: Stack, + host: string, + path: string, + headers: Record = {} +): Promise<{ status: number }> { + return new Promise((done, fail) => { + const req = httpsRequest({ + host: '127.0.0.1', + port: stack.https, + servername: host, + rejectUnauthorized: false, + path, + headers: { Host: host, ...headers }, + }); + req.on('response', (res) => { + res.resume(); + res.on('end', () => done({ status: res.statusCode ?? 0 })); + }); + req.on('error', fail); + req.end(); + }); +} + +function accessLines(stack: Stack): Array> { + return stack + .stdout() + .split('\n') + .filter((line) => line.includes('"http.log.access')) + .map((line) => JSON.parse(line) as Record); +} + +/** Removes every running stack, so pings counted next come only from the stack a test starts. */ +function stopStacks(): void { + for (const stack of stacks.splice(0)) spawnSync('docker', ['rm', '-f', stack.container]); +} + +function healthHitsSince(start: number): Hit[] { + return hits.slice(start).filter((hit) => hit.url === '/health'); +} + +beforeAll(async () => { + celldPort = await freePort(); + celld = createServer((req, res) => { + hits.push({ host: req.headers.host ?? '', url: req.url ?? '' }); + if (req.url === '/health') { + res.statusCode = healthStatus; + res.end('health'); + return; + } + res.setHeader('Set-Cookie', `session=${SECRETS.responseCookie}`); + res.end('celld'); + }); + await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); +}); + +afterAll(async () => { + for (const stack of stacks) spawnSync('docker', ['rm', '-f', stack.container]); + await new Promise((done) => celld.close(() => done())); +}); + +describe('access log', () => { + let stack: Stack; + beforeAll(async () => { + stack = await startCaddy({ SAM_KEEP_WARM: 'off' }); + }); + + it('logs one line per request with host, path, status and duration, and nothing secret', async () => { + const reply = await get(stack, `app.${DOMAIN}`, `/api/projects?token=${SECRETS.query}&x=1`, { + Cookie: `__Secure-better-auth.session_token=${SECRETS.cookie}`, + Authorization: `Bearer ${SECRETS.bearer}`, + 'X-SAM-Upstream-Authorization': SECRETS.samHeader, + }); + expect(reply.status).toBe(200); + // Liveness: the request did reach celld with its query, so redaction is in the log only. + expect(hits.some((hit) => hit.url.includes(SECRETS.query))).toBe(true); + + let line: Record | undefined; + await waitFor( + 'the access-log line', + async () => { + line = accessLines(stack).find((entry) => JSON.stringify(entry).includes('/api/projects')); + return line !== undefined; + }, + 10_000, + stack.stderr + ); + const request = line!.request as Record; + expect(request.host).toBe(`app.${DOMAIN}`); + expect(request.method).toBe('GET'); + expect(request.uri).toBe('/api/projects?'); + expect(request.headers).toBeUndefined(); + expect(line!.resp_headers).toBeUndefined(); + expect(line!.status).toBe(200); + expect(typeof line!.duration).toBe('number'); + + const everything = stack.stdout() + stack.stderr(); + for (const secret of [...Object.values(SECRETS), GATEWAY_SECRET]) { + expect(everything).not.toContain(secret); + } + }); + + it('replaces a credential carried in the path, and leaves other paths alone', async () => { + const token = `pt${randomBytes(12).toString('hex')}`; + const cases: Array<[string, string, string]> = [ + [ + `api.${DOMAIN}`, + `/ai/proxy/${token}/anthropic/v1/messages`, + '/ai/proxy//anthropic/v1/messages', + ], + [`api.${DOMAIN}`, `/api/bootstrap/${token}`, '/api/bootstrap/'], + [ + `api.${DOMAIN}`, + `/api/projects/invite-links/${token}/request?x=1`, + '/api/projects/invite-links//request?', + ], + [`app.${DOMAIN}`, `/projects/invite/${token}`, '/projects/invite/'], + [`preview.${DOMAIN}`, `/p/proj/file/1/9999/${token}/index.html`, '/p/'], + [`api.${DOMAIN}`, '/api/projects/p1/sessions', '/api/projects/p1/sessions'], + ]; + for (const [host, path] of cases) expect((await get(stack, host, path)).status).toBe(200); + await waitFor('every path-case line', async () => { + const uris = accessLines(stack).map((line) => (line.request as { uri?: string }).uri); + return cases.every(([, , logged]) => uris.includes(logged)); + }); + // Liveness: the token reached celld unchanged; only the log is redacted. + expect(hits.filter((hit) => hit.url.includes(token))).toHaveLength(5); + expect(stack.stdout() + stack.stderr()).not.toContain(token); + }); + + it('redacts the query of a proxy-error entry in Caddy own log', async () => { + const down = await startCaddy({ SAM_KEEP_WARM: 'off', CELLD_PORT: String(await freePort()) }); + expect((await get(down, `api.${DOMAIN}`, `/x?t=${SECRETS.query}`)).status).toBe(502); + await waitFor('the proxy error entry', async () => down.stderr().includes('/x?')); + expect(down.stdout() + down.stderr()).not.toContain(SECRETS.query); + }); +}); + +describe('keep-warm', () => { + beforeEach(stopStacks); + it('sends GET /health on the API host while idle', async () => { + const start = hits.length; + await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); + await waitFor('three keep-warm pings', async () => healthHitsSince(start).length >= 3); + expect(healthHitsSince(start).every((hit) => hit.host === `api.${DOMAIN}`)).toBe(true); + }); + + it('a failing /health leaves real traffic untouched', async () => { + const stack = await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); + healthStatus = 503; + try { + const start = hits.length; + await waitFor('two failed pings', async () => healthHitsSince(start).length >= 2); + for (let i = 0; i < 3; i++) { + expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + } + } finally { + healthStatus = 200; + } + }); + + it('SAM_KEEP_WARM=off sends nothing', async () => { + const stack = await startCaddy({ SAM_KEEP_WARM: 'off', SAM_KEEP_WARM_INTERVAL: '1s' }); + const start = hits.length; + await sleep(3_500); + expect(healthHitsSince(start)).toEqual([]); + // Liveness: this Caddy is serving. + expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + }); + + it.each([ + [{ SAM_KEEP_WARM: 'yes' }, /SAM_KEEP_WARM must be on or off/], + [{ SAM_KEEP_WARM_INTERVAL: '7s' }, /SAM_KEEP_WARM_INTERVAL must be 1s to 6s/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '0' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '2d' }, /SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be/], + // A shell override handed straight to docker compose (F21 L5): celld's operator port inside + // the lease range the deploy wrote to gateway.env. + [ + { CELLD_INTERNAL_PORT: String(LIVE_TUNNEL_RANGE.start + 1) }, + /CELLD_INTERNAL_PORT \(20001\) lies inside the reverse-tunnel range 20000-20099/, + ], + [{ REVERSE_TUNNEL_PORT_RANGE_END: '' }, /REVERSE_TUNNEL_PORT_RANGE_START\/END missing/], + ])('start.sh refuses %j', async (extra, message) => { + const container = `sam-live-log-${randomBytes(4).toString('hex')}`; + const run = spawnSync( + 'docker', + caddyArgs(container, await baseEnv(extra)).map((arg) => (arg === '-d' ? '--rm' : arg)), + { encoding: 'utf8', timeout: 60_000 } + ); + expect(run.status).toBe(64); + expect(run.stderr).toMatch(message); + }); +}); diff --git a/scripts/selfhost/live/caddy-fragments.live.test.ts b/scripts/selfhost/live/caddy-fragments.live.test.ts new file mode 100644 index 0000000000..b84cd8c9c2 --- /dev/null +++ b/scripts/selfhost/live/caddy-fragments.live.test.ts @@ -0,0 +1,492 @@ +/** + * Live: the box's real Caddyfile and sam.d fragments (deploy/selfhost/caddy/), run by the + * pinned Caddy release in Docker with host networking, in front of stub upstreams that record + * what reaches them: + * + * - celld stub: answers the forward_auth subrequest as the test scenario says, and 200 for + * anything else (so a request that should never leave Caddy is visible when it does); + * - node stub: a node agent behind a lease port that accepts WebSocket upgrades. + * + * Checked: the public 404 for /api/self-host/gateway on every host and under path tricks + * (encodings at any depth, backslash separators, dot segments, absolute-form targets), that paths + * merely containing "self-host" still reach celld, the per-address rate limit on frp connections + * (/~!frp), the stripping of client X-SAM-* headers before forward_auth and before the node, and + * the 101 Set-Cookie rule for port-preview sockets. + * + * Image: the box's Caddy image, built from deploy/selfhost/caddy/Dockerfile as compose builds it, + * started through start.sh with the frp rate limit lowered to FRP_LOGIN_LIMIT. + */ +import { execFileSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { + createServer, + type IncomingHttpHeaders, + type IncomingMessage, + type OutgoingHttpHeaders, + type Server, +} from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { posix } from 'node:path'; +import type { Duplex } from 'node:stream'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { caddyBoxEnv, caddyImage, freePort, REPO_ROOT, waitFor } from './harness'; + +const DOMAIN = 'sam.test'; +const SECRET = randomBytes(32).toString('hex'); +const WORKSPACE = '01krrtliveaaaaaaaaaaaaaaaa'; +const WS_HOST = `ws-${WORKSPACE}.${DOMAIN}`; +const PORT_HOST = `ws-${WORKSPACE}--3000.${DOMAIN}`; +const CADDY_DIR = `${REPO_ROOT}/deploy/selfhost/caddy`; +/** frp connections one address may open per minute in this run (the box default is 60). */ +const FRP_LOGIN_LIMIT = 3; + +interface Seen { + method: string; + url: string; + headers: IncomingHttpHeaders; +} + +type Decision = { status: number; headers?: OutgoingHttpHeaders }; + +const celldSeen: Seen[] = []; +const nodeSeen: Seen[] = []; +const frpsSeen: Seen[] = []; +let decide: (req: IncomingMessage) => Decision = () => ({ status: 401 }); +let nodeUpgradeHeaders: Record = {}; +let celld: Server; +let node: Server; +let frps: Server; +let ports: { https: number; http: number; celld: number; frps: number; node: number }; +let container = ''; + +const record = (req: IncomingMessage): Seen => ({ + method: req.method ?? '', + url: req.url ?? '', + headers: req.headers, +}); + +function acceptKey(key: string | string[] | undefined): string { + return createHash('sha1') + .update(`${String(key)}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64'); +} + +beforeAll(async () => { + ports = { + https: await freePort(), + http: await freePort(), + celld: await freePort(), + frps: await freePort(), + node: await freePort(), + }; + celld = createServer((req, res) => { + celldSeen.push(record(req)); + if (req.url?.startsWith('/api/self-host/gateway/node-websocket')) { + const { status, headers } = decide(req); + res.writeHead(status, headers); + res.end(); + return; + } + res.end('celld'); + }); + node = createServer((req, res) => { + nodeSeen.push(record(req)); + res.setHeader('Set-Cookie', 'node_cookie=1'); + res.end('node'); + }); + node.on('upgrade', (req: IncomingMessage, socket: Duplex) => { + nodeSeen.push(record(req)); + const extra = Object.entries(nodeUpgradeHeaders) + .map(([name, value]) => `${name}: ${value}\r\n`) + .join(''); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${acceptKey(req.headers['sec-websocket-key'])}\r\n${extra}\r\n` + ); + socket.end(); + }); + // Stands in for frps: plain HTTP is enough to see which /~!frp requests Caddy let through. + frps = createServer((req, res) => { + frpsSeen.push(record(req)); + res.end('frps'); + }); + await new Promise((done) => celld.listen(ports.celld, '127.0.0.1', done)); + await new Promise((done) => node.listen(ports.node, '127.0.0.1', done)); + await new Promise((done) => frps.listen(ports.frps, '127.0.0.1', done)); + + container = `sam-live-caddy-${randomBytes(4).toString('hex')}`; + const env = { + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + HTTP_PORT: String(ports.http), + HTTPS_PORT: String(ports.https), + CELLD_PORT: String(ports.celld), + FRPS_BIND_PORT: String(ports.frps), + REVERSE_TUNNEL_GATEWAY_SECRET: SECRET, + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: String(FRP_LOGIN_LIMIT), + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '1m', + }; + // As docker-compose.yml runs it: start.sh as the entrypoint, only NET_BIND_SERVICE. + execFileSync('docker', [ + 'run', + '-d', + '--rm', + '--name', + container, + '--network', + 'host', + '--cap-drop', + 'ALL', + '--cap-add', + 'NET_BIND_SERVICE', + '-v', + `${CADDY_DIR}:/etc/caddy:ro`, + '--entrypoint', + '/bin/sh', + ...Object.entries(env).flatMap(([name, value]) => ['-e', `${name}=${value}`]), + caddyImage(), + '/etc/caddy/start.sh', + ]); + const logs = () => { + try { + return execFileSync('docker', ['logs', container], { encoding: 'utf8', stdio: 'pipe' }); + } catch (err) { + return String(err); + } + }; + await waitFor( + 'Caddy to serve TLS', + async () => { + try { + return (await send('app', '/')).status === 200; + } catch { + return false; + } + }, + 120_000, + logs + ); +}); + +afterAll(async () => { + if (container) execFileSync('docker', ['rm', '-f', container], { stdio: 'ignore' }); + await new Promise((done) => (celld ? celld.close(() => done()) : done())); + await new Promise((done) => (node ? node.close(() => done()) : done())); + await new Promise((done) => (frps ? frps.close(() => done()) : done())); +}); + +beforeEach(() => { + celldSeen.length = 0; + nodeSeen.length = 0; + frpsSeen.length = 0; + nodeUpgradeHeaders = {}; + decide = () => ({ status: 401 }); +}); + +interface Reply { + status: number; + headers: IncomingHttpHeaders; +} + +/** One HTTPS request through Caddy with an exact raw path (Node does not normalize it). */ +function send( + host: string, + path: string, + headers: Record = {}, + upgrade = false +): Promise { + const fullHost = host.includes('.') ? host : `${host}.${DOMAIN}`; + return new Promise((done, fail) => { + const req = httpsRequest({ + host: '127.0.0.1', + port: ports.https, + servername: fullHost.toLowerCase(), + rejectUnauthorized: false, + method: 'GET', + path, + headers: { + Host: fullHost, + ...(upgrade + ? { + Connection: 'Upgrade', + Upgrade: 'websocket', + 'Sec-WebSocket-Version': '13', + 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), + } + : {}), + ...headers, + }, + }); + req.on('upgrade', (res: IncomingMessage, socket: Duplex) => { + socket.destroy(); + done({ status: res.statusCode ?? 0, headers: res.headers }); + }); + req.on('response', (res) => { + res.resume(); + res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers })); + }); + req.on('error', fail); + req.end(); + }); +} + +/** What celld (Deno / workerd URL parsing) could treat as the gateway route, generously. */ +function couldBeGatewayPath(raw: string): boolean { + let path = (raw.split('?')[0] ?? '').replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, ''); + for (let i = 0; i < 3; i += 1) { + try { + path = decodeURIComponent(path); + } catch { + break; + } + } + path = posix.normalize(path.replaceAll('\\', '/').replace(/\/+/g, '/')).toLowerCase(); + return path.startsWith('/api/self-host/gateway'); +} + +const HOSTS = ['api', 'app', `ws-${WORKSPACE}`, `ws-${WORKSPACE}--3000`, 'API']; +const CANONICAL = [ + '/api/self-host/gateway', + '/api/self-host/gateway/', + '/api/self-host/gateway/frps-plugin?op=Login', + '/api/self-host/gateway/node-websocket', +]; +const TRICKS = [ + '//api/self-host/gateway/frps-plugin', + '/api//self-host/gateway/frps-plugin', + '/api/self-host//gateway/node-websocket', + '/api/self-host/./gateway/frps-plugin', + '/api/self-host/x/../gateway/frps-plugin', + '/api/./self-host/gateway/', + '/api/self-host/gateway%2Ffrps-plugin', + '/api%2Fself-host%2Fgateway%2Ffrps-plugin', + '/api/self-host/%67ateway/frps-plugin', + '/api/self-host/gateway%252Ffrps-plugin', + '/API/SELF-HOST/GATEWAY/frps-plugin', + '/Api/Self-Host/Gateway', + '/api/self-host/gateway;x=1', + '/api/self-host/gateway%00/frps-plugin', + '/api/self-host/gateway/..%2Ffrps-plugin', + // Encoded hyphen: only the raw-request-path clause of the variant matcher sees these. + '/api/self%2Dhost/gateway/', + '/API/SELF%2DHOST/gateway', + '/api/self%252dhost/gateway/frps-plugin', + '/api/self%252Dhost/gateway/node-websocket', + // Encoded letters at any depth (F21 L1: the old matcher enumerated only the hyphen's spellings). + '/api/%73elf-host/gateway/frps-plugin', + '/api/%2573elf-host/gateway/frps-plugin', + '/api/%252573elf-host/gateway/node-websocket', + '/api/SELF-HOS%2554/gateway', + '/%61pi/self-host/gateway/frps-plugin', + '/%2561%2570%2569/self-host/gateway', + // Backslash separators (a WHATWG URL parser reads \ as / in http(s) URLs) and dot segments. + '/api\\self-host\\gateway\\frps-plugin', + '/api%5Cself-host%5Cgateway', + '/x\\..\\api\\self-host\\gateway\\frps-plugin', + '/api/x\\..\\self-host/gateway/frps-plugin', + '/api/x/%2e%2e/self-host/gateway/frps-plugin', + '/static/%2e%2e/api/%2573elf-host/gateway', + // Absolute-form request target. + `https://api.${DOMAIN}/api/self-host/gateway/frps-plugin`, + `https://api.${DOMAIN}/api/%2573elf-host/gateway`, +]; + +describe('internal gateway routes are never served publicly', () => { + it.each(HOSTS.flatMap((host) => CANONICAL.map((path) => [host, path] as const)))( + '404 on %s for %s, plain and upgrade', + async (host, path) => { + for (const upgrade of [false, true]) { + const reply = await send(host, path, {}, upgrade); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBe(404); + } + expect(celldSeen).toEqual([]); + expect(nodeSeen).toEqual([]); + } + ); + + // Non-workspace hosts only: on a ws-* host the Worker hands every request to the workspace + // proxy before any route (apps/api/src/index.ts; pinned by the workers test 'never forwards + // the gateway secret to a node, even when a request carrying it reaches the ws-* proxy'). + const API_HOSTS = ['api', 'app', 'API', 'App']; + it.each(API_HOSTS.flatMap((host) => TRICKS.map((path) => [host, path] as const)))( + 'no path trick on %s reaches the gateway route: %s', + async (host, path) => { + for (const upgrade of [false, true]) { + const reply = await send(host, path, {}, upgrade); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).not.toBe(101); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBeGreaterThanOrEqual(400); + } + // Whatever Caddy did with it, nothing celld could route to the gateway arrived there. + expect(celldSeen.filter((seen) => couldBeGatewayPath(seen.url))).toEqual([]); + expect(nodeSeen).toEqual([]); + } + ); + + it('control: ordinary API traffic and a preview app path naming self-hosting reach celld', async () => { + expect((await send('api', '/api/projects?q=self-host')).status).toBe(200); + expect((await send(`ws-${WORKSPACE}--3000`, '/docs/self-hosting')).status).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual([ + '/api/projects?q=self-host', + '/docs/self-hosting', + ]); + }); + + // F21 L6: only the gateway prefix is refused; a public path that merely names "self-host" + // (a docs page, a project file called self-host) still reaches the app. + const PUBLIC = [ + ['app', '/docs/self-host/guide'], + ['app', '/blog/how-to-self-host'], + ['api', '/api/projects/p1/files/self-host/README.md'], + ['api', '/api/projects/p1/files/docs%2Fself-host'], + ['api', '/api/self-hosted'], + ['api', '/api/x/self-host'], + ] as const; + it.each(PUBLIC)('control: %s%s reaches celld', async (host, path) => { + expect((await send(host, path)).status, `${host}${path}`).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual([path]); + }); +}); + +describe('frp connections are rate limited per client address', () => { + it(`passes ${FRP_LOGIN_LIMIT} connections a minute to frps, then answers 429`, async () => { + const replies: number[] = []; + for (let i = 0; i < FRP_LOGIN_LIMIT + 2; i += 1) { + replies.push((await send('api', '/~!frp')).status); + } + expect(replies.slice(FRP_LOGIN_LIMIT)).toEqual([429, 429]); + expect(replies.slice(0, FRP_LOGIN_LIMIT).every((status) => status !== 429)).toBe(true); + expect(frpsSeen).toHaveLength(FRP_LOGIN_LIMIT); + // Control: the limit is the frp route's alone; the API on the same host still answers. + expect((await send('api', '/health')).status).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual(['/health']); + }); +}); + +const FORGED = { + 'X-SAM-Gateway-Secret': 'client-forged-secret', + 'X-SAM-Gateway-Original-Host': `api.${DOMAIN}`, + 'X-SAM-Upstream': '127.0.0.1:7001', + 'X-SAM-Upstream-Uri': '/forged', + 'X-SAM-Upstream-Authorization': 'Bearer forged', + 'X-SAM-Upstream-Cookie': 'forged=1', + 'x-sam-node-id': 'FORGED-NODE', + 'X-Sam-Workspace-Id': 'FORGED-WS', +}; + +const forwardAuth = () => + celldSeen.filter((seen) => seen.url.startsWith('/api/self-host/gateway/node-websocket')); + +describe('forward_auth for node WebSockets', () => { + it.each([WS_HOST, PORT_HOST])( + 'strips client X-SAM-* headers before forward_auth and passes a refusal through (%s)', + async (host) => { + decide = () => ({ status: 401, headers: { 'Content-Type': 'application/json' } }); + const reply = await send(host, '/agent/ws', FORGED, true); + expect(reply.status).toBe(401); + const [auth, ...more] = forwardAuth(); + expect(more).toEqual([]); + expect(auth?.headers['x-sam-gateway-secret']).toBe(SECRET); + expect(auth?.headers['x-sam-gateway-original-host']).toBe(host); + expect(auth?.headers['x-forwarded-uri']).toBe('/agent/ws'); + for (const name of [ + 'x-sam-upstream', + 'x-sam-upstream-uri', + 'x-sam-upstream-authorization', + 'x-sam-upstream-cookie', + 'x-sam-node-id', + 'x-sam-workspace-id', + ]) { + expect(auth?.headers[name], name).toBeUndefined(); + } + expect(nodeSeen).toEqual([]); + } + ); + + it('proxies an authorized socket with exactly the Worker-decided headers', async () => { + decide = () => ({ + status: 200, + headers: { + 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, + 'X-SAM-Upstream-Uri': '/agent/ws?decided=1', + 'X-SAM-Upstream-Authorization': 'Bearer worker-decided', + 'X-SAM-Upstream-Cookie': '', + 'X-SAM-Node-Id': 'NODE-REAL', + 'X-SAM-Workspace-Id': 'WS-REAL', + }, + }); + const reply = await send( + WS_HOST, + '/agent/ws?client=1', + { ...FORGED, Authorization: 'Bearer client', Cookie: 'session=client' }, + true + ); + expect(reply.status).toBe(101); + const [upstream] = nodeSeen; + expect(upstream?.url).toBe('/agent/ws?decided=1'); + expect(upstream?.headers.authorization).toBe('Bearer worker-decided'); + expect(upstream?.headers.cookie ?? '').toBe(''); + expect(upstream?.headers['x-sam-node-id']).toBe('NODE-REAL'); + expect(upstream?.headers['x-sam-workspace-id']).toBe('WS-REAL'); + expect(upstream?.headers['x-forwarded-host']).toBe(WS_HOST); + for (const name of [ + 'x-sam-gateway-secret', + 'x-sam-gateway-original-host', + 'x-sam-upstream', + 'x-sam-upstream-uri', + 'x-sam-upstream-authorization', + 'x-sam-upstream-cookie', + ]) { + expect(upstream?.headers[name], name).toBeUndefined(); + } + }); +}); + +describe('Set-Cookie on port-preview sockets', () => { + const allowTo = (uri: string): Decision => ({ + status: 200, + headers: { + 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, + 'X-SAM-Upstream-Uri': uri, + 'X-SAM-Upstream-Authorization': '', + 'X-SAM-Upstream-Cookie': '', + 'X-SAM-Node-Id': 'NODE-REAL', + 'X-SAM-Workspace-Id': 'WS-REAL', + }, + }); + + it('drops a Set-Cookie the workspace app sends on its 101 upgrade', async () => { + decide = () => allowTo('/workspaces/W/ports/3000/hmr'); + nodeUpgradeHeaders = { 'Set-Cookie': 'sam_port_access=from-the-app; Path=/' }; + const reply = await send(PORT_HOST, '/hmr', {}, true); + expect(reply.status).toBe(101); + expect(nodeSeen).toHaveLength(1); + expect(reply.headers['set-cookie']).toBeUndefined(); + }); + + it("control: SAM's own port-token redirect keeps its cookie", async () => { + decide = () => ({ + status: 302, + headers: { + Location: `https://${PORT_HOST}/app`, + 'Set-Cookie': 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', + }, + }); + const reply = await send(PORT_HOST, '/app?port_token=t', {}, true); + expect(reply.status).toBe(302); + expect(reply.headers['set-cookie']).toEqual([ + 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', + ]); + expect(nodeSeen).toEqual([]); + }); + + it('control: the agent socket on a non-port host is not a port preview', async () => { + decide = () => allowTo('/agent/ws'); + nodeUpgradeHeaders = { 'X-Node-Marker': 'reached' }; + const reply = await send(WS_HOST, '/agent/ws', {}, true); + expect(reply.status).toBe(101); + expect(reply.headers['x-node-marker']).toBe('reached'); + }); +}); diff --git a/scripts/selfhost/live/celld-lab.ts b/scripts/selfhost/live/celld-lab.ts new file mode 100644 index 0000000000..97bbb00e23 --- /dev/null +++ b/scripts/selfhost/live/celld-lab.ts @@ -0,0 +1,216 @@ +/** + * A celld node on loopback for the live suite: the box's object store (the pinned MinIO image), + * the pinned celld binary serving from it, and `celld deploy` of a probe project. Shared by every + * live test that runs a Worker on the real runtime, so each test states only what it probes. + */ +import { spawnSync, type SpawnSyncReturns } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { parse } from 'yaml'; + +import { resolveEsbuild } from '../celld-binary.js'; +import { freePort, REPO_ROOT, type Running, start, waitFor } from './harness'; + +/** The object store image docker-compose.yml pins (digest); `mc` ships in it. */ +export const OBJECTSTORE_IMAGE = ( + parse(readFileSync(join(REPO_ROOT, 'deploy/selfhost/docker-compose.yml'), 'utf8')) as { + services: { objectstore: { image: string } }; + } +).services.objectstore.image; + +/** + * The docker CLI from a fixed system directory, never resolved through a caller-controlled PATH + * (as harness.ts does for tar and openssl). Empty when docker is not installed. + */ +export const DOCKER = + ['/usr/bin/docker', '/usr/local/bin/docker', '/bin/docker'].find((path) => existsSync(path)) ?? + ''; +export const hasDocker = + DOCKER !== '' && spawnSync(DOCKER, ['version'], { stdio: 'ignore' }).status === 0; + +export interface ObjectStore { + port: number; + /** `http://127.0.0.1:` */ + url: string; + /** The S3 credentials celld and its deploy command read. */ + env: () => Record; + /** `mc` from the same image, with `src` aliased to this store. `extra` goes before the image. */ + mc: (args: string[], extra?: string[]) => SpawnSyncReturns; + stop: () => void; +} + +/** Start the pinned object store on a free loopback port and create the `fleet` bucket. */ +export async function startObjectStore(key: string, secret: string): Promise { + const port = await freePort(); + const run = spawnSync( + DOCKER, + [ + 'run', + '-d', + '--rm', + '--network', + 'host', + '-e', + `MINIO_ROOT_USER=${key}`, + '-e', + `MINIO_ROOT_PASSWORD=${secret}`, + '--entrypoint', + 'minio', + OBJECTSTORE_IMAGE, + 'server', + '/data', + '--address', + `127.0.0.1:${port}`, + '--console-address', + `127.0.0.1:${await freePort()}`, + ], + { encoding: 'utf8' } + ); + if (run.status !== 0) throw new Error(`object store did not start: ${run.stderr}`); + const container = run.stdout.trim(); + const url = `http://127.0.0.1:${port}`; + const store: ObjectStore = { + port, + url, + env: () => ({ AWS_ACCESS_KEY_ID: key, AWS_SECRET_ACCESS_KEY: secret, AWS_REGION: 'us-east-1' }), + mc: (args, extra = []) => + spawnSync( + DOCKER, + [ + 'run', + '--rm', + '--network', + 'host', + ...extra, + '-e', + `MC_HOST_src=http://${key}:${secret}@127.0.0.1:${port}`, + '-e', + 'MC_CONFIG_DIR=/tmp/mc', + '--entrypoint', + 'mc', + OBJECTSTORE_IMAGE, + ...args, + ], + { encoding: 'utf8' } + ), + stop: () => { + spawnSync(DOCKER, ['rm', '-f', container]); + }, + }; + try { + await waitFor( + 'object store', + async () => (await fetch(`${url}/minio/health/live`).catch(() => null))?.ok + ); + const made = store.mc(['mb', 'src/fleet']); + if (made.status !== 0) throw new Error(`bucket not created: ${made.stderr}`); + } catch (error) { + store.stop(); + throw error; + } + return store; +} + +export interface CelldNode { + /** Ports celld serves Workers and its internal API on. */ + port: number; + internalPort: number; + /** `--bucket --endpoint ` for celld and `celld deploy`. */ + bucketArgs: () => string[]; + start: () => Running; + /** `celld deploy `; the caller asserts on the result. */ + deploy: (project: string) => SpawnSyncReturns; + /** Start celld, deploy `project`, and wait until `/` answers 200. */ + serve: (project: string) => Promise; +} + +/** A celld node over `store`, serving `bucket` (an s3:// URL inside the `fleet` bucket). */ +export async function celldNode( + binary: string, + store: ObjectStore, + bucket = 's3://fleet' +): Promise { + const port = await freePort(); + const internalPort = await freePort(); + const bucketArgs = () => ['--bucket', bucket, '--endpoint', store.url]; + const node: CelldNode = { + port, + internalPort, + bucketArgs, + start: () => + start( + binary, + [ + ...bucketArgs(), + '--listen', + `127.0.0.1:${port}`, + '--internal-listen', + `127.0.0.1:${internalPort}`, + ], + store.env() + ), + deploy: (project) => + spawnSync(binary, ['deploy', project, ...bucketArgs()], { + encoding: 'utf8', + env: { + ...process.env, + ...store.env(), + CELLD_ESBUILD: resolveEsbuild(join(REPO_ROOT, 'apps/api')), + }, + }), + serve: async (project) => { + const running = node.start(); + const deployed = node.deploy(project); + if (deployed.status !== 0) { + await running.stop(); + throw new Error(`celld deploy failed: ${deployed.stderr}${deployed.stdout}`); + } + await waitFor( + 'celld to serve the Worker', + async () => (await fetch(`http://127.0.0.1:${port}/`).catch(() => null))?.status === 200, + 120_000, + () => running.output() + ); + return running; + }, + }; + return node; +} + +/** + * Write a celld project: the Worker source plus its `wrangler.json`. `bindings` adds top-level + * wrangler keys (`d1_databases`, `r2_buckets`, ...); `probeObject` binds the `ProbeDO` class. + */ +export function writeProject( + dir: string, + config: { + name: string; + worker: string; + vars: Record; + probeObject?: boolean; + main?: string; + bindings?: Record; + } +): string { + const main = config.main ?? 'worker.js'; + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, main), config.worker); + writeFileSync( + join(dir, 'wrangler.json'), + JSON.stringify({ + name: config.name, + main, + compatibility_date: '2026-01-01', + ...(config.probeObject + ? { + durable_objects: { bindings: [{ name: 'PROBE_DO', class_name: 'ProbeDO' }] }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['ProbeDO'] }], + } + : {}), + ...config.bindings, + vars: config.vars, + }) + ); + return dir; +} diff --git a/scripts/selfhost/live/celld-redirect.live.test.ts b/scripts/selfhost/live/celld-redirect.live.test.ts new file mode 100644 index 0000000000..1965aafcca --- /dev/null +++ b/scripts/selfhost/live/celld-redirect.live.test.ts @@ -0,0 +1,161 @@ +/** + * The API's guarded fetch on the real celld runtime (`celld dev`, the pinned, checksum-verified + * release), not a mocked fetch: the guard is only as good as the runtime's `redirect: 'manual'`. + * + * A Worker bundles packages/worker-core/src/network-hosts and calls stub servers on loopback. The first + * case records why the guard exists: celld's default fetch follows a 302 to an internal service + * and hands back its body (res.redirected stays false, so nothing downstream can tell). + */ +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { ensureCelldBinary, resolveEsbuild } from '../celld-binary.js'; +import { freePort, LIVE_TMP, REPO_ROOT, type Running, start, waitFor } from './harness'; + +const NETWORK_HOSTS = join(REPO_ROOT, 'packages/worker-core/src/network-hosts/index.ts'); + +const WORKER = ` +import { guardedFetch } from ${JSON.stringify(NETWORK_HOSTS)}; + +async function run(fn) { + try { + const response = await fn(); + return { status: response.status, location: response.headers.get('location'), body: await response.text() }; + } catch (error) { + return { error: String(error && error.name), reason: error && error.reason }; + } +} + +export default { + async fetch(request) { + const url = new URL(request.url); + const target = url.searchParams.get('target'); + const policy = { allowPrivateNetwork: true }; + const cases = { + '/default': () => fetch(target), + '/manual': () => fetch(target, { redirect: 'manual' }), + '/guarded': () => guardedFetch(target, {}, policy), + }; + const fn = cases[url.pathname]; + return fn ? Response.json(await run(fn)) : new Response('celld-redirect'); + }, +}; +`; + +let edge: Server; +let internal: Server; +let ports: { edge: number; internal: number; celld: number }; +let celld: Running | undefined; +let internalHits = 0; + +beforeAll(async () => { + ports = { edge: await freePort(), internal: await freePort(), celld: await freePort() }; + internal = createServer((_req, res) => { + internalHits += 1; + res.end('INTERNAL'); + }); + edge = createServer((req, res) => { + const path = req.url ?? '/'; + const hop = /^\/chain\/(\d+)$/.exec(path); + if (path === '/to-internal') { + res.writeHead(302, { Location: `http://127.0.0.1:${ports.internal}/secret` }); + } else if (path === '/to-same') { + res.writeHead(302, { Location: '/final' }); + } else if (hop) { + res.writeHead(302, { Location: `/chain/${Number(hop[1]) + 1}` }); + } else { + res.writeHead(200); + } + res.end(path === '/final' ? 'FINAL' : ''); + }); + await new Promise((done) => internal.listen(ports.internal, '127.0.0.1', done)); + await new Promise((done) => edge.listen(ports.edge, '127.0.0.1', done)); + + mkdirSync(LIVE_TMP, { recursive: true }); + const project = mkdtempSync(join(LIVE_TMP, 'celld-redirect-')); + writeFileSync( + join(project, 'wrangler.json'), + JSON.stringify({ name: 'redirect-probe', main: 'worker.js', compatibility_date: '2026-01-01' }) + ); + writeFileSync(join(project, 'worker.js'), WORKER); + const binary = await ensureCelldBinary(join(LIVE_TMP, 'celld-bin')); + celld = start( + 'bash', + [ + '-c', + `cd "$0" && exec "$1" dev . --host 127.0.0.1 --port "$2"`, + project, + binary, + String(ports.celld), + ], + { CELLD_ESBUILD: resolveEsbuild(join(REPO_ROOT, 'apps/api')) } + ); + await waitFor( + 'celld dev to serve the Worker', + async () => { + try { + return (await fetch(`http://127.0.0.1:${ports.celld}/`)).status === 200; + } catch { + return false; + } + }, + 120_000, + () => celld?.output() ?? '' + ); +}); + +afterAll(async () => { + await celld?.stop(); + await new Promise((done) => (edge ? edge.close(() => done()) : done())); + await new Promise((done) => (internal ? internal.close(() => done()) : done())); +}); + +async function ask(path: string, target: string): Promise> { + const url = `http://127.0.0.1:${ports.celld}${path}?target=${encodeURIComponent(target)}`; + return (await (await fetch(url)).json()) as Record; +} + +const at = (path: string): string => `http://127.0.0.1:${ports.edge}${path}`; + +describe('redirects on the real celld runtime', () => { + it("celld's default fetch follows a redirect to an internal service (why the guard exists)", async () => { + const before = internalHits; + expect(await ask('/default', at('/to-internal'))).toMatchObject({ + status: 200, + body: 'INTERNAL', + }); + expect(internalHits).toBe(before + 1); + }); + + it("redirect: 'manual' returns the 302 and its Location, and nothing follows it", async () => { + const before = internalHits; + expect(await ask('/manual', at('/to-internal'))).toMatchObject({ + status: 302, + location: `http://127.0.0.1:${ports.internal}/secret`, + }); + expect(internalHits).toBe(before); + }); + + it('guardedFetch refuses a hop to another private origin before requesting it', async () => { + const before = internalHits; + expect(await ask('/guarded', at('/to-internal'))).toEqual({ + error: 'OutboundRequestRefusedError', + reason: 'host', + }); + expect(internalHits).toBe(before); + }); + + it('control: guardedFetch follows a validated same-origin hop to the final response', async () => { + expect(await ask('/guarded', at('/to-same'))).toMatchObject({ status: 200, body: 'FINAL' }); + }); + + it('guardedFetch stops a redirect chain past the hop limit', async () => { + expect(await ask('/guarded', at('/chain/0'))).toEqual({ + error: 'OutboundRequestRefusedError', + reason: 'redirect_limit', + }); + }); +}); diff --git a/scripts/selfhost/live/frpc-tls.live.test.ts b/scripts/selfhost/live/frpc-tls.live.test.ts new file mode 100644 index 0000000000..0d9b14901f --- /dev/null +++ b/scripts/selfhost/live/frpc-tls.live.test.ts @@ -0,0 +1,245 @@ +/** + * Live: the frpc.toml cloud-init renders for a reverse-tunnel node, run by the real pinned frpc, + * must refuse a control plane whose certificate does not chain to a CA it trusts (or names + * another host), and must log in when it does. frpc trusts the system pool (useSystemCa); + * SSL_CERT_FILE replaces that pool for the test, which is how Go's crypto/x509 reads it on + * Linux. A TLS terminator in front of a real frps stands in for the box's Caddy. + * + * Also records what frps 0.72.0 actually sends the server plugin, so the NewWorkConn + * authorization in apps/api/src/selfhost/reverse-tunnel/authz.ts rests on observed fields. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer as createHttpServer, type Server } from 'node:http'; +import { connect, createServer as createTcpServer } from 'node:net'; +import { join } from 'node:path'; +import { createServer as createTlsServer, type Server as TlsServer } from 'node:tls'; + +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import YAML from 'yaml'; + +import { generateCloudInit } from '../../../packages/cloud-init/src/generate'; +import { + freePort, + frpBinaries, + LIVE_TMP, + makeCertificate, + type Running, + start, + waitFor, +} from './harness'; + +const NODE_ID = '01M72NODELIVETLS0000000001'; +const INCARNATION = '0f6c0a8e-2a4b-4c55-9d6e-1b2c3d4e5f60'; +// Built at runtime so no secret-shaped literal sits in the source (gitleaks). +const CREDENTIAL = ['Live', 'credential', 'fixture', '0123456789abcdef'].join('_'); + +interface PluginCall { + op: string; + content: Record; +} + +let work: string; +let bins: { frpc: string; frps: string }; +let frps: Running; +let plugin: Server; +let terminator: TlsServer | null = null; +let echo: ReturnType; +const calls: PluginCall[] = []; +let ports: { frps: number; plugin: number; tls: number; lease: number; local: number }; +const running: Running[] = []; + +beforeAll(async () => { + bins = await frpBinaries(); + mkdirSync(LIVE_TMP, { recursive: true }); + work = mkdtempSync(join(LIVE_TMP, 'frpc-tls-')); + ports = { + frps: await freePort(), + plugin: await freePort(), + tls: await freePort(), + lease: await freePort(), + local: await freePort(), + }; + // Stand-in for the SAM plugin: allows everything, records every op it is asked about. + plugin = createHttpServer((req, res) => { + let body = ''; + req.on('data', (chunk: Buffer) => (body += chunk.toString())); + req.on('end', () => { + const parsed = JSON.parse(body) as { op: string; content: Record }; + calls.push({ op: parsed.op, content: parsed.content }); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ reject: false, unchange: true })); + }); + }); + await new Promise((done) => plugin.listen(ports.plugin, '127.0.0.1', done)); + // The node agent's loopback listener frpc forwards to. + echo = createTcpServer((socket) => socket.end('node-agent-says-hi')); + await new Promise((done) => echo.listen(ports.local, '127.0.0.1', done)); + const frpsToml = join(work, 'frps.toml'); + writeFileSync( + frpsToml, + [ + 'bindAddr = "127.0.0.1"', + `bindPort = ${ports.frps}`, + 'proxyBindAddr = "127.0.0.1"', + `allowPorts = [ { start = ${ports.lease}, end = ${ports.lease} } ]`, + 'transport.tls.force = false', + '[[httpPlugins]]', + 'name = "recorder"', + `addr = "http://127.0.0.1:${ports.plugin}"`, + 'path = "/plugin"', + 'ops = ["Login", "NewProxy", "Ping", "NewWorkConn"]', + ].join('\n') + ); + frps = start(bins.frps, ['-c', frpsToml]); + await waitFor( + 'frps to listen', + () => frps.output().includes('frps started successfully'), + 15_000, + frps.output + ); +}); + +afterEach(async () => { + for (const proc of running.splice(0)) await proc.stop(); + await new Promise((done) => (terminator ? terminator.close(() => done()) : done())); + terminator = null; + calls.length = 0; +}); + +afterAll(async () => { + await frps?.stop(); + await new Promise((done) => plugin?.close(() => done())); + await new Promise((done) => echo?.close(() => done())); + if (work) rmSync(work, { recursive: true, force: true }); +}); + +/** TLS on ports.tls, plain TCP to frps: what Caddy does in front of frps on the box. */ +async function serveTls(cert: string, key: string) { + terminator = createTlsServer({ cert: readFileSync(cert), key: readFileSync(key) }, (socket) => { + const upstream = connect(ports.frps, '127.0.0.1'); + socket.pipe(upstream).pipe(socket); + socket.on('error', () => upstream.destroy()); + upstream.on('error', () => socket.destroy()); + }); + terminator.on('tlsClientError', () => {}); + await new Promise((done) => terminator!.listen(ports.tls, '127.0.0.1', done)); +} + +/** The exact frpc.toml cloud-init writes for this node, pointed at the local terminator. */ +function generatedFrpcToml(): string { + const parsed = YAML.parse( + generateCloudInit({ + nodeId: NODE_ID, + nodeRuntimeIncarnationId: INCARNATION, + hostname: 'sam-live-node', + controlPlaneUrl: `https://localhost:${ports.tls}`, + jwksUrl: `https://localhost:${ports.tls}/.well-known/jwks.json`, + callbackToken: 'callback-token', + swapSizeMb: '0', + reverseTunnelCredential: CREDENTIAL, + reverseTunnelRemotePort: String(ports.lease), + reverseTunnelLocalPort: String(ports.local), + }) + ) as { write_files: Array<{ path: string; content: string }> }; + const toml = parsed.write_files.find((f) => f.path === '/etc/sam/frpc/frpc.toml')?.content; + if (!toml) throw new Error('cloud-init wrote no frpc.toml'); + expect(toml).toContain('transport.tls.useSystemCa = true'); + expect(toml).toContain('serverAddr = "localhost"'); + return toml; +} + +function runFrpc(trustedCaPem: string): Running { + const dir = mkdtempSync(join(work, 'frpc-')); + const config = join(dir, 'frpc.toml'); + const trust = join(dir, 'trusted.pem'); + writeFileSync(config, generatedFrpcToml()); + writeFileSync(trust, trustedCaPem); + const proc = start(bins.frpc, ['-c', config], { + SAM_REVERSE_TUNNEL_CREDENTIAL: CREDENTIAL, + SSL_CERT_FILE: trust, + SSL_CERT_DIR: dir, + }); + running.push(proc); + return proc; +} + +describe('frpc certificate verification (generated frpc.toml, real frpc 0.72.0)', () => { + it('refuses a server whose certificate does not chain to a trusted CA', async () => { + const server = makeCertificate(join(work, 'untrusted'), 'localhost'); + const other = makeCertificate(join(work, 'other-ca'), 'localhost'); + await serveTls(server.cert, server.key); + const frpc = runFrpc(other.ca); + await waitFor( + 'a certificate error', + () => /x509|certificate/i.test(frpc.output()), + 30_000, + frpc.output + ); + expect(frpc.output()).not.toContain('login to server success'); + expect(calls.filter((c) => c.op === 'Login')).toEqual([]); + }); + + it('refuses a trusted certificate issued for another host', async () => { + const server = makeCertificate(join(work, 'wrong-host'), 'not-the-box.test'); + await serveTls(server.cert, server.key); + const frpc = runFrpc(server.ca); + await waitFor( + 'a certificate error', + () => /x509|certificate/i.test(frpc.output()), + 30_000, + frpc.output + ); + expect(calls.filter((c) => c.op === 'Login')).toEqual([]); + }); + + it('control: logs in and serves the lease port when the certificate chains to a trusted CA', async () => { + const server = makeCertificate(join(work, 'trusted'), 'localhost'); + await serveTls(server.cert, server.key); + const frpc = runFrpc(server.ca); + await waitFor( + 'frpc login', + () => frpc.output().includes('login to server success'), + 30_000, + frpc.output + ); + await waitFor( + 'the lease proxy', + () => calls.some((c) => c.op === 'NewProxy'), + 15_000, + frpc.output + ); + const login = calls.find((c) => c.op === 'Login')!.content; + expect(login.user).toBe(NODE_ID); + expect(login.metas).toEqual({ + node_id: NODE_ID, + incarnation: INCARNATION, + credential: CREDENTIAL, + }); + + // poolCount: work connections are opened, and authorized, before any user connection. + await waitFor( + 'the pooled work connections', + () => calls.filter((c) => c.op === 'NewWorkConn').length >= 2, + 15_000, + frpc.output + ); + // A connection through the lease port is served by a pooled work connection. + const reply = await new Promise((done, fail) => { + const socket = connect(ports.lease, '127.0.0.1'); + let data = ''; + socket.on('data', (chunk: Buffer) => (data += chunk.toString())); + socket.on('end', () => done(data)); + socket.on('error', fail); + }); + expect(reply).toBe('node-agent-says-hi'); + const workConn = calls.find((c) => c.op === 'NewWorkConn')?.content; + // The fields the SAM plugin relies on, as frps 0.72.0 sends them: `user` is the control + // session's login identity; nothing describes the dialing connection. + expect(Object.keys(workConn ?? {}).sort()).toEqual(['run_id', 'user']); + const user = workConn!.user as { user: string; metas: unknown; run_id: string }; + expect(user.user).toBe(NODE_ID); + expect(user.metas).toEqual(login.metas); + expect(user.run_id).toMatch(/^[0-9a-f]{16}$/); + expect(workConn!.run_id).toBe(user.run_id); + }); +}); diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts new file mode 100644 index 0000000000..9cbfd84814 --- /dev/null +++ b/scripts/selfhost/live/harness.ts @@ -0,0 +1,204 @@ +/** + * Shared plumbing for the self-host live suite (`pnpm selfhost:live-test`): real frp 0.72.0 + * binaries (checksum-pinned by the same table cloud-init uses), real Caddy in Docker, and + * stub upstreams. Nothing here talks to a SAM deployment or a cloud provider. + */ +import { type ChildProcess, execFileSync, spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { basename, join, resolve } from 'node:path'; + +import { + DEFAULT_FRPC_VERSION, + FRPC_DOWNLOAD_BASE_URL, + FRPC_RELEASES, +} from '../../../packages/cloud-init/src/reverse-tunnel'; + +export const REPO_ROOT = resolve(import.meta.dirname, '../../..'); +/** Gitignored scratch directory (see .tmp/README.md). */ +export const LIVE_TMP = join(REPO_ROOT, '.tmp', 'selfhost-live'); +/** System tools run by absolute path, never resolved through a caller-controlled PATH. */ +const TAR = '/usr/bin/tar'; +const OPENSSL = '/usr/bin/openssl'; + +/** A free loopback TCP port (the kernel picks it; closed before returning). */ +export async function freePort(): Promise { + return await new Promise((done, fail) => { + const server = createServer(); + server.once('error', fail); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + server.close(() => + typeof address === 'object' && address ? done(address.port) : fail(new Error('no port')) + ); + }); + }); +} + +/** Directory holding `frpc` and `frps` for the pinned release, downloaded once and verified. */ +export async function frpBinaries(): Promise<{ frpc: string; frps: string }> { + const arch = process.arch === 'arm64' ? 'arm64' : 'amd64'; + const release = FRPC_RELEASES[DEFAULT_FRPC_VERSION]; + if (!release) throw new Error(`no pinned checksum for frp ${DEFAULT_FRPC_VERSION}`); + const name = `frp_${DEFAULT_FRPC_VERSION}_linux_${arch}`; + const dir = join(LIVE_TMP, name); + const bin = { frpc: join(dir, name, 'frpc'), frps: join(dir, name, 'frps') }; + if (existsSync(bin.frpc) && existsSync(bin.frps)) return bin; + mkdirSync(dir, { recursive: true }); + const response = await fetch(`${FRPC_DOWNLOAD_BASE_URL}/v${DEFAULT_FRPC_VERSION}/${name}.tar.gz`); + if (!response.ok) throw new Error(`frp download failed: HTTP ${response.status}`); + const tarball = Buffer.from(await response.arrayBuffer()); + const digest = createHash('sha256').update(tarball).digest('hex'); + if (digest !== release[arch]) throw new Error(`frp ${name} checksum mismatch: ${digest}`); + const archive = join(dir, `${name}.tar.gz`); + writeFileSync(archive, tarball); + execFileSync(TAR, ['-xzf', archive, '-C', dir]); + return bin; +} + +export interface Running { + child: ChildProcess; + output: () => string; + stop: () => Promise; +} + +/** Start a process, capturing combined output for assertions and failure messages. */ +export function start(command: string, args: string[], env: NodeJS.ProcessEnv = {}): Running { + const child = spawn(command, args, { env: { ...process.env, ...env } }); + let output = ''; + child.stdout?.on('data', (chunk: Buffer) => (output += chunk.toString())); + child.stderr?.on('data', (chunk: Buffer) => (output += chunk.toString())); + return { + child, + output: () => output, + stop: async () => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = new Promise((done) => child.once('exit', () => done())); + child.kill('SIGTERM'); + await Promise.race([exited, sleep(5000).then(() => child.kill('SIGKILL'))]); + }, + }; +} + +const CADDY_IMAGE = 'sam-selfhost-caddy:live-test'; +let caddyBuilt = false; + +/** + * The box's Caddy image, built from deploy/selfhost/caddy/Dockerfile exactly as + * `docker compose build caddy` builds it (digest-pinned bases, version-pinned modules, including + * the rate-limit module sam.d/frp.caddy needs). Built once per test file; Docker's layer cache + * makes later builds instant. + */ +export function caddyImage(): string { + if (!caddyBuilt) { + execFileSync( + 'docker', + ['build', '-q', '-t', CADDY_IMAGE, join(REPO_ROOT, 'deploy/selfhost/caddy')], + { + stdio: 'pipe', + } + ); + caddyBuilt = true; + } + return CADDY_IMAGE; +} + +/** Lease range for live Caddy runs: below the kernel's ephemeral range, so freePort never hits it. */ +export const LIVE_TUNNEL_RANGE = { start: 20000, end: 20099 }; + +/** + * Every setting caddy/start.sh checks, on free ports: each box port docker-compose.yml passes + * and the lease range from gateway.env. Callers override what their test probes. + */ +export async function caddyBoxEnv(): Promise> { + const env: Record = { + REVERSE_TUNNEL_PORT_RANGE_START: String(LIVE_TUNNEL_RANGE.start), + REVERSE_TUNNEL_PORT_RANGE_END: String(LIVE_TUNNEL_RANGE.end), + }; + for (const name of [ + 'HTTP_PORT', + 'HTTPS_PORT', + 'CELLD_PORT', + 'CELLD_INTERNAL_PORT', + 'FRPS_BIND_PORT', + 'OBJECTSTORE_PORT', + 'OBJECTSTORE_CONSOLE_PORT', + 'MAIL_COLLECTOR_SMTP_PORT', + 'MAIL_COLLECTOR_UI_PORT', + ]) { + env[name] = String(await freePort()); + } + return env; +} + +export const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); + +/** Poll until `check` is truthy or the deadline passes. */ +export async function waitFor( + what: string, + check: () => T | Promise, + timeoutMs = 30_000, + context: () => string = () => '' +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = await check(); + if (value) return value; + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}\n${context()}`); + await sleep(200); + } +} + +/** A private CA plus a leaf for `host`, created with the system openssl. */ +export function makeCertificate( + dir: string, + host: string +): { ca: string; cert: string; key: string } { + mkdirSync(dir, { recursive: true }); + const ca = join(dir, 'ca.pem'); + const caKey = join(dir, 'ca.key'); + const key = join(dir, 'leaf.key'); + const csr = join(dir, 'leaf.csr'); + const cert = join(dir, 'leaf.pem'); + const ext = join(dir, 'leaf.ext'); + const run = (...args: string[]) => execFileSync(OPENSSL, args, { stdio: 'pipe' }); + run( + 'req', + '-x509', + '-newkey', + 'rsa:2048', + '-nodes', + '-days', + '2', + '-subj', + `/CN=Live Test CA ${basename(dir)}`, + '-keyout', + caKey, + '-out', + ca + ); + run('req', '-newkey', 'rsa:2048', '-nodes', '-subj', `/CN=${host}`, '-keyout', key, '-out', csr); + writeFileSync( + ext, + `subjectAltName=DNS:${host}\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n` + ); + run( + 'x509', + '-req', + '-in', + csr, + '-CA', + ca, + '-CAkey', + caKey, + '-CAcreateserial', + '-days', + '2', + '-extfile', + ext, + '-out', + cert + ); + return { ca: readFileSync(ca, 'utf8'), cert, key }; +} diff --git a/scripts/selfhost/live/mail-collector.live.test.ts b/scripts/selfhost/live/mail-collector.live.test.ts new file mode 100644 index 0000000000..47ea820db8 --- /dev/null +++ b/scripts/selfhost/live/mail-collector.live.test.ts @@ -0,0 +1,349 @@ +/** + * Live: the mail collector's Caddy route (deploy/selfhost/caddy/mail-collector/, start.sh) on the + * box's Caddy image (built from caddy/Dockerfile), started through start.sh exactly as docker-compose.yml starts it, in front + * of stub upstreams that record what reaches them. + * + * Checked: the collector UI refuses requests without the generated password and never forwards + * them; the right password reaches it; Caddy's process environment holds only the hash; with the + * collector off the host is not routed to it; with the collector on and no password Caddy refuses + * to start. + */ +import { execFileSync, spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { connect } from 'node:net'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; + +import { caddyBoxEnv, caddyImage, freePort, REPO_ROOT, waitFor } from './harness'; + +const DOMAIN = 'sam.test'; +const CADDY_DIR = `${REPO_ROOT}/deploy/selfhost/caddy`; +const PASSWORD = randomBytes(32).toString('hex'); +const USER = 'collector'; + +interface Stack { + container: string; + https: number; + logs: () => string; +} + +const collectorHits: string[] = []; +const celldHits: string[] = []; +let collector: Server; +let celld: Server; +let collectorPort = 0; +let celldPort = 0; +const stacks: Stack[] = []; + +function dockerArgs(name: string, env: Record): string[] { + return [ + 'run', + '-d', + '--name', + name, + '--network', + 'host', + '-v', + `${CADDY_DIR}:/etc/caddy:ro`, + '--cap-drop', + 'ALL', + '--cap-add', + 'NET_BIND_SERVICE', + '--entrypoint', + '/bin/sh', + ...Object.entries(env).flatMap(([key, value]) => ['-e', `${key}=${value}`]), + caddyImage(), + '/etc/caddy/start.sh', + ]; +} + +async function startCaddy(extra: Record): Promise { + const https = await freePort(); + const container = `sam-live-mail-${randomBytes(4).toString('hex')}`; + execFileSync( + 'docker', + dockerArgs(container, { + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + HTTPS_PORT: String(https), + CELLD_PORT: String(celldPort), + REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), + ...extra, + }) + ); + const logs = () => spawnSync('docker', ['logs', container], { encoding: 'utf8' }).stderr ?? ''; + const stack = { container, https, logs }; + stacks.push(stack); + await waitFor( + 'Caddy to serve TLS', + async () => { + try { + return (await get(stack, `app.${DOMAIN}`)).status === 200; + } catch { + return false; + } + }, + 120_000, + logs + ); + return stack; +} + +function get(stack: Stack, host: string, auth?: string): Promise<{ status: number; body: string }> { + return new Promise((done, fail) => { + const req = httpsRequest({ + host: '127.0.0.1', + port: stack.https, + servername: host, + rejectUnauthorized: false, + path: '/api/v1/messages', + headers: { Host: host, ...(auth ? { Authorization: auth } : {}) }, + }); + req.on('response', (res) => { + let body = ''; + res.on('data', (chunk: Buffer) => (body += chunk.toString())); + res.on('end', () => done({ status: res.statusCode ?? 0, body })); + }); + req.on('error', fail); + req.end(); + }); +} + +const basic = (user: string, password: string) => + `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`; + +const ON = { + SAM_MAIL_COLLECTOR: 'on', + MAIL_COLLECTOR_HOST_LABEL: 'mail', + MAIL_COLLECTOR_UI_USER: USER, + MAIL_COLLECTOR_UI_PASSWORD: PASSWORD, +}; + +beforeAll(async () => { + collectorPort = await freePort(); + celldPort = await freePort(); + collector = createServer((req, res) => { + collectorHits.push(req.url ?? ''); + res.end('collector'); + }); + celld = createServer((req, res) => { + celldHits.push(`${req.headers.host ?? ''}${req.url ?? ''}`); + res.end('celld'); + }); + await new Promise((done) => collector.listen(collectorPort, '127.0.0.1', done)); + await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); +}); + +afterAll(async () => { + for (const stack of stacks) spawnSync('docker', ['rm', '-f', stack.container]); + await new Promise((done) => collector.close(() => done())); + await new Promise((done) => celld.close(() => done())); +}); + +describe('mail collector route, collector on', () => { + let stack: Stack; + beforeAll(async () => { + stack = await startCaddy({ ...ON, MAIL_COLLECTOR_UI_PORT: String(collectorPort) }); + }); + + it('refuses requests without the password and never forwards them', async () => { + collectorHits.length = 0; + for (const auth of [undefined, basic(USER, 'wrong'), basic('admin', PASSWORD), 'Bearer x']) { + expect((await get(stack, `mail.${DOMAIN}`, auth)).status).toBe(401); + } + expect(collectorHits).toEqual([]); + }); + + it('control: the generated password reaches the collector UI', async () => { + collectorHits.length = 0; + const reply = await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD)); + expect(reply).toEqual({ status: 200, body: 'collector' }); + expect(collectorHits).toEqual(['/api/v1/messages']); + }); + + it('keeps the plaintext password out of the running Caddy process', () => { + const environ = execFileSync('docker', ['exec', stack.container, 'cat', '/proc/1/environ'], { + encoding: 'utf8', + }); + expect(environ).not.toContain(PASSWORD); + expect(environ).toMatch(/MAIL_COLLECTOR_UI_HASH=\$2a\$/); + }); + + it('control: other SAM hosts still go to celld', async () => { + expect((await get(stack, `app.${DOMAIN}`)).body).toBe('celld'); + }); +}); + +describe('mail collector route, collector off', () => { + it('does not route the mail host to the collector', async () => { + const stack = await startCaddy({ + SAM_MAIL_COLLECTOR: 'off', + MAIL_COLLECTOR_UI_PORT: String(collectorPort), + }); + collectorHits.length = 0; + celldHits.length = 0; + expect((await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD))).body).toBe('celld'); + expect(collectorHits).toEqual([]); + expect(celldHits).toEqual([`mail.${DOMAIN}/api/v1/messages`]); + }); +}); + +describe('mail collector on without its password', () => { + it.each([ + ['no password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: '' }], + ['a short password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: 'hunter2' }], + ['an unknown switch value', { ...ON, SAM_MAIL_COLLECTOR: 'yes' }], + ])('refuses to start Caddy with %s', async (_, env) => { + const name = `sam-live-mail-${randomBytes(4).toString('hex')}`; + stacks.push({ container: name, https: 0, logs: () => '' }); + execFileSync( + 'docker', + dockerArgs(name, { + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), + ...env, + }) + ); + const exit = await waitFor('Caddy to exit', () => { + const state = spawnSync( + 'docker', + ['inspect', '-f', '{{.State.Status}} {{.State.ExitCode}}', name], + { + encoding: 'utf8', + } + ).stdout.trim(); + return state.startsWith('exited') ? state : ''; + }); + expect(exit).toBe('exited 64'); + }); +}); + +/** The mail-collector service exactly as docker-compose.yml defines it, on free ports. */ +function collectorService(smtpPort: number, uiPort: number): { image: string; command: string[] } { + const compose = parse( + readFileSync(`${REPO_ROOT}/deploy/selfhost/docker-compose.yml`, 'utf8') + ) as { + services: Record; + }; + const service = compose.services['mail-collector']!; + const command = service.command.map((arg) => + arg + .replace('${MAIL_COLLECTOR_SMTP_PORT:-1025}', String(smtpPort)) + .replace('${MAIL_COLLECTOR_UI_PORT:-8025}', String(uiPort)) + ); + return { image: service.image, command }; +} + +/** One plaintext SMTP exchange, the way the Worker talks to the collector (SMTP_TLS=none). */ +function sendPlainSmtp(port: number, to: string, subject: string): Promise { + const script = [ + 'EHLO api.sam.test', + 'MAIL FROM:', + `RCPT TO:<${to}>`, + 'DATA', + `From: sign-in@sam.test\r\nTo: ${to}\r\nSubject: ${subject}\r\n\r\nYour code is 123456\r\n.`, + 'QUIT', + ]; + return new Promise((done, fail) => { + const replies: string[] = []; + const socket = connect(port, '127.0.0.1'); + let buffer = ''; + socket.on('data', (chunk: Buffer) => { + buffer += chunk.toString(); + const lines = buffer.split('\r\n'); + buffer = lines.pop() ?? ''; + for (const line of lines) { + if (!/^\d{3} /.test(line)) continue; + replies.push(line.slice(0, 3)); + const next = script.shift(); + if (next) socket.write(`${next}\r\n`); + } + }); + socket.on('close', () => done(replies)); + socket.on('error', fail); + }); +} + +describe('the real collector (Mailpit) as compose runs it', () => { + const password = randomBytes(32).toString('hex'); + let smtpPort = 0; + let uiPort = 0; + const name = `sam-live-mailpit-${randomBytes(4).toString('hex')}`; + + beforeAll(async () => { + smtpPort = await freePort(); + uiPort = await freePort(); + const { image, command } = collectorService(smtpPort, uiPort); + stacks.push({ container: name, https: 0, logs: () => '' }); + execFileSync('docker', [ + 'run', + '-d', + '--name', + name, + '--network', + 'host', + '--user', + '65534:65534', + '--read-only', + '--tmpfs', + '/tmp', + '--cap-drop', + 'ALL', + '-e', + `MP_UI_AUTH=${USER}:${password}`, + image, + ...command, + ]); + await waitFor('Mailpit to listen', async () => { + try { + return (await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`)).status === 401; + } catch { + return false; + } + }); + }); + + it('accepts plaintext SMTP on loopback and shows the message to the password only', async () => { + expect(await sendPlainSmtp(smtpPort, 'owner@example.com', 'live code')).toEqual([ + '220', + '250', + '250', + '250', + '354', + '250', + '221', + ]); + const unauthenticated = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`); + expect(unauthenticated.status).toBe(401); + const wrong = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { + headers: { Authorization: basic(USER, 'wrong') }, + }); + expect(wrong.status).toBe(401); + const list = (await ( + await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { + headers: { Authorization: basic(USER, password) }, + }) + ).json()) as { messages: Array<{ Subject: string; To: Array<{ Address: string }> }> }; + expect(list.messages).toEqual([ + expect.objectContaining({ + Subject: 'live code', + To: [expect.objectContaining({ Address: 'owner@example.com' })], + }), + ]); + }); + + it('refuses the send API without the password too', async () => { + const res = await fetch(`http://127.0.0.1:${uiPort}/api/v1/send`, { + method: 'POST', + body: '{}', + }); + expect(res.status).toBe(401); + }); +}); diff --git a/scripts/selfhost/live/shared-flight-cancel.live.test.ts b/scripts/selfhost/live/shared-flight-cancel.live.test.ts new file mode 100644 index 0000000000..df1655644a --- /dev/null +++ b/scripts/selfhost/live/shared-flight-cancel.live.test.ts @@ -0,0 +1,399 @@ +/** + * The one-minute hangs on the celld box (task H2): an aborted request must not poison its isolate. + * + * celld 0.6.3 gives every async op (fetch, setTimeout, AbortSignal.timeout) to the request that + * started it, and drops the op when that request's client disconnects (runtime.rs: the cancel + * path clears the request's pending ops and deletes their resolvers). A promise one request + * starts and later requests join therefore never settles once the first client goes away, and + * every joiner hangs until its own client gives up or the 300 s handler budget runs out. + * + * Runs on the real runtime: celld 0.6.3 (pinned) over the pinned object store, with a loopback + * server behind a proxy that holds each connection for a moment (a slow dependency, as on a + * loaded box). The per-isolate reads every request's auth/config path joins (the admin settings + * cache, the legacy platform-config read resolvePlatformConfig reaches for example from every MCP + * tool listing) are started by a request whose client then gives up; the joiners may wait out the + * dropped read's deadline plus the join grace, then read for themselves + * (packages/worker-core/src/shared-flight.ts). Every other kind of join the API makes is driven + * through its real code below. + */ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { createServer as createHttpServer } from 'node:http'; +import { connect, createServer, type Server } from 'node:net'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS } from '../../../apps/api/src/lib/shared-flight'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from '../../../apps/api/src/services/config-read-deadline'; +import { ensureCelldBinary } from '../celld-binary.js'; +import { + celldNode, + hasDocker, + type ObjectStore, + startObjectStore, + writeProject, +} from './celld-lab'; +import { freePort, LIVE_TMP, REPO_ROOT, type Running, sleep, waitFor } from './harness'; + +const SETTINGS_CACHE = join(REPO_ROOT, 'apps/api/src/services/admin-settings-cache.ts'); +const SHARED_FLIGHT = join(REPO_ROOT, 'apps/api/src/lib/shared-flight.ts'); +const PLATFORM_CONFIG = join(REPO_ROOT, 'apps/api/src/services/platform-config.ts'); +const SETTINGS_RESOLUTION = join(REPO_ROOT, 'apps/api/src/services/admin-settings-resolution.ts'); +// Moved into the ProjectData package by the worker split (#2681); both import worker-core's +// shared-flight, the same module instance the apps/api shim re-exports. +const ENSURE_MEMO = join(REPO_ROOT, 'packages/project-data/src/client/project-data-ensure-memo.ts'); +const COMPACT_R2 = join(REPO_ROOT, 'packages/project-data/src/archive/compact-r2.ts'); +/** The settings flight's own deadline in the probe: longer than one slow read. */ +const SETTINGS_READ_TIMEOUT_MS = 3000; +/** The legacy platform-config read's deadline: performance.configReadTimeoutMs at its default. */ +const PLATFORM_CONFIG_READ_TIMEOUT_MS = DEFAULT_CONFIG_READ_TIMEOUT_MS; +const JOIN_GRACE_MS = DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS; +/** How long the proxy holds each connection: wide enough to abort the first request in. */ +const SLOW_DELAY_MS = 1500; +/** The first client gives up while its shared read is still in flight. */ +const ABORT_AFTER_MS = 400; +/** Past two 30 s pool ticks, so the next request builds a fresh isolate with empty caches. */ +const IDLE_FOR_FRESH_ISOLATE_MS = 65_000; +/** A healthy answer takes ~SLOW_DELAY_MS; a poisoned isolate holds a request until this cap. */ +const CLIENT_CAP_MS = 15_000; + +// `/settings` reads through the real AdminSettingsCache (the shared per-isolate flight every +// request's auth path joins), with a loader that waits on the slow proxy like a slow D1 read. +// `/platform-config` runs the real resolvePlatformConfig over a stand-in D1 whose settings reads +// answer at once and whose five legacy platform-config reads wait on the slow proxy, so an +// aborted first request is mid legacy read when its client leaves. +const WORKER = ` +import { AdminSettingsCache } from ${JSON.stringify(SETTINGS_CACHE)}; +import { resumeSharedFlightJoinsOnOwnTimer, settleSharedFlight } from ${JSON.stringify(SHARED_FLIGHT)}; +import { resolvePlatformConfig } from ${JSON.stringify(PLATFORM_CONFIG)}; +import { resolveAdminSetting } from ${JSON.stringify(SETTINGS_RESOLUTION)}; +import { ensureOncePerIsolate } from ${JSON.stringify(ENSURE_MEMO)}; +import { writeImmutableJson } from ${JSON.stringify(COMPACT_R2)}; +// What the generated celld entry does at startup (scripts/selfhost/celld-project.ts). +resumeSharedFlightJoinsOnOwnTimer(); +const DB = {}; +const isolate = crypto.randomUUID().slice(0, 8); +let settings; +let slowUrl = ''; +let delayUrl = ''; +/** One slow read: the proxied server (slow per connection) or the delay server (slow per request). */ +const slowRead = async (url) => void (await (await fetch(url)).arrayBuffer()); +const LEGACY_READ = /WHERE key = \\?|AS encryptedToken/; +/** A stand-in D1 whose statements matching \`slow\` wait on a slow read (a slow D1 read). */ +function stubDb(slow, onSlow = () => undefined, url = () => slowUrl) { + const statement = (sql) => { + const wait = async () => { + if (!slow.test(sql)) return; + onSlow(); + await slowRead(url()); + }; + const api = { + bind: () => api, + first: async () => { await wait(); return null; }, + all: async () => { await wait(); return { results: [], success: true, meta: {} }; }, + run: async () => { await wait(); return { success: true, meta: {} }; }, + raw: async () => { await wait(); return []; }, + }; + return api; + }; + return { prepare: statement, batch: async () => [] }; +} +const CONFIG_DB = stubDb(LEGACY_READ); +// The join cases below: one stand-in per kind, so each joins a flight of its own. Their slow reads +// go to the delay server, which holds EVERY request (the proxy holds only new connections, +// so a pooled connection would make a "slow" read instant and the second request start its own). +const loads = { settings: 0, platform: 0, credentials: 0, kv: 0, ensure: 0, r2: 0 }; +const count = (kind) => () => loads[kind]++; +const delayed = () => delayUrl; +let ioSettings; +const IO_PLATFORM_DB = stubDb(LEGACY_READ, count('platform'), delayed); +const IO_CREDENTIALS_DB = stubDb(/FROM platform_credentials/, count('credentials'), delayed); +const IO_KV_DB = stubDb(/^$/); +const IO_KV = { get: async () => { loads.kv++; await slowRead(delayUrl); return null; } }; +// A stand-in R2 bucket whose PUT is a slow provider write. +const r2Objects = new Map(); +const IO_R2 = { + head: async (key) => { + const stored = r2Objects.get(key); + return stored ? { size: stored.size, customMetadata: stored.customMetadata } : null; + }, + put: async (key, bytes, options) => { + loads.r2++; + await slowRead(delayUrl); + r2Objects.set(key, { size: bytes.byteLength, customMetadata: options.customMetadata }); + return {}; + }, + get: async () => null, +}; +/** Each kind: the real shared read, as a request reaches it. */ +const JOINS = { + settings: () => { + ioSettings ??= new AdminSettingsCache(60_000, Date.now, async () => { + loads.settings++; + await slowRead(delayUrl); + return []; + }); + return ioSettings.read(DB, false, 60_000, ${SETTINGS_READ_TIMEOUT_MS}); + }, + platform: () => resolvePlatformConfig({ DATABASE: IO_PLATFORM_DB, GITHUB_APP_SLUG: 'live-app' }), + credentials: () => + resolveAdminSetting({ DATABASE: IO_CREDENTIALS_DB }, 'integration.github.clientSecret'), + kv: () => resolveAdminSetting({ DATABASE: IO_KV_DB, KV: IO_KV }, 'operations.cronSweepsEnabled'), + ensure: () => + ensureOncePerIsolate({}, 'live-join-probe', async () => { + loads.ensure++; + await slowRead(delayUrl); + }), + // The archive cron's immutable write: B's HEAD waits on A's PUT, then HEADs again. + r2: () => writeImmutableJson(IO_R2, 'live-join-probe.json', { ok: true }, 10_000), +}; +/** The request's own I/O after the join: what every auth path does next (D1, fetch, timer). */ +async function ownIo(env) { + await (await fetch(env.FAST_URL)).arrayBuffer(); + await new Promise((resume) => setTimeout(resume, 50)); +} +class Probe { + constructor(_ctx, env) { + this.env = env; + this.joinLoads = 0; + this.cleanupInFlight = null; + } + async fetch(request) { + if (new URL(request.url).pathname !== '/join') return Response.json({ ok: true }); + // A Durable Object field joined by a second request, as CredentialSetupSession's alarm joins + // an inline cleanup another request started (resumeCleanup). + const inline = this.cleanupInFlight; + if (inline) { + const joined = await settleSharedFlight(inline.promise, inline.startedAt + 5000); + if (joined.abandoned) return Response.json({ abandoned: true }, { status: 500 }); + } else { + this.joinLoads++; + const flight = { + startedAt: Date.now(), + promise: slowRead(this.env.DELAY_URL), + }; + this.cleanupInFlight = flight; + try { + await flight.promise; + } finally { + if (this.cleanupInFlight === flight) this.cleanupInFlight = null; + } + } + await ownIo(this.env); + return Response.json({ isolate, loads: this.joinLoads }); + } +} +export const ProbeDO = Probe; +export default { + async fetch(request, env) { + const url = new URL(request.url); + slowUrl = env.SLOW_URL; + delayUrl = env.DELAY_URL; + if (url.pathname === '/settings') { + settings ??= new AdminSettingsCache(60_000, Date.now, async () => { + await (await fetch(env.SLOW_URL)).arrayBuffer(); + return []; + }); + const rows = await settings.read(DB, false, 60_000, ${SETTINGS_READ_TIMEOUT_MS}); + return Response.json({ rows: rows.length }); + } + if (url.pathname === '/join-io') { + const kind = url.searchParams.get('kind') ?? ''; + if (kind === 'do') { + const stub = env.PROBE_DO.get(env.PROBE_DO.idFromName('live-join-probe')); + return await stub.fetch('https://do/join'); + } + await JOINS[kind](env); + await ownIo(env); + return Response.json({ isolate, loads: loads[kind] }); + } + if (url.pathname === '/platform-config') { + const config = await resolvePlatformConfig({ DATABASE: CONFIG_DB, GITHUB_APP_SLUG: 'live-app' }); + return Response.json({ appSlug: config.github.appSlug.value }); + } + if (url.pathname === '/do') { + const stub = env.PROBE_DO.get(env.PROBE_DO.idFromName(url.searchParams.get('name') ?? 'x')); + return await stub.fetch('https://do/'); + } + return Response.json({ ok: true }); + }, +}; +`; + +let root = ''; +let store: ObjectStore | undefined; +let celld: Running | undefined; +let upstream: ReturnType | undefined; +let proxy: Server | undefined; +let delayServer: ReturnType | undefined; +let celldPort = 0; + +/** A loopback TCP proxy that waits before connecting: a slow dependency. */ +function startDelayProxy(listenPort: number, targetPort: number, delayMs: number): Server { + const server = createServer((client) => { + client.pause(); + const timer = setTimeout(() => { + const upstream = connect(targetPort, '127.0.0.1', () => { + client.pipe(upstream); + upstream.pipe(client); + client.resume(); + }); + upstream.on('error', () => client.destroy()); + client.on('error', () => upstream.destroy()); + }, delayMs); + client.on('close', () => clearTimeout(timer)); + }); + server.listen(listenPort, '127.0.0.1'); + return server; +} + +interface Outcome { + status: number; + ms: number; + body?: unknown; +} + +async function request(path: string, timeoutMs: number): Promise { + const started = Date.now(); + try { + const response = await fetch(`http://127.0.0.1:${celldPort}${path}`, { + signal: AbortSignal.timeout(timeoutMs), + }); + return { status: response.status, ms: Date.now() - started, body: await response.json() }; + } catch { + return { status: 0, ms: Date.now() - started }; + } +} + +/** Abort the first request to a fresh isolate, then require the next two to answer in `bound`. */ +async function expectJoinersAnswer(path: string, bound: number): Promise { + await sleep(IDLE_FOR_FRESH_ISOLATE_MS); + expect((await request(path, ABORT_AFTER_MS)).status).toBe(0); + // The next reads join the dropped flight. They may wait out its deadline plus the join grace, + // then read for themselves: bounded, never the client cap. + const next = await Promise.all([request(path, CLIENT_CAP_MS), request(path, CLIENT_CAP_MS)]); + const report = JSON.stringify(next) + (celld?.output().slice(-3000) ?? ''); + expect( + next.map((o) => o.status), + report + ).toEqual([200, 200]); + for (const outcome of next) expect(outcome.ms, report).toBeLessThan(bound); + return next; +} + +describe.skipIf(!hasDocker && !process.env.CI)('an aborted request does not poison celld', () => { + beforeAll(async () => { + const upstreamPort = await freePort(); + const proxyPort = await freePort(); + const delayPort = await freePort(); + mkdirSync(LIVE_TMP, { recursive: true }); + root = mkdtempSync(join(LIVE_TMP, 'shared-flight-')); + store = await startObjectStore('sam-live-sharedflight', 'live-sharedflight-store-0123456789'); + const project = writeProject(join(root, 'project'), { + name: 'shared-flight-probe', + worker: WORKER, + probeObject: true, + // As the API runs (apps/api/wrangler.toml): the archive code imports node:crypto. + bindings: { compatibility_flags: ['nodejs_compat'] }, + vars: { + // The Worker's slow reads go through the proxy; the proxy talks to the fast server. + SLOW_URL: `http://127.0.0.1:${proxyPort}/healthz`, + FAST_URL: `http://127.0.0.1:${upstreamPort}/healthz`, + DELAY_URL: `http://127.0.0.1:${delayPort}/`, + }, + }); + upstream = createHttpServer((_req, res) => res.end('ok')).listen(upstreamPort, '127.0.0.1'); + await waitFor( + 'the upstream', + async () => (await fetch(`http://127.0.0.1:${upstreamPort}/healthz`).catch(() => null))?.ok + ); + proxy = startDelayProxy(proxyPort, upstreamPort, SLOW_DELAY_MS); + // Holds every request, pooled connection or not: the join cases' slow read. + delayServer = createHttpServer((_req, res) => { + setTimeout(() => res.end('ok'), SLOW_DELAY_MS); + }).listen(delayPort, '127.0.0.1'); + const node = await celldNode(await ensureCelldBinary(join(LIVE_TMP, 'celld-bin')), store); + celldPort = node.port; + celld = await node.serve(project); + }, 300_000); + + afterAll(async () => { + await celld?.stop(); + upstream?.closeAllConnections(); + await new Promise((done) => (upstream ? upstream.close(() => done()) : done())); + await new Promise((done) => (proxy ? proxy.close(() => done()) : done())); + delayServer?.closeAllConnections(); + await new Promise((done) => (delayServer ? delayServer.close(() => done()) : done())); + store?.stop(); + if (root) rmSync(root, { recursive: true, force: true }); + }); + + it('serves settings reads after the request that started the shared read was aborted', async () => { + await expectJoinersAnswer( + '/settings', + SETTINGS_READ_TIMEOUT_MS + JOIN_GRACE_MS + 2 * SLOW_DELAY_MS + 2000 + ); + }, 150_000); + + it('serves platform-config reads after the request that started the shared read was aborted', async () => { + const next = await expectJoinersAnswer( + '/platform-config', + PLATFORM_CONFIG_READ_TIMEOUT_MS + JOIN_GRACE_MS + 2 * SLOW_DELAY_MS + 2000 + ); + for (const outcome of next) expect(outcome.body).toEqual({ appSlug: 'live-app' }); + }, 150_000); + /** + * Every kind of join the API makes, driven through its real code. No client gives up here: B + * joins A's healthy shared read, then makes its own fetch and timer. Without the own-timer + * resume B continues as part of A's request, celld drops B's later ops when A answers, and B + * hangs to the client cap (task R6: authenticated requests after #2706). `loadsPerFlight` is the + * number of slow reads one flight makes; both answers reporting it proves B really joined. + * + * Verified discriminating (task R7): with the startup switch removed, the six stateless kinds + * go red (B hangs to CLIENT_CAP_MS) and the Durable Object kind stays green. On celld 0.6.3 an + * object's ops are not dropped when one of its requests answers, so that case is a control: it + * proves the own-timer join also works inside an object, and that B joined (one load). + */ + it.each([ + { kind: 'settings', site: 'AdminSettingsCache.read (joinSharedFlight)', loadsPerFlight: 1 }, + { kind: 'platform', site: 'resolveLegacyPlatformConfig', loadsPerFlight: 5 }, + { kind: 'credentials', site: 'admin-settings credentialRows', loadsPerFlight: 1 }, + { kind: 'kv', site: 'admin-settings legacyKv', loadsPerFlight: 1 }, + // Main's memo (af302dbd3) remembers only completed ensures: two concurrent cold requests each + // run their own ensure, so there is no join to strand, and each answer reports both loads. + { kind: 'ensure', site: 'ensureOncePerIsolate', loadsPerFlight: 2 }, + { kind: 'r2', site: 'compact-r2 timedR2 (archive cron)', loadsPerFlight: 1 }, + { + kind: 'do', + site: 'Durable Object field (CredentialSetupSession.resumeCleanup)', + loadsPerFlight: 1, + }, + ])( + 'a request that joined $site keeps its own I/O after the starter answers', + async ({ kind, loadsPerFlight }) => { + if (kind === 'do') { + // Warm the object first, so neither request waits on its first activation. + expect((await request('/do?name=live-join-probe', CLIENT_CAP_MS)).status).toBe(200); + } + const path = `/join-io?kind=${kind}`; + const first = request(path, CLIENT_CAP_MS); + await sleep(200); + const second = request(path, CLIENT_CAP_MS); + const both = [await first, await second]; + const report = JSON.stringify(both) + (celld?.output().slice(-3000) ?? ''); + expect( + both.map((o) => o.status), + report + ).toEqual([200, 200]); + // Liveness of the scenario: one isolate and ONE flight, so the second request really joined. + const bodies = both.map((o) => o.body as { isolate: string; loads: number }); + expect(bodies[1]?.isolate, report).toBe(bodies[0]?.isolate); + expect( + bodies.map((b) => b.loads), + report + ).toEqual([loadsPerFlight, loadsPerFlight]); + for (const outcome of both) expect(outcome.ms, report).toBeLessThan(2 * SLOW_DELAY_MS + 2000); + }, + 60_000 + ); +}); diff --git a/scripts/selfhost/live/vitest.config.ts b/scripts/selfhost/live/vitest.config.ts new file mode 100644 index 0000000000..f542c6a214 --- /dev/null +++ b/scripts/selfhost/live/vitest.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from 'vitest/config'; + +/** + * Live self-host suite: real frp and celld binaries (checksum-pinned downloads), the box's Caddy + * image built from deploy/selfhost/caddy/Dockerfile, and digest-pinned Mailpit and MinIO images. + * Run with `pnpm selfhost:live-test`; needs network access (downloads, image pulls, the Caddy + * build) and a Linux Docker daemon that supports `--network host`. No root or nftables. + */ +export default defineConfig({ + test: { + root: import.meta.dirname, + include: ['**/*.live.test.ts'], + testTimeout: 120_000, + hookTimeout: 300_000, + fileParallelism: false, + }, +}); From 2ef8050ed4b6d812c93f22fae7cb89debc08881f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:08:51 +0000 Subject: [PATCH 07/65] docs(selfhost): README describes upgrade retry and box-scoped compose commands The upgrade from PR 2 records an unfinished upgrade in .state/upgrade-pending.json and retries from it, and runs and prints every compose command with the box's .env and selected compose files; the explicit image rebuild (F11) does the same. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 4424b10468..5f40005cc6 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -75,8 +75,16 @@ pnpm selfhost:upgrade --to ``` It refuses a checkout with uncommitted changes, checks the ref out, runs `deploy --init`, rebuilds -only the images whose build inputs changed, restarts the stack only when compose inputs changed, -deploys, checks health and prints how to roll back. +only the images whose build inputs changed (explicitly, with `docker compose build `), +restarts the stack (`up -d`, never `--build`) only when compose inputs changed, deploys, checks +health and prints how to roll back. For a box other than the default, pass `--box-env`, +`--state-dir` and `--secrets`; every deploy and compose command it runs or prints uses that box's +`.env` and every compose file its `COMPOSE_FILE` selects. + +If an upgrade fails, `.state/upgrade-pending.json` records the ref it started from and the printed +output gives both ways out: run the same `selfhost:upgrade --to ` again to retry (it reruns +every step, from the recorded ref, and its rollback still names that ref), or run the printed +rollback commands. The file is removed once an upgrade passes its health check. **It takes no backup.** Copy the fleet bucket and `deploy/selfhost/.state` yourself first. An upgrade that carries a D1 migration cannot be rolled back by redeploying the old ref; only your From 8549ccbcd41a17a8ec48c2b4db092e3915d68be5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:14:29 +0000 Subject: [PATCH 08/65] style(quality): drop useless quote escapes in dependency-governance test ESLint no-useless-escape: \' inside a template literal is just '. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- scripts/quality/dependency-governance.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/quality/dependency-governance.test.ts b/scripts/quality/dependency-governance.test.ts index a2bcaf5603..164de45648 100644 --- a/scripts/quality/dependency-governance.test.ts +++ b/scripts/quality/dependency-governance.test.ts @@ -44,7 +44,7 @@ function npmGlobalInstallSpecs(files: string[], packageName: string): string[] { const specs: string[] = []; const escapedPackageName = packageName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const installPattern = new RegExp( - `npm\\s+install(?:\\s+-{1,2}[^\\s"\']+)*\\s+["\']?(${escapedPackageName}(?:@[^\\s"\']+)?)`, + `npm\\s+install(?:\\s+-{1,2}[^\\s"']+)*\\s+["']?(${escapedPackageName}(?:@[^\\s"']+)?)`, 'g' ); From 943d36a4792653cd58d1a916f3105c78da0b3e9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:29:27 +0000 Subject: [PATCH 09/65] ci(selfhost): run box static tests on deploy/selfhost changes; route redaction guards run with route changes deploy-scripts now selects deploy/selfhost/**, so compose, Caddy and gcp-bootstrap changes run the static tests that read them. The credential-route scan moves out of scripts/selfhost: the API half into an API unit test, the App.tsx half into a web unit test, so each runs with the suite CI already selects for those routes (App.tsx in the API unit filter would have started the API suite on every web routing change). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 ++ .../caddy-log-redaction-routes.test.ts | 76 +++++++++++++++++++ .../selfhost-log-redaction-routes.test.ts | 42 ++++++++++ deploy/selfhost/caddy/log-redaction.caddy | 4 +- scripts/quality/ci-suite-selection.test.ts | 24 ++++++ .../selfhost/caddy-logging-compose.test.ts | 65 ++-------------- 6 files changed, 158 insertions(+), 60 deletions(-) create mode 100644 apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts create mode 100644 apps/web/tests/unit/selfhost-log-redaction-routes.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cdf93e7859..39c8ee9151 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -152,6 +152,8 @@ jobs: - 'scripts/selfhost/selfhost-migrations.ts' # selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only). - 'deploy/selfhost/sam-mx/**' + # The self-host access-log redaction guard scans the API routes against this filter. + - 'deploy/selfhost/caddy/log-redaction.caddy' - 'scripts/quality/node-pool-boundary.ts' - 'scripts/quality/node-pool-boundary/**' - 'tests/fixtures/acp-activity-report-v1.json' @@ -166,6 +168,8 @@ jobs: - 'packages/terminal/**' - 'packages/ui/**' - 'tests/fixtures/diagnostic-secret-canaries.json' + # The self-host access-log redaction guard scans App.tsx against this filter. + - 'deploy/selfhost/caddy/log-redaction.caddy' # Storybook (packages/ui) and the public site (apps/www, which depends on ui). public-site: - *workspace-root @@ -253,6 +257,9 @@ jobs: - 'scripts/deploy/**' # Self-hosted (celld) packaging: config generator, deploy, upgrade, create-account. - 'scripts/selfhost/**' + # The box files its static tests read: compose, Caddy fragments and start.sh, frps.toml, + # gcp-bootstrap.sh, .env.example. + - 'deploy/selfhost/**' # ...and what its tests read outside it: the self-host migration projection and the # SMTP settings parser. - 'apps/api/src/selfhost/**' diff --git a/apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts b/apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts new file mode 100644 index 0000000000..27b7135e3d --- /dev/null +++ b/apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts @@ -0,0 +1,76 @@ +/** + * The self-host box's Caddy access log (deploy/selfhost/caddy/log-redaction.caddy) replaces a + * credential that a route carries in its path. This scans the API routes for path parameters named + * like a credential, so a new one fails here until the redaction filter and this list cover it. + * + * It lives with the API unit tests, not with the self-host packaging tests, so that it runs when a + * route changes. The web app's routes have the same guard in + * apps/web/tests/unit/selfhost-log-redaction-routes.test.ts (the web suite runs on App.tsx + * changes). The redaction itself is proven against the real Caddy image in + * scripts/selfhost/live/access-log-keep-warm.live.test.ts. + */ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +const REPO = resolve(import.meta.dirname, '../../../../..'); +const ROUTES_DIR = resolve(import.meta.dirname, '../../../src/routes'); +const REDACTION = resolve( + import.meta.dirname, + '../../../../../deploy/selfhost/caddy/log-redaction.caddy' +); + +/** Route-definition strings with a path parameter named like a credential. */ +const CREDENTIAL_ROUTE = + /(?:\.(?:get|post|put|patch|delete|all|on)\(|path=)\s*['"`]([^'"`]*\/:(?:[a-z]*token|sig|signature|secret|key|code|jwt|nonce)\b[^'"`]*)['"`]/gi; + +/** Each known credential route and the logged path prefix the redaction filter rewrites. */ +const KNOWN_CREDENTIAL_ROUTES: Record = { + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages': '/ai/proxy/', + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages/count_tokens': + '/ai/proxy/', + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/openai/v1/chat/completions': '/ai/proxy/', + 'apps/api/src/routes/bootstrap.ts /:token': '/api/bootstrap/', + 'apps/api/src/routes/projects/members.ts /invite-links/:token': '/api/projects/invite-links/', + 'apps/api/src/routes/projects/members.ts /invite-links/:token/request': + '/api/projects/invite-links/', +}; + +function routeFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return routeFiles(path); + return path.endsWith('.ts') && !path.endsWith('.test.ts') ? [path] : []; + }); +} + +/** The path prefixes the filter's `regexp "^(||...)[^/?]*"` rule rewrites. */ +function redactedPrefixes(): string[] { + const rule = /regexp "\^\(([^)"]+)\)\[\^\/\?\]\*" "\$\{1\}"/.exec( + readFileSync(REDACTION, 'utf8') + ); + return rule?.[1]?.split('|') ?? []; +} + +describe('self-host access log: path credentials', () => { + it('every route with a credential in its path is on the redaction list', () => { + const found = routeFiles(ROUTES_DIR) + .flatMap((file) => + [...readFileSync(file, 'utf8').matchAll(CREDENTIAL_ROUTE)].map( + (m) => `${relative(REPO, file)} ${m[1]}` + ) + ) + .sort(); + expect(found.length).toBeGreaterThanOrEqual(6); // the scan itself works + expect(found).toEqual(Object.keys(KNOWN_CREDENTIAL_ROUTES).sort()); + }); + + it('log-redaction.caddy rewrites the prefix each of those routes is served under', () => { + const prefixes = redactedPrefixes(); + expect(prefixes.length).toBeGreaterThan(0); // the rule was found + for (const prefix of Object.values(KNOWN_CREDENTIAL_ROUTES)) { + expect(prefixes).toContain(prefix); + } + }); +}); diff --git a/apps/web/tests/unit/selfhost-log-redaction-routes.test.ts b/apps/web/tests/unit/selfhost-log-redaction-routes.test.ts new file mode 100644 index 0000000000..762e8b9b1d --- /dev/null +++ b/apps/web/tests/unit/selfhost-log-redaction-routes.test.ts @@ -0,0 +1,42 @@ +/** + * The self-host box's Caddy access log (deploy/selfhost/caddy/log-redaction.caddy) replaces a + * credential that a route carries in its path. This scans the app's client routes (App.tsx: the + * box serves the app's HTML document for them, so they reach the access log) for path parameters + * named like a credential, so a new one fails here until the redaction filter and this list cover + * it. The API routes have the same guard in + * apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +const APP = resolve(__dirname, '../../src/App.tsx'); +const REDACTION = resolve(__dirname, '../../../../deploy/selfhost/caddy/log-redaction.caddy'); + +/** `` values with a path parameter named like a credential. */ +const CREDENTIAL_ROUTE = + /path=\s*['"`]([^'"`]*\/:(?:[a-z]*token|sig|signature|secret|key|code|jwt|nonce)\b[^'"`]*)['"`]/gi; + +/** Each known credential route and the logged path prefix the redaction filter rewrites. */ +const KNOWN_CREDENTIAL_ROUTES: Record = { + '/projects/invite/:token': '/projects/invite/', +}; + +describe('self-host access log: path credentials in app routes', () => { + it('every app route with a credential in its path is on the redaction list', () => { + const found = [...readFileSync(APP, 'utf8').matchAll(CREDENTIAL_ROUTE)].map((m) => m[1]); + expect(found.sort()).toEqual(Object.keys(KNOWN_CREDENTIAL_ROUTES).sort()); + }); + + it('log-redaction.caddy rewrites the prefix each of those routes is served under', () => { + const rule = /regexp "\^\(([^)"]+)\)\[\^\/\?\]\*" "\$\{1\}"/.exec( + readFileSync(REDACTION, 'utf8') + ); + const prefixes = rule?.[1]?.split('|') ?? []; + expect(prefixes.length).toBeGreaterThan(0); // the rule was found + for (const prefix of Object.values(KNOWN_CREDENTIAL_ROUTES)) { + expect(prefixes).toContain(prefix); + } + }); +}); diff --git a/deploy/selfhost/caddy/log-redaction.caddy b/deploy/selfhost/caddy/log-redaction.caddy index a21298f1e9..116f3cd126 100644 --- a/deploy/selfhost/caddy/log-redaction.caddy +++ b/deploy/selfhost/caddy/log-redaction.caddy @@ -7,7 +7,9 @@ # deleting the header maps outright also covers every other header, including ones forward_auth # copies onto the request. `headers` is where reverse_proxy's debug entries put response headers. # -# Credentials in paths (keep in sync with the routes; scripts/selfhost/caddy-logging-compose.test.ts): +# Credentials in paths. Keep in sync with the routes, which these tests scan: +# apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts (API routes) and +# apps/web/tests/unit/selfhost-log-redaction-routes.test.ts (App.tsx). # /ai/proxy//... apps/api/src/routes/ai-proxy-passthrough.ts # /api/bootstrap/ apps/api/src/routes/bootstrap.ts # /api/projects/invite-links/ apps/api/src/routes/projects/members.ts diff --git a/scripts/quality/ci-suite-selection.test.ts b/scripts/quality/ci-suite-selection.test.ts index 67da4ec98b..6ee39f8147 100644 --- a/scripts/quality/ci-suite-selection.test.ts +++ b/scripts/quality/ci-suite-selection.test.ts @@ -698,6 +698,30 @@ describe('runner budget (jobs a ready PR starts)', () => { } }); + it('a box file alone starts Validate Deploy Scripts, whose static tests read deploy/selfhost', () => { + const jobs = (paths: string[]) => + simulate({ eventName: 'pull_request', filters: filtersFor(paths) }); + for (const path of [ + 'deploy/selfhost/caddy/start.sh', + 'deploy/selfhost/docker-compose.yml', + 'deploy/selfhost/gcp-bootstrap.sh', + ]) { + expect(jobs([path]).get('deploy-scripts'), path).toBe('success'); + } + // Control: a change outside the deploy inputs does not start it. + expect(jobs(['apps/web/src/main.tsx']).get('deploy-scripts')).not.toBe('success'); + }); + + // The access-log redaction guards: the API one runs with the API unit suite, the App.tsx one + // with the web suite, and either runs when the redaction filter itself changes. + it('a credential route or the redaction filter selects the suite holding its guard', () => { + expect(suitesFor(['apps/api/src/routes/bootstrap.ts'])).toContain('test-api'); + expect(suitesFor(['apps/web/src/App.tsx'])).toContain('test-web'); + expect(suitesFor(['deploy/selfhost/caddy/log-redaction.caddy'])).toEqual( + expect.arrayContaining(['test-api', 'test-web']) + ); + }); + it('a draft PR starts 6 jobs', () => { const results = simulate({ eventName: 'pull_request', draft: true, filters: allFilters() }); expect(started(results)).toHaveLength(6); diff --git a/scripts/selfhost/caddy-logging-compose.test.ts b/scripts/selfhost/caddy-logging-compose.test.ts index 58ff47c9b3..6b744f4a4b 100644 --- a/scripts/selfhost/caddy-logging-compose.test.ts +++ b/scripts/selfhost/caddy-logging-compose.test.ts @@ -2,10 +2,12 @@ * Static wiring for Caddy's access log and the keep-warm health check (the behaviour itself is * proven against the real Caddy image in live/access-log-keep-warm.live.test.ts): compose passes * the keep-warm settings with their defaults and caps the Caddy log on disk, and both Caddy - * loggers import the one redaction filter. + * loggers import the one redaction filter. Which path prefixes the filter rewrites is pinned against + * the routes themselves in apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts, which CI + * runs on route changes. */ -import { readdirSync, readFileSync, statSync } from 'node:fs'; -import { join, relative, resolve } from 'node:path'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; import { describe, expect, it } from 'vitest'; import { parse } from 'yaml'; @@ -26,38 +28,6 @@ const caddyfile = readFileSync(`${SELFHOST}/caddy/Caddyfile`, 'utf8'); const redaction = readFileSync(`${SELFHOST}/caddy/log-redaction.caddy`, 'utf8'); const keepWarm = readFileSync(`${SELFHOST}/caddy/keep-warm/on.caddy`, 'utf8'); -/** Route-definition strings with a path parameter named like a credential. */ -const CREDENTIAL_ROUTE = - /(?:\.(?:get|post|put|patch|delete|all|on)\(|path=)\s*['"`]([^'"`]*\/:(?:[a-z]*token|sig|signature|secret|key|code|jwt|nonce)\b[^'"`]*)['"`]/gi; - -/** Each known credential route and the logged path prefix the redaction filter rewrites. */ -const KNOWN_CREDENTIAL_ROUTES: Record = { - 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages': '/ai/proxy/', - 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages/count_tokens': - '/ai/proxy/', - 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/openai/v1/chat/completions': '/ai/proxy/', - 'apps/api/src/routes/bootstrap.ts /:token': '/api/bootstrap/', - 'apps/api/src/routes/projects/members.ts /invite-links/:token': '/api/projects/invite-links/', - 'apps/api/src/routes/projects/members.ts /invite-links/:token/request': - '/api/projects/invite-links/', - 'apps/web/src/App.tsx /projects/invite/:token': '/projects/invite/', -}; - -const PATH_CREDENTIAL_PREFIXES = [ - '/ai/proxy/', - '/api/bootstrap/', - '/api/projects/invite-links/', - '/projects/invite/', -]; - -function routeFiles(dir: string): string[] { - return readdirSync(dir).flatMap((name) => { - const path = join(dir, name); - if (statSync(path).isDirectory()) return routeFiles(path); - return path.endsWith('.ts') && !path.endsWith('.test.ts') ? [path] : []; - }); -} - describe('Caddy logging and keep-warm wiring', () => { it('passes keep-warm on by default, at 5 s', () => { expect(caddy?.environment?.SAM_KEEP_WARM).toBe('${SAM_KEEP_WARM:-on}'); @@ -76,35 +46,12 @@ describe('Caddy logging and keep-warm wiring', () => { expect(caddyfile).toMatch(/\tlog \{\s*output stdout\s*import log-redaction\.caddy/); }); - it('the redaction filter drops headers, query strings and path credentials', () => { + it('the redaction filter drops headers, query strings and preview paths', () => { expect(redaction).toMatch(/^\trequest>headers delete$/m); expect(redaction).toMatch(/^\tresp_headers delete$/m); expect(redaction).toMatch(/^\theaders delete$/m); expect(redaction).toContain('\t\tregexp "\\?.*$" "?"'); expect(redaction).toContain('\t\tregexp "^/p/[^?]*" "/p/"'); - for (const prefix of PATH_CREDENTIAL_PREFIXES) { - expect(redaction).toMatch(new RegExp(`regexp "\\^\\([^"]*\\|?${prefix}\\|?[^"]*\\)`)); - } - }); - - // Every route whose path carries a credential-like parameter must be redacted in the logs. - // A new one fails here until it is added to caddy/log-redaction.caddy and to this list. - it('every route with a credential in its path is on the redaction list', () => { - const found = [ - ...routeFiles(join(REPO, 'apps/api/src/routes')), - join(REPO, 'apps/web/src/App.tsx'), - ] - .flatMap((file) => - [...readFileSync(file, 'utf8').matchAll(CREDENTIAL_ROUTE)].map( - (m) => `${relative(REPO, file)} ${m[1]}` - ) - ) - .sort(); - expect(found.length).toBeGreaterThanOrEqual(6); // the scan itself works - expect(found).toEqual(Object.keys(KNOWN_CREDENTIAL_ROUTES).sort()); - for (const prefix of Object.values(KNOWN_CREDENTIAL_ROUTES)) { - expect(PATH_CREDENTIAL_PREFIXES).toContain(prefix); - } }); it('keeps the keep-warm check on a route that never serves a request', () => { From 509a63f6cf1303faf084d7d969ad3b78d2c92a03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:33:39 +0000 Subject: [PATCH 10/65] ci(selfhost): drop the workspace build from Validate Deploy Scripts Only two things needed built packages: gcp-bootstrap.test.ts parsed the printed credential with parseGcpCredential (imports shared and worker-core dist), and the scripts/selfhost type check covered live/, whose shared-flight test imports worker-core. The parser contract test moves to the API unit suite, which builds and also runs when the parser changes; live/ gets its own tsconfig, type-checked in the Self-host Live job after its build. pnpm selfhost:test now passes with every @simple-agent-manager import aliased to a missing module. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 18 +++-- .../selfhost/gcp-bootstrap-credential.test.ts | 67 +++++++++++++++++++ scripts/quality/ci-suite-selection.test.ts | 12 ++++ scripts/selfhost/gcp-bootstrap.test.ts | 22 ++---- scripts/selfhost/live/tsconfig.json | 6 ++ scripts/selfhost/tsconfig.json | 4 +- 6 files changed, 103 insertions(+), 26 deletions(-) create mode 100644 apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts create mode 100644 scripts/selfhost/live/tsconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 39c8ee9151..72cab31643 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -154,6 +154,10 @@ jobs: - 'deploy/selfhost/sam-mx/**' # The self-host access-log redaction guard scans the API routes against this filter. - 'deploy/selfhost/caddy/log-redaction.caddy' + # gcp-bootstrap-credential.test.ts runs the bootstrap against the fake gcloud and parses + # its output with the app's credential parser. + - 'deploy/selfhost/gcp-bootstrap.sh' + - 'scripts/selfhost/testdata/fake-gcloud-iam.mjs' - 'scripts/quality/node-pool-boundary.ts' - 'scripts/quality/node-pool-boundary/**' - 'tests/fixtures/acp-activity-report-v1.json' @@ -887,12 +891,8 @@ jobs: - name: Enforce source file size limits run: pnpm quality:file-sizes - # The self-host scripts and their tests load API modules (the GCP credential parser, the - # shared-flight helper) that import workspace packages through their built dist/, as - # `pnpm selfhost:deploy` does after building them (deploy.ts buildApiDependencies). - - name: Build the API Worker's workspace dependencies - run: pnpm exec turbo run build --filter=@simple-agent-manager/api^... - + # No workspace build here: neither these scripts nor their tests import a workspace package + # (the self-host tests that do live in the API unit suite and the Self-host Live job). - name: Type check deployment scripts run: | pnpm exec tsc --project scripts/deploy/tsconfig.json --noEmit @@ -1268,10 +1268,14 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - # celld bundles API modules (worker-core's shared-flight) through their built dist/. + # celld bundles API modules (worker-core's shared-flight) through their built dist/, and the + # live tests type-check against them. - name: Build the API Worker's workspace dependencies run: pnpm exec turbo run build --filter=@simple-agent-manager/api^... + - name: Type check the live tests + run: pnpm exec tsc --project scripts/selfhost/live/tsconfig.json --noEmit + - name: Run self-host live tests run: pnpm selfhost:live-test diff --git a/apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts b/apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts new file mode 100644 index 0000000000..e238e8fec8 --- /dev/null +++ b/apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts @@ -0,0 +1,67 @@ +/** + * `pnpm selfhost:gcp-bootstrap` (deploy/selfhost/gcp-bootstrap.sh) prints the platform cloud + * credential an operator pastes into Admin -> Credentials. This runs the script against the fake + * `gcloud` its own tests use (scripts/selfhost/gcp-bootstrap.test.ts) and parses the printed JSON + * with the parser the app uses for every node (parseGcpCredential), so a change on either side + * fails here. It lives with the API unit tests because the parser imports workspace packages + * through their built dist/, which the API unit suite builds and the self-host packaging tests do + * not need. + */ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { parseGcpCredential } from '../../../src/services/provider-credential-codecs'; + +const SCRIPT = resolve(import.meta.dirname, '../../../../../deploy/selfhost/gcp-bootstrap.sh'); +const FAKE_GCLOUD_IAM = resolve( + import.meta.dirname, + '../../../../../scripts/selfhost/testdata/fake-gcloud-iam.mjs' +); +const ISSUER = 'https://api.vmtest.example.org'; + +let dir: string; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'gcp-bootstrap-credential-')); + writeFileSync( + join(dir, 'gcloud'), + `#!/usr/bin/env bash\nexec node ${JSON.stringify(FAKE_GCLOUD_IAM)} "$@"\n` + ); + writeFileSync( + join(dir, 'curl'), + `#!/usr/bin/env bash\nprintf '{"issuer":"%s"}' ${JSON.stringify(ISSUER)}\n` + ); + chmodSync(join(dir, 'gcloud'), 0o755); + chmodSync(join(dir, 'curl'), 0o755); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('gcp-bootstrap.sh output', () => { + it('prints JSON the credential parser accepts once ZONE is filled in (box round R12)', () => { + const result = spawnSync('bash', [SCRIPT, '--project', 'sam-vm-test', '--api-url', ISSUER], { + encoding: 'utf8', + env: { PATH: `${dir}:${process.env.PATH ?? ''}`, STATE: dir, HOME: dir }, + timeout: 60_000, + }); + expect(result.status, result.stderr).toBe(0); + const json = /^\{"version":1,"provider":"gcp".*\}$/m.exec(result.stdout)?.[0]; + expect(json).toBeDefined(); + // The operator replaces ZONE; the result is what the app stores and parses for every node. + const parsed = parseGcpCredential(json!.replace('"ZONE"', '"europe-west1-b"')); + expect(parsed).toMatchObject({ + authType: 'workload-identity', + gcpProjectId: 'sam-vm-test', + gcpProjectNumber: '123456789012', + serviceAccountEmail: 'sam-nodes@sam-vm-test.iam.gserviceaccount.com', + wifProviderId: 'sam-api', + defaultZone: 'europe-west1-b', + }); + expect(parsed.authType === 'workload-identity' && parsed.wifPoolId).toMatch( + /^sam-[0-9a-f]{8}$/ + ); + }); +}); diff --git a/scripts/quality/ci-suite-selection.test.ts b/scripts/quality/ci-suite-selection.test.ts index 6ee39f8147..cce92234b4 100644 --- a/scripts/quality/ci-suite-selection.test.ts +++ b/scripts/quality/ci-suite-selection.test.ts @@ -712,6 +712,18 @@ describe('runner budget (jobs a ready PR starts)', () => { expect(jobs(['apps/web/src/main.tsx']).get('deploy-scripts')).not.toBe('success'); }); + // Its tests import no workspace package, so it builds none (a full API-dependency build was + // most of its runtime); the tests that need one run in the API unit suite and Self-host Live. + it('Validate Deploy Scripts builds no workspace package; Self-host Live builds before its type check', () => { + const steps = (job: string) => loadWorkflow().jobs[job]!.steps!.map((step) => step.run ?? ''); + expect(steps('deploy-scripts').filter((run) => run.includes('turbo run build'))).toEqual([]); + const live = steps('selfhost-live'); + const build = live.findIndex((run) => run.includes('turbo run build')); + const typecheck = live.findIndex((run) => run.includes('scripts/selfhost/live/tsconfig.json')); + expect(build).toBeGreaterThanOrEqual(0); + expect(typecheck).toBeGreaterThan(build); + }); + // The access-log redaction guards: the API one runs with the API unit suite, the App.tsx one // with the web suite, and either runs when the redaction filter itself changes. it('a credential route or the redaction filter selects the suite holding its guard', () => { diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index 6659f26b6c..069bcecec7 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -9,8 +9,6 @@ import { join, resolve } from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { parseGcpCredential } from '../../apps/api/src/services/provider-credential-codecs'; - // Every case runs bash and a node-based fake gcloud many times. vi.setConfig({ testTimeout: 60_000 }); @@ -118,26 +116,14 @@ describe('pnpm selfhost:gcp-bootstrap', () => { ); }); - it('prints where the credential goes in SAM and JSON the credential parser accepts (box round R12)', () => { + // The printed JSON is parsed with the app's own parser in + // apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts (it needs built packages). + it('prints where the credential goes in SAM (box round R12)', () => { const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); expect(result.status, result.stderr).toBe(0); expect(result.stdout).toContain('Admin -> Credentials -> Add Credential'); expect(result.stdout).not.toContain('Integrations'); - const json = /^\{"version":1,"provider":"gcp".*\}$/m.exec(result.stdout)?.[0]; - expect(json).toBeDefined(); - // The operator replaces ZONE; the result is what the app stores and parses for every node. - const parsed = parseGcpCredential(json!.replace('"ZONE"', '"europe-west1-b"')); - expect(parsed).toMatchObject({ - authType: 'workload-identity', - gcpProjectId: 'sam-vm-test', - gcpProjectNumber: '123456789012', - serviceAccountEmail: 'sam-nodes@sam-vm-test.iam.gserviceaccount.com', - wifProviderId: 'sam-api', - defaultZone: 'europe-west1-b', - }); - expect(parsed.authType === 'workload-identity' && parsed.wifPoolId).toMatch( - /^sam-[0-9a-f]{8}$/ - ); + expect(result.stdout).toMatch(/^\{"version":1,"provider":"gcp".*"defaultZone":"ZONE"\}$/m); }); it('is idempotent: a second run creates nothing new and prints the same values', () => { diff --git a/scripts/selfhost/live/tsconfig.json b/scripts/selfhost/live/tsconfig.json new file mode 100644 index 0000000000..dfe74aba68 --- /dev/null +++ b/scripts/selfhost/live/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "../../deploy/tsconfig.json", + "include": ["**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/scripts/selfhost/tsconfig.json b/scripts/selfhost/tsconfig.json index 47ef86cce4..e27c50787b 100644 --- a/scripts/selfhost/tsconfig.json +++ b/scripts/selfhost/tsconfig.json @@ -2,5 +2,7 @@ "$schema": "https://json.schemastore.org/tsconfig", "extends": "../deploy/tsconfig.json", "include": ["**/*.ts"], - "exclude": ["node_modules", "dist"] + // live/ imports API modules that resolve workspace packages through their built dist/, so it + // has its own project, checked by the Self-host Live job after it builds them. + "exclude": ["node_modules", "dist", "live"] } From 9f58d142c1e46572098885651d0bb0eaa7219f6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:38:11 +0000 Subject: [PATCH 11/65] fix(selfhost): gcp-bootstrap refuses a shared pool, pins its APIs and roles to the guided setup - An existing --pool-id is reused only when every provider in it (deleted ones too) is PROVIDER_ID trusting this install's issuer: the service account binding is pool-wide. - The binding comment no longer claims the pool is this install only: it admits any token the install signs for the provider's audience, and SAM does not yet stop a user credential from naming the pool (SAM task 01M7SB8FRZ08M5NEX9WGM74X61). README and the script say to use a project dedicated to SAM's nodes. - NODE_APIS / NODE_ROLES document why cloudresourcemanager, aiplatform and roles/aiplatform.user are left out; a test fails when the script drifts from GCP_REQUIRED_APIS or gcp-setup.ts SA_PROJECT_ROLES. - A trailing flag with no value is a clear error; --help prints the whole header. - README: the access log redacts path credentials on the listed routes only, and an .env build-arg change needs docker compose build caddy (upgrade never sees it). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 + deploy/selfhost/README.md | 19 ++- deploy/selfhost/gcp-bootstrap.sh | 68 ++++++-- scripts/selfhost/gcp-bootstrap.test.ts | 148 +++++++++++++++++- scripts/selfhost/testdata/fake-gcloud-iam.mjs | 12 +- 5 files changed, 230 insertions(+), 20 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72cab31643..adfc23ecde 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -264,6 +264,9 @@ jobs: # The box files its static tests read: compose, Caddy fragments and start.sh, frps.toml, # gcp-bootstrap.sh, .env.example. - 'deploy/selfhost/**' + # gcp-bootstrap.test.ts pins the script's APIs and roles to the guided setup's. + - 'packages/shared/src/constants/gcp-required-apis.ts' + - 'apps/api/src/services/gcp-setup.ts' # ...and what its tests read outside it: the self-host migration projection and the # SMTP settings parser. - 'apps/api/src/selfhost/**' diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 5f40005cc6..3fd1527de4 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -65,6 +65,14 @@ From the repository root on the VM: creates a workload identity pool and provider trusting only this install, and a node service account, then prints the credential JSON to paste in **Admin -> Credentials** (Cloud Provider, GCP). Add machines to the installation pool in **Admin -> Infrastructure**. + **Use a GCP project dedicated to SAM's nodes**, not the box's: the node service account's + roles apply to the whole project, so in a shared project it could change or delete the box VM + and its firewall. An existing `--pool-id` is reused only when its sole provider is this + install's. Known gap: the service account trusts every token this install signs for that + provider, and SAM does not yet stop a user's own GCP credential from naming this pool, so a + user of the install could act as the node service account (fix tracked as SAM task + 01M7SB8FRZ08M5NEX9WGM74X61). Until then, give accounts on a GCP-node install only to people + you would trust with that project. `pnpm selfhost:deploy --dry-run` prints the Worker configuration it would deploy, secrets redacted. @@ -101,8 +109,11 @@ pinned by version and verified against the Go checksum database, and the build f binary carries exactly those versions; `sam-mx` modules are pinned by `go.sum`. A build still downloads from the network (Docker Hub, the Go module proxy, Alpine packages). The -content is pinned, so a changed upstream fails the build rather than changing the image. After -changing `CADDY_DNS_MODULE`, run `docker compose build caddy`. +content is pinned, so a changed upstream fails the build rather than changing the image. + +After changing a build argument in `.env` (`CADDY_DNS_MODULE`), run `docker compose build caddy` +yourself, then `docker compose up -d`: `selfhost:upgrade` rebuilds only for changes in the +repository, so it never notices an `.env` edit. ## Settings worth knowing @@ -149,7 +160,9 @@ waits 1.5-2.4 s while a new one loads. Caddy pings `/health` every `SAM_KEEP_WAR (default 5s) so the ping pays that cost instead of a user. `SAM_KEEP_WARM=off` turns it off. **Logs.** `docker compose logs caddy` is the access log: one JSON line per request, with no -headers, query strings or path credentials. `docker compose logs celld` is the Worker's output. +headers, no query strings, and no credentials in the path on the routes listed in +`caddy/log-redaction.caddy` (bootstrap, invite and AI-proxy tokens, preview signatures). +`docker compose logs celld` is the Worker's output. ## Not included yet diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index c93d56a962..0a13a0d269 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -12,8 +12,14 @@ # then prints the platform cloud credential to add in Admin -> Credentials (Cloud Provider, GCP). # It does not create the box VM, its firewall, the fleet bucket or DNS (README.md, Prerequisites). # +# Use a GCP project dedicated to SAM's nodes, not the box's project: the service account's roles +# apply to the whole project, so in a shared project it could also change or delete the box VM +# and its firewall rules. +# # Every resource is described first and created only when missing. A provider that already -# trusts a different issuer is never retargeted; pick another --pool-id. +# trusts a different issuer is never retargeted, and an existing pool is reused only when its +# sole provider is this install's (the pool-wide binding below admits every provider in it); +# otherwise pick another --pool-id. # # Run it once the install answers (after the first `pnpm selfhost:deploy`): it checks the issuer # the install advertises. @@ -36,19 +42,37 @@ SA_ID="sam-nodes" DRY_RUN=0 CHECK_ISSUER=1 +# The APIs node provisioning calls: compute (VMs, firewalls; packages/providers/src/gcp*.ts), +# cloudbilling (list prices, gcp-pricing.ts), and iam, sts and iamcredentials (the pool and the +# token exchange and impersonation in apps/api/src/services/gcp-sts.ts). The in-app guided setup +# enables GCP_REQUIRED_APIS (packages/shared/src/constants/gcp-required-apis.ts); two of those +# are intentionally left out here, because no node path calls them: +# cloudresourcemanager.googleapis.com: only the guided setup (gcp-setup.ts) calls it, with the +# user's own OAuth token, to list projects and edit the project IAM policy. +# aiplatform.googleapis.com: Vertex AI for agents in a user's own project, not node provisioning. +# Likewise the guided setup also grants roles/aiplatform.user (SA_PROJECT_ROLES in gcp-setup.ts); +# the node service account gets only the two compute roles. +# scripts/selfhost/gcp-bootstrap.test.ts fails when either list drifts from the guided setup's. +NODE_APIS=(compute.googleapis.com iam.googleapis.com iamcredentials.googleapis.com + sts.googleapis.com cloudbilling.googleapis.com) +NODE_ROLES=(roles/compute.instanceAdmin.v1 roles/compute.securityAdmin) + die() { echo "gcp-bootstrap: $*" >&2; exit 1; } +# `--flag value`: refuse a trailing flag with no value instead of failing on `shift 2`. +need_value() { [ "$2" -ge 2 ] || die "$1 needs a value (see --help)"; } while [ $# -gt 0 ]; do case "$1" in --) shift ;; - --project) PROJECT="${2:-}"; shift 2 ;; - --api-url) API_URL="${2:-}"; shift 2 ;; - --pool-id) POOL_ID="${2:-}"; shift 2 ;; - --provider-id) PROVIDER_ID="${2:-}"; shift 2 ;; - --service-account) SA_ID="${2:-}"; shift 2 ;; + --project) need_value "$1" $#; PROJECT="$2"; shift 2 ;; + --api-url) need_value "$1" $#; API_URL="$2"; shift 2 ;; + --pool-id) need_value "$1" $#; POOL_ID="$2"; shift 2 ;; + --provider-id) need_value "$1" $#; PROVIDER_ID="$2"; shift 2 ;; + --service-account) need_value "$1" $#; SA_ID="$2"; shift 2 ;; --skip-issuer-check) CHECK_ISSUER=0; shift ;; --dry-run) DRY_RUN=1; shift ;; - -h|--help) sed -n '2,28p' "$0"; exit 0 ;; + # The header comment, up to the first line that is not a comment. + -h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; exit 0 ;; *) die "unknown argument: $1 (see --help)" ;; esac done @@ -113,11 +137,11 @@ PROJECT_NUMBER="$(gcloud projects describe "$PROJECT" --format='value(projectNum [ -n "$PROJECT_NUMBER" ] || die "project ${PROJECT} has no project number" echo "Project ${PROJECT} (${PROJECT_NUMBER}), issuer ${ISSUER}, pool ${POOL_ID}" +echo "Note: use a project dedicated to SAM nodes. The node service account's roles apply to the whole project, so in a shared project it could also change the box VM and its firewall." # cloudbilling: read-only Compute Engine list prices for the node catalog (no IAM role needed; # without it every GCP machine shows "Price unavailable"; box round R14). -change services enable compute.googleapis.com iam.googleapis.com iamcredentials.googleapis.com \ - sts.googleapis.com cloudbilling.googleapis.com --project="$PROJECT" +change services enable "${NODE_APIS[@]}" --project="$PROJECT" # A deleted pool still describes (state DELETED) and keeps its id for 30 days: reusing it as # "exists" would then try to create a provider in a deleted pool (R13 D5). @@ -125,6 +149,18 @@ if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --projec --location=global --format='value(state)' 2>/dev/null)"; then [ "$pool_state" != "DELETED" ] \ || die "workload identity pool ${POOL_ID} was deleted (Google keeps a deleted pool for 30 days, and its id cannot be reused until it is purged). Either undelete it: gcloud iam workload-identity-pools undelete ${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --pool-id and put the new values in the platform credential (Admin -> Credentials)." + # The service account binding below is pool-wide, so every provider in the pool would be + # admitted: reuse the pool only when each provider in it (deleted ones too, which can be + # undeleted) is PROVIDER_ID trusting this install's issuer. + pool_providers="$(gcloud iam workload-identity-pools providers list --project="$PROJECT" \ + --location=global --workload-identity-pool="$POOL_ID" --show-deleted \ + --format='value(name,oidc.issuerUri)')" || die "cannot list the providers of pool ${POOL_ID}" + while IFS=$'\t' read -r provider_name provider_issuer; do + [ -n "$provider_name" ] || continue + if [ "${provider_name##*/}" != "$PROVIDER_ID" ] || [ "$provider_issuer" != "$ISSUER" ]; then + die "pool ${POOL_ID} is not dedicated to this install: its provider ${provider_name##*/} already trusts ${provider_issuer:-a non-OIDC issuer}, and the node service account would admit every provider in the pool. Use another --pool-id." + fi + done <<<"$pool_providers" echo "pool ${POOL_ID}: exists" else change iam workload-identity-pools create "$POOL_ID" --project="$PROJECT" --location=global \ @@ -162,15 +198,19 @@ else --description="Creates and deletes SAM workspace VMs and their firewall rules for ${ISSUER}" fi -for role in roles/compute.instanceAdmin.v1 roles/compute.securityAdmin; do +for role in "${NODE_ROLES[@]}"; do change_retry projects add-iam-policy-binding "$PROJECT" --member="serviceAccount:${SA_EMAIL}" \ --role="$role" --condition=None --quiet --format=none done -# Scope: the whole pool. That is this one install only, because the pool is created for it and -# its only provider admits tokens whose issuer is this install's API origin (the condition -# above, checked again on every run). Any provider added to this pool later would inherit the -# service account, so do not add providers to it. +# Scope: the whole pool. Its only provider (checked above on every run) admits tokens whose +# issuer is this install's API origin and whose audience is that provider, so the binding admits +# ANY token this installation signs for the provider's audience, not only the ones it signs for +# node provisioning. SAM does not currently stop a user's own GCP credential from naming this +# pool, provider and service account, so a user of this install could obtain such a token and act +# as the node service account; closing that needs a Worker change (SAM task +# 01M7SB8FRZ08M5NEX9WGM74X61). Any provider added to this pool later would inherit the service +# account too, so do not add providers to it. change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ --role=roles/iam.workloadIdentityUser \ --member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" \ diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index 069bcecec7..d7d5fdd398 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -9,6 +9,8 @@ import { join, resolve } from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { GCP_REQUIRED_APIS } from '../../packages/shared/src/constants/gcp-required-apis'; + // Every case runs bash and a node-based fake gcloud many times. vi.setConfig({ testTimeout: 60_000 }); @@ -51,7 +53,7 @@ function run(args: string[], advertisedIssuer = ISSUER, env: NodeJS.ProcessEnv = interface FakeGcp { pools: Record; - providers: Record; + providers: Record; accounts: Record; bindings: string[]; } @@ -159,6 +161,84 @@ describe('pnpm selfhost:gcp-bootstrap', () => { expect(gcp().providers['sam-api'].issuer).toBe(ISSUER); }); + // S1: the node service account binding is pool-wide, so a reused pool must hold nothing but + // this install's provider. + describe('an existing --pool-id', () => { + const seedPool = (providers: Record) => { + writeFileSync( + join(state, 'gcp.json'), + JSON.stringify({ + pools: { 'sam-shared': { description: 'made elsewhere' } }, + providers: Object.fromEntries( + Object.entries(providers).map(([id, p]) => [id, { ...p, pool: 'sam-shared' }]) + ), + accounts: {}, + bindings: [], + }) + ); + }; + const args = ['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-shared']; + const changes = (result: ReturnType) => + result.calls.filter((c) => MUTATING.test(c) && !c.startsWith('services')); + + it('is refused when another provider in it trusts another issuer; nothing is bound', () => { + seedPool({ 'github-actions': { issuer: 'https://token.actions.githubusercontent.com' } }); + const result = run(args); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('pool sam-shared is not dedicated to this install'); + expect(result.stderr).toContain( + 'provider github-actions already trusts https://token.actions.githubusercontent.com' + ); + expect(changes(result)).toEqual([]); + expect(gcp().bindings).toEqual([]); + }); + + it('is refused when it also holds this issuer under another provider id', () => { + seedPool({ 'sam-api': { issuer: ISSUER }, 'sam-api-2': { issuer: ISSUER } }); + const result = run(args); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('provider sam-api-2 already trusts'); + expect(changes(result)).toEqual([]); + }); + + it('is refused when the other provider is soft-deleted (it can be undeleted)', () => { + seedPool({ other: { issuer: 'https://idp.example.com', state: 'DELETED' } }); + const result = run(args); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('provider other already trusts https://idp.example.com'); + expect(changes(result)).toEqual([]); + }); + + it('control: reused when it holds only this install provider, or nothing yet', () => { + seedPool({ 'sam-api': { issuer: ISSUER } }); + const reused = run(args); + expect(reused.status, reused.stderr).toBe(0); + expect(reused.stdout).toContain('pool sam-shared: exists'); + expect(reused.calls.filter((c) => / create/.test(c) && c.includes('pools'))).toEqual([]); + + seedPool({}); + const empty = run(args); + expect(empty.status, empty.stderr).toBe(0); + expect(gcp().providers['sam-api']).toMatchObject({ issuer: ISSUER, pool: 'sam-shared' }); + }); + }); + + it.each(['--project', '--api-url', '--pool-id', '--provider-id', '--service-account'])( + 'a trailing %s with no value is a clear error, not a shift failure', + (flag) => { + const result = run(['--project', 'sam-vm-test', flag]); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`gcp-bootstrap: ${flag} needs a value`); + expect(result.calls).toEqual([]); + } + ); + + it('says to use a project dedicated to SAM nodes', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--dry-run']); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('use a project dedicated to SAM nodes'); + }); + it('refuses an install whose discovery document names a different issuer', () => { const result = run( ['--project', 'sam-vm-test', '--api-url', ISSUER], @@ -227,3 +307,69 @@ describe('pnpm selfhost:gcp-bootstrap', () => { expect(result.calls).toEqual([]); }); }); + +/** + * A4: what the bootstrap enables and grants, against what the in-app guided setup does for a user + * project. Every API or role it leaves out must be on these lists with a reason, and named in + * the script's own comment, so a new required API fails here until someone decides. + */ +const OMITTED_APIS: Record = { + 'cloudresourcemanager.googleapis.com': + 'only the guided setup calls it, with the user OAuth token; nodes never do', + 'aiplatform.googleapis.com': 'Vertex AI for agents in a user project, not node provisioning', +}; +/** + * SA_PROJECT_ROLES in apps/api/src/services/gcp-setup.ts (not exported, so copied here; the test + * below reads that file and fails when the two differ). + */ +const GUIDED_SETUP_SA_ROLES = [ + 'roles/compute.instanceAdmin.v1', + 'roles/compute.securityAdmin', + 'roles/aiplatform.user', +]; +const OMITTED_ROLES: Record = { + 'roles/aiplatform.user': 'Vertex AI for agents; the node service account only manages VMs', +}; + +describe('gcp-bootstrap.sh against the guided setup (drift)', () => { + const script = readFileSync(SCRIPT, 'utf8'); + const enabled = () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + const services = result.calls.find((c) => c.startsWith('services enable'))!; + const roles = result.calls + .filter((c) => c.startsWith('projects add-iam-policy-binding')) + .map((c) => /--role=(\S+)/.exec(c)?.[1] ?? ''); + return { apis: services.split(' ').filter((w) => w.endsWith('.googleapis.com')), roles }; + }; + + it('enables only APIs the guided setup requires, and omits only listed ones', () => { + const required = GCP_REQUIRED_APIS.map((api) => api.service); + const { apis } = enabled(); + expect(apis.length).toBeGreaterThan(0); + for (const api of apis) expect(required, api).toContain(api); + expect(required.filter((api) => !apis.includes(api)).sort()).toEqual( + Object.keys(OMITTED_APIS).sort() + ); + for (const api of Object.keys(OMITTED_APIS)) expect(script, api).toContain(`# ${api}:`); + }); + + it('the copied guided-setup role list still matches gcp-setup.ts', () => { + const source = readFileSync( + resolve(import.meta.dirname, '../../apps/api/src/services/gcp-setup.ts'), + 'utf8' + ); + const list = /const SA_PROJECT_ROLES = \[([^\]]*)\]/.exec(source)?.[1] ?? ''; + expect([...list.matchAll(/'(roles\/[^']+)'/g)].map((m) => m[1])).toEqual(GUIDED_SETUP_SA_ROLES); + }); + + it('grants only roles the guided setup grants, and omits only listed ones', () => { + const { roles } = enabled(); + expect(roles.length).toBeGreaterThan(0); + for (const role of roles) expect(GUIDED_SETUP_SA_ROLES, role).toContain(role); + expect(GUIDED_SETUP_SA_ROLES.filter((role) => !roles.includes(role)).sort()).toEqual( + Object.keys(OMITTED_ROLES).sort() + ); + for (const role of Object.keys(OMITTED_ROLES)) expect(script, role).toContain(role); + }); +}); diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index b721fc0410..7c59935cd9 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -32,12 +32,20 @@ if (cmd.startsWith('projects describe')) out('123456789012'); else if (cmd.startsWith('services enable')) save(); else if (cmd.startsWith('iam workload-identity-pools providers')) { const [, , , op, id] = words; - if (op === 'describe') { + const pool = flag('workload-identity-pool'); + if (op === 'list') { + // value(name,oidc.issuerUri): the full resource name, a tab, the issuer. + for (const [providerId, provider] of Object.entries(db.providers)) { + if (provider.pool !== pool) continue; + const name = `projects/123456789012/locations/global/workloadIdentityPools/${pool}/providers/${providerId}`; + out(`${name}\t${provider.issuer ?? ''}`); + } + } else if (op === 'describe') { if (!db.providers[id]) fail('not found'); if (format.includes('issuerUri')) out(db.providers[id].issuer); if (format.includes('state')) out(db.providers[id].state ?? 'ACTIVE'); } else if (op === 'create-oidc') { - db.providers[id] = { issuer: flag('issuer-uri') }; + db.providers[id] = { issuer: flag('issuer-uri'), pool }; save(); } else fail(`unexpected ${cmd}`); } else if (cmd.startsWith('iam workload-identity-pools')) { From 28749ee009a757bc05da92222ea083f899fb713d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:42:12 +0000 Subject: [PATCH 12/65] fix(selfhost): celld and frps run with no capabilities and a read-only root Both listen only on loopback ports above 1023. celld writes only CELLD_WATCH (its volume) and gets a tmpfs /tmp; checked on the pinned image with cap_drop ALL, no-new-privileges and a read-only root: a Worker and a SQLite Durable Object serve and keep their state across a restart, and /tmp stays empty. frps logs to the console and starts read-only. A static test pins the settings. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/docker-compose.yml | 13 ++++++++ .../selfhost/caddy-logging-compose.test.ts | 31 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml index deca8eaf61..9f6c1fd4fe 100644 --- a/deploy/selfhost/docker-compose.yml +++ b/deploy/selfhost/docker-compose.yml @@ -56,6 +56,14 @@ services: volumes: # A cache on one node: the bucket is the durable copy. - celld-data:/var/lib/celld + # Runs the Workers: no capability (its listeners are loopback ports above 1023) and a + # read-only root. It writes only CELLD_WATCH (the volume above) and nothing to /tmp; the + # tmpfs is there for the runtime's scratch files. Checked on the pinned image: a Worker and a + # SQLite Durable Object serve and keep their state across a restart. + cap_drop: [ALL] + security_opt: ['no-new-privileges:true'] + read_only: true + tmpfs: [/tmp] # Above CELLD_SHUTDOWN_TOTAL_MS (40 s) so a stop is a clean lease handoff. stop_grace_period: 50s # celld docs: restart without an attempt limit. An immediate restart can hit @@ -148,6 +156,11 @@ services: # same resolved range there and into the Worker's vars (scripts/selfhost/box-settings.ts). volumes: - ./frps:/etc/frp:ro + # No capability (it binds FRPS_BIND_PORT and lease ports, all loopback and above 1023) and + # a read-only root: frps.toml logs to the console and frps writes no file. + cap_drop: [ALL] + security_opt: ['no-new-privileges:true'] + read_only: true restart: unless-stopped # Mail collector for TEST installs (profile `mail-collector`, off by default): catches every diff --git a/scripts/selfhost/caddy-logging-compose.test.ts b/scripts/selfhost/caddy-logging-compose.test.ts index 6b744f4a4b..85456ac082 100644 --- a/scripts/selfhost/caddy-logging-compose.test.ts +++ b/scripts/selfhost/caddy-logging-compose.test.ts @@ -17,6 +17,11 @@ const SELFHOST = resolve(REPO, 'deploy/selfhost'); interface Service { environment?: Record; + cap_drop?: string[]; + cap_add?: string[]; + security_opt?: string[]; + read_only?: boolean; + tmpfs?: string[]; logging?: { driver?: string; options?: Record }; } @@ -62,3 +67,29 @@ describe('Caddy logging and keep-warm wiring', () => { expect(keepWarm).toContain('health_interval {$SAM_KEEP_WARM_INTERVAL:5s}'); }); }); + +// Every long-running box service on the host network runs without capabilities it does not need. +// celld and frps listen only on loopback ports above 1023, so they need none; Caddy keeps only +// NET_BIND_SERVICE for 80/443. Read-only roots: frps writes no file (frps.toml logs to the +// console); celld writes only its CELLD_WATCH volume (checked on the pinned image). +describe('box service privileges', () => { + it.each(['celld', 'frps'])('%s drops every capability and cannot gain one', (name) => { + const service = compose.services[name]; + expect(service?.cap_drop).toEqual(['ALL']); + expect(service?.cap_add).toBeUndefined(); + expect(service?.security_opt).toEqual(['no-new-privileges:true']); + expect(service?.read_only).toBe(true); + }); + + it('celld writes only its data volume and a tmpfs /tmp', () => { + const celld = compose.services.celld as Service & { volumes?: string[] }; + expect(celld.tmpfs).toEqual(['/tmp']); + expect(celld.volumes).toEqual(['celld-data:/var/lib/celld']); + expect(celld.environment?.CELLD_WATCH).toBe('/var/lib/celld'); + }); + + it('control: Caddy keeps only NET_BIND_SERVICE, for 80 and 443', () => { + expect(caddy?.cap_drop).toEqual(['ALL']); + expect(caddy?.cap_add).toEqual(['NET_BIND_SERVICE']); + }); +}); From 6ffc0c89dae9d4bcc9bfbc8e252ad8c0026548e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:51:04 +0000 Subject: [PATCH 13/65] fix(selfhost): the bundled object store refuses a root secret under 24 characters Its root credential reads every Worker secret in the fleet bucket. The entrypoint check moves from 8 to 24 characters (.env.example and README say so); a test runs the compose entrypoint under /bin/sh with the image entrypoint stubbed. The deploy test fixture's fleet secret is lengthened to match. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/.env.example | 2 +- deploy/selfhost/README.md | 4 +- deploy/selfhost/docker-compose.yml | 7 +-- .../selfhost/caddy-logging-compose.test.ts | 52 ++++++++++++++++--- scripts/selfhost/deploy-harness.ts | 2 +- 5 files changed, 55 insertions(+), 12 deletions(-) diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example index 281fcefcb0..ffff5c92ec 100644 --- a/deploy/selfhost/.env.example +++ b/deploy/selfhost/.env.example @@ -32,7 +32,7 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # CELLD_BUCKET=s3://celld-fleet # S3_ENDPOINT=http://127.0.0.1:9000 # AWS_ACCESS_KEY_ID=sam-objectstore -# AWS_SECRET_ACCESS_KEY= # openssl rand -hex 24 +# AWS_SECRET_ACCESS_KEY= # at least 24 characters (the store refuses less): openssl rand -hex 24 # Loopback ports (host network). Change only on conflict, and only here: a port set in the shell # also overrides this file for docker compose, and Caddy refuses to start if any of them lies in diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 3fd1527de4..1229c2a80c 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -123,7 +123,9 @@ credential scoped to the R2 prefix (`R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`; credential, which the deploy refuses). **For an `s3://` bucket `R2_S3_REGION` is required** (the store's SigV4 signing region, for MinIO usually `us-east-1`): the deploy refuses `R2_S3_ENDPOINT` without it. A `gs://` bucket defaults to `auto`. The bundled store is a community MinIO build that -celld does not qualify for production. +celld does not qualify for production. It refuses to start unless `AWS_ACCESS_KEY_ID` and +`AWS_SECRET_ACCESS_KEY` are set, are not `minioadmin`, and the secret has at least 24 characters +(`openssl rand -hex 24`): that credential reads every Worker secret in the bucket. **Reverse-tunnel ports and the gateway secret.** frps binds one loopback port per node from `REVERSE_TUNNEL_PORT_RANGE_START`..`_END` (default 20000-29999). The deploy writes the resolved diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml index 9f6c1fd4fe..72c4ee6b0f 100644 --- a/deploy/selfhost/docker-compose.yml +++ b/deploy/selfhost/docker-compose.yml @@ -286,7 +286,8 @@ services: # Compose interpolates every service, including ones whose profile is off, so a `:?` here # would stop a gs:// or s3:// install that never runs this store. The store checks instead: # it refuses an unset credential (MinIO would fall back to minioadmin), MinIO's well-known - # default, and a secret under 8 characters. /usr/bin/docker-entrypoint.sh is the image's + # default, and a secret under 24 characters (the root credential reads every deployed Worker + # secret in the fleet bucket, so it must not be guessable). /usr/bin/docker-entrypoint.sh is the image's # own ENTRYPOINT at the pinned digest. entrypoint: - /bin/sh @@ -296,8 +297,8 @@ services: :* | *: | minioadmin:* | *:minioadmin) echo 'objectstore: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env (not minioadmin)' >&2; exit 64;; esac; - test "$${#MINIO_ROOT_PASSWORD}" -ge 8 || - { echo 'objectstore: AWS_SECRET_ACCESS_KEY must be at least 8 characters' >&2; exit 64; }; + test "$${#MINIO_ROOT_PASSWORD}" -ge 24 || + { echo 'objectstore: AWS_SECRET_ACCESS_KEY must be at least 24 characters (openssl rand -hex 24)' >&2; exit 64; }; exec /usr/bin/docker-entrypoint.sh "$$@" - objectstore environment: diff --git a/scripts/selfhost/caddy-logging-compose.test.ts b/scripts/selfhost/caddy-logging-compose.test.ts index 85456ac082..6594570489 100644 --- a/scripts/selfhost/caddy-logging-compose.test.ts +++ b/scripts/selfhost/caddy-logging-compose.test.ts @@ -1,11 +1,13 @@ /** - * Static wiring for Caddy's access log and the keep-warm health check (the behaviour itself is - * proven against the real Caddy image in live/access-log-keep-warm.live.test.ts): compose passes - * the keep-warm settings with their defaults and caps the Caddy log on disk, and both Caddy - * loggers import the one redaction filter. Which path prefixes the filter rewrites is pinned against - * the routes themselves in apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts, which CI - * runs on route changes. + * Static wiring in docker-compose.yml. Caddy (its behaviour is proven against the real image in + * live/access-log-keep-warm.live.test.ts): compose passes the keep-warm settings with their + * defaults and caps the Caddy log on disk, and both Caddy loggers import the one redaction filter. + * Which path prefixes the filter rewrites is pinned against the routes themselves in + * apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts and + * apps/web/tests/unit/selfhost-log-redaction-routes.test.ts, which CI runs on route changes. + * Also: the capabilities of celld and frps, and the bundled object store's credential check. */ +import { spawnSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; @@ -22,6 +24,7 @@ interface Service { security_opt?: string[]; read_only?: boolean; tmpfs?: string[]; + entrypoint?: string[]; logging?: { driver?: string; options?: Record }; } @@ -93,3 +96,40 @@ describe('box service privileges', () => { expect(caddy?.cap_add).toEqual(['NET_BIND_SERVICE']); }); }); + +// The bundled store's root credential reads every Worker secret in the fleet bucket. Its +// entrypoint (run here under /bin/sh, with the image's own entrypoint stubbed) refuses a weak one. +describe('bundled object store credential', () => { + const [shell, flag, script, name] = compose.services.objectstore?.entrypoint ?? []; + const run = (user: string, password: string) => + spawnSync( + shell!, + [ + flag!, + // Compose writes $$ for a literal $; the image's entrypoint becomes a marker. + script!.replaceAll('$$', '$').replace('exec /usr/bin/docker-entrypoint.sh', 'echo started'), + name!, + 'server', + ], + { + encoding: 'utf8', + env: { PATH: '/usr/bin:/bin', MINIO_ROOT_USER: user, MINIO_ROOT_PASSWORD: password }, + } + ); + + it.each([ + ['an unset secret', 'sam-objectstore', ''], + ['the MinIO default', 'minioadmin', 'minioadmin'], + ['a 23-character secret', 'sam-objectstore', 'a'.repeat(23)], + ])('refuses %s', (_, user, password) => { + const result = run(user, password); + expect(result.status).toBe(64); + expect(result.stdout).not.toContain('started'); + }); + + it('control: starts with a 24-character secret', () => { + const result = run('sam-objectstore', 'a'.repeat(24)); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('started'); + }); +}); diff --git a/scripts/selfhost/deploy-harness.ts b/scripts/selfhost/deploy-harness.ts index e654c5edd6..6f3c40e569 100644 --- a/scripts/selfhost/deploy-harness.ts +++ b/scripts/selfhost/deploy-harness.ts @@ -21,7 +21,7 @@ const BASE_BOX_ENV = [ 'CELLD_BUCKET=s3://fleet/celld', 'S3_ENDPOINT=http://127.0.0.1:9000', 'AWS_ACCESS_KEY_ID=fleet-key', - 'AWS_SECRET_ACCESS_KEY=fleet-secret-0123456789', + 'AWS_SECRET_ACCESS_KEY=fleet-secret-0123456789abcdef', ]; export function writeBox(dir: string, extra: string[] = []): string { From 4f83ce8731e9bbc0aa5a4c79bf8679d6e1c033ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:57:01 +0000 Subject: [PATCH 14/65] fix(selfhost): reserve sam-mx's port and check box ports before anything starts S4: - SAM_MX_LISTEN (sam-mx's public SMTP listener, default :25; the port after the last ':') joins the reserved box ports: the deploy, upgrade and Caddy's start.sh refuse it inside the lease range. compose passes it to Caddy. - loadBoxEnv (box-settings.ts) reads the .env, applies shell port overrides and checks the range, so selfhost:deploy refuses before writing platform keys and selfhost:upgrade before it fetches, checks out or runs docker compose. - start.sh checks each lease-range bound is a plain number: a malformed one such as 1:2 made the -ge test error, which if read as false, silently skipping the check. - celld, frps and the mail collector have no capabilities, so their ports must be 1024 or above. A6: deploy.ts and upgrade-lib.ts share loadBoxEnv instead of each parsing the .env and applying overrides; SELFHOST_DIR lives in deploy-steps.ts and COMPOSE_PATH derives from it. The live harness's caddyBoxEnv takes its names from BOX_RESERVED_PORTS. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/.env.example | 3 +- deploy/selfhost/README.md | 9 ++-- deploy/selfhost/caddy/start.sh | 22 +++++--- deploy/selfhost/docker-compose.yml | 2 + scripts/selfhost/box-settings.test.ts | 76 ++++++++++++++++++++++++++- scripts/selfhost/box-settings.ts | 57 +++++++++++++++++++- scripts/selfhost/caddy-start.test.ts | 31 ++++++++++- scripts/selfhost/deploy-steps.ts | 4 +- scripts/selfhost/deploy.test.ts | 11 ++++ scripts/selfhost/deploy.ts | 21 +++----- scripts/selfhost/image-rebuilds.ts | 6 ++- scripts/selfhost/live/harness.ts | 16 ++---- scripts/selfhost/upgrade-lib.ts | 16 +++--- scripts/selfhost/upgrade.test.ts | 24 ++++++++- scripts/selfhost/upgrade.ts | 4 +- 15 files changed, 244 insertions(+), 58 deletions(-) diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example index ffff5c92ec..4eeafb2efd 100644 --- a/deploy/selfhost/.env.example +++ b/deploy/selfhost/.env.example @@ -44,7 +44,8 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # OBJECTSTORE_CONSOLE_PORT=9001 # HTTP_PORT=80 # HTTPS_PORT=443 -# MAIL_COLLECTOR_SMTP_PORT=1025 and MAIL_COLLECTOR_UI_PORT=8025 (below) are box ports too. +# MAIL_COLLECTOR_SMTP_PORT=1025 and MAIL_COLLECTOR_UI_PORT=8025 (below), and the port of +# SAM_MX_LISTEN (sam-mx, default :25), are box ports too. # Presigned browser uploads (attachments, snapshots) go straight to the fleet bucket. Set the # store's public HTTPS endpoint here and a credential scoped to //r2//* diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 1229c2a80c..2f87c968db 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -131,9 +131,12 @@ celld does not qualify for production. It refuses to start unless `AWS_ACCESS_KE `REVERSE_TUNNEL_PORT_RANGE_START`..`_END` (default 20000-29999). The deploy writes the resolved range to both the Worker and `.state/gateway.env`, and refuses a range that contains a box port (`CELLD_PORT`, `CELLD_INTERNAL_PORT`, `FRPS_BIND_PORT`, `OBJECTSTORE_*`, `HTTP(S)_PORT`, -`MAIL_COLLECTOR_*`): a node leased one of those would receive traffic meant for it. Docker Compose -takes a port from the shell before `.env`, so the deploy checks shell overrides too, and Caddy's -`start.sh` refuses to start when a port it is given lies in the range. Set ports in `.env`, not +`MAIL_COLLECTOR_*`, and the port of sam-mx's `SAM_MX_LISTEN`): a node leased one of those would +receive traffic meant for it. Docker Compose takes a port from the shell before `.env`, so +`selfhost:deploy` and `selfhost:upgrade` check shell overrides too, as soon as they read `.env` +and before anything starts, and Caddy's `start.sh` refuses to start when a port it is given lies +in the range. celld, frps and the mail collector run without capabilities, so their ports must be +1024 or above. Set ports in `.env`, not the shell. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and Caddy present to the Worker's loopback-only gateway routes (`/api/self-host/gateway/*`, which Caddy answers with 404 from outside). When `gateway.env` changes, the deploy stops until the diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh index b6d2896eb5..805b852f09 100644 --- a/deploy/selfhost/caddy/start.sh +++ b/deploy/selfhost/caddy/start.sh @@ -59,17 +59,23 @@ esac # the shell before the .env, so this checks the values the stack really runs with. A port inside # the range could be leased to a node: the Worker and Caddy would then send that node's traffic, # with its credentials, to celld's unauthenticated operator API or another box service. +# Each bound must be a plain number: a malformed one (`1:2`, `20000x`) would make the `-ge`/`-le` +# tests below error, which `if` reads as false, silently skipping the check. start="${REVERSE_TUNNEL_PORT_RANGE_START:-}" end="${REVERSE_TUNNEL_PORT_RANGE_END:-}" -case "$start:$end" in -*[!0-9:]* | :* | *:) - echo "caddy: REVERSE_TUNNEL_PORT_RANGE_START/END missing from gateway.env; run pnpm selfhost:deploy --init" >&2 - exit 64 - ;; -esac +for bound in "$start" "$end"; do + case "$bound" in + '' | *[!0-9]*) + echo "caddy: REVERSE_TUNNEL_PORT_RANGE_START/END missing from gateway.env or not a number; run pnpm selfhost:deploy --init" >&2 + exit 64 + ;; + esac +done +# SAM_MX_LISTEN is a listen address ([host]:port): its port is the part after the last ':'. for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT OBJECTSTORE_PORT \ - OBJECTSTORE_CONSOLE_PORT MAIL_COLLECTOR_SMTP_PORT MAIL_COLLECTOR_UI_PORT; do + OBJECTSTORE_CONSOLE_PORT MAIL_COLLECTOR_SMTP_PORT MAIL_COLLECTOR_UI_PORT SAM_MX_LISTEN; do eval "port=\"\${$name:-}\"" + port="${port##*:}" case "$port" in '' | *[!0-9]*) echo "caddy: $name must be set to a port number (docker-compose.yml passes every box port)" >&2 @@ -81,5 +87,5 @@ for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT O exit 64 fi done -unset start end name port +unset start end bound name port exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml index 72c4ee6b0f..c81538c454 100644 --- a/deploy/selfhost/docker-compose.yml +++ b/deploy/selfhost/docker-compose.yml @@ -115,6 +115,8 @@ services: OBJECTSTORE_CONSOLE_PORT: ${OBJECTSTORE_CONSOLE_PORT:-9001} MAIL_COLLECTOR_SMTP_PORT: ${MAIL_COLLECTOR_SMTP_PORT:-1025} MAIL_COLLECTOR_UI_PORT: ${MAIL_COLLECTOR_UI_PORT:-8025} + # sam-mx's public listen address; start.sh checks the port after the last ':'. + SAM_MX_LISTEN: ${SAM_MX_LISTEN:-:25} # Keep-warm for celld's stateless Worker isolate (caddy/keep-warm/on.caddy): on unless set # to off; the interval (1s-6s) sets how long a cold window follows each 30 s celld pool tick. # start.sh validates both. diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index a3fd26401e..7e2fce4aec 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -15,9 +15,11 @@ import { describe, expect, it } from 'vitest'; import { parse } from 'yaml'; import { + BOX_LISTEN_ADDRESSES, BOX_RESERVED_PORTS, celldChildEnv, gatewayEnvAction, + loadBoxEnv, presignVars, redactSecrets, renderGatewayEnv, @@ -228,7 +230,8 @@ const COMPOSE_TEXT = readFileSync( describe('BOX_RESERVED_PORTS', () => { it('matches the defaults docker-compose.yml actually uses', () => { - const defaults = [...COMPOSE_TEXT.matchAll(/\$\{([A-Z_]+):-(\d+)\}/g)].map( + // A listen address (SAM_MX_LISTEN) defaults to `:`. + const defaults = [...COMPOSE_TEXT.matchAll(/\$\{([A-Z_]+):-:?(\d+)\}/g)].map( (m) => [m[1]!, Number(m[2])] as const ); for (const [name, port] of Object.entries(BOX_RESERVED_PORTS)) { @@ -249,7 +252,8 @@ describe('BOX_RESERVED_PORTS', () => { 'utf8' ); for (const [name, port] of Object.entries(BOX_RESERVED_PORTS)) { - expect(compose.services.caddy.environment[name], name).toBe(`\${${name}:-${port}}`); + const fallback = BOX_LISTEN_ADDRESSES.includes(name) ? `:${port}` : String(port); + expect(compose.services.caddy.environment[name], name).toBe(`\${${name}:-${fallback}}`); expect(startSh, name).toMatch(new RegExp(`\\b${name}\\b`)); } }); @@ -279,6 +283,74 @@ describe('withComposePortOverrides (F21 L5)', () => { }); }); +describe('sam-mx listen address and unprivileged listeners (S4)', () => { + it.each([':20500', '0.0.0.0:20500', '[::]:20500', '20500'])( + 'fails the deploy when SAM_MX_LISTEN=%s lies in the range', + (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( + /contains SAM_MX_LISTEN \(20500\)/ + ); + } + ); + + it('control: the default :25 and a host-qualified :2525 are accepted', () => { + expect(resolveTunnelPortRange({ SAM_MX_LISTEN: ':25' })).toEqual({ start: 20000, end: 29999 }); + expect(resolveTunnelPortRange({ SAM_MX_LISTEN: '0.0.0.0:2525' })).toEqual({ + start: 20000, + end: 29999, + }); + }); + + it.each(['0.0.0.0:', ':x', 'smtp'])('refuses a malformed SAM_MX_LISTEN %s', (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow(/SAM_MX_LISTEN/); + }); + + // celld, frps and the collector run with no capability (docker-compose.yml cap_drop: [ALL]). + it.each(['CELLD_PORT', 'CELLD_INTERNAL_PORT', 'FRPS_BIND_PORT', 'MAIL_COLLECTOR_UI_PORT'])( + 'refuses a privileged port for %s, whose service has no capability', + (name) => { + expect(() => resolveTunnelPortRange({ [name]: '80' })).toThrow( + new RegExp(`${name} must be an integer between 1024`) + ); + } + ); + + it('control: Caddy and the object store may still sit below 1024', () => { + expect(resolveTunnelPortRange({ HTTPS_PORT: '8443', OBJECTSTORE_PORT: '900' })).toEqual({ + start: 20000, + end: 29999, + }); + }); +}); + +describe('loadBoxEnv (S4: checked before anything starts)', () => { + const box = (lines: string[]) => { + const file = join(mkdtempSync(join(tmpdir(), 'sam-box-env-')), '.env'); + writeFileSync(file, `${lines.join('\n')}\n`, { mode: 0o600 }); + return file; + }; + + it('refuses a box listener inside the lease range, from the .env or the shell', () => { + expect(() => loadBoxEnv(box(['SAM_MX_LISTEN=:20025']), {})).toThrow( + /contains SAM_MX_LISTEN \(20025\)/ + ); + const reported: string[] = []; + expect(() => + loadBoxEnv(box(['CELLD_INTERNAL_PORT=7001']), { CELLD_INTERNAL_PORT: '20001' }, (name) => + reported.push(name) + ) + ).toThrow(/contains CELLD_INTERNAL_PORT \(20001\)/); + // The override is reported before the refusal, so the operator sees where it came from. + expect(reported).toEqual(['CELLD_INTERNAL_PORT']); + }); + + it('control: returns the box with shell overrides applied', () => { + expect( + loadBoxEnv(box(['SAM_DOMAIN=box.example', 'CELLD_PORT=8080']), { CELLD_PORT: '8081' }) + ).toEqual({ SAM_DOMAIN: 'box.example', CELLD_PORT: '8081' }); + }); +}); + describe('gatewayEnvAction', () => { const settings = resolveTunnelSettings({}); const current = renderGatewayEnv(SECRET, settings); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index e743865c00..3888bd3122 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -2,6 +2,7 @@ * Settings shared by more than one process on a celld box, resolved once by the deploy script * so the Worker, frps and Caddy cannot disagree. */ +import { readFileSync } from 'node:fs'; // The Worker's own defaults and bounds (apps/api/src/selfhost/reverse-tunnel/config.ts re-exports // them): the deploy always passes the resolved range and heartbeat timeout to BOTH the Worker @@ -21,6 +22,7 @@ import { DEFAULT_MAIL_COLLECTOR_SMTP_PORT, DEFAULT_MAIL_COLLECTOR_UI_PORT, } from './mail-settings.js'; +import { parseDotenv } from './secret-files.js'; /** * Every other loopback/host listener on the box, with the default docker-compose.yml uses. A @@ -39,8 +41,29 @@ export const BOX_RESERVED_PORTS: Readonly> = { // Reserved even with the collector off: a node holding its port would receive sign-in codes. MAIL_COLLECTOR_SMTP_PORT: DEFAULT_MAIL_COLLECTOR_SMTP_PORT, MAIL_COLLECTOR_UI_PORT: DEFAULT_MAIL_COLLECTOR_UI_PORT, + // sam-mx's public SMTP listener (profile mail-in), a listen address: see BOX_LISTEN_ADDRESSES. + // Reserved even with the profile off, like the collector. + SAM_MX_LISTEN: 25, }; +/** + * Settings in BOX_RESERVED_PORTS that hold a listen address (`[host]:port`, sam-mx's `:25`) + * rather than a bare port: the port is the part after the last ':'. + */ +export const BOX_LISTEN_ADDRESSES: readonly string[] = ['SAM_MX_LISTEN']; + +/** + * Listeners of services that run with no capability (docker-compose.yml cap_drop: [ALL]), so + * they cannot bind a privileged port. + */ +const UNPRIVILEGED_LISTENERS: readonly string[] = [ + 'CELLD_PORT', + 'CELLD_INTERNAL_PORT', + 'FRPS_BIND_PORT', + 'MAIL_COLLECTOR_SMTP_PORT', + 'MAIL_COLLECTOR_UI_PORT', +]; + /** * The box settings with the port values docker compose will actually run with. Compose takes a * variable from the shell before the .env file, so `CELLD_INTERNAL_PORT=20001 docker compose up` @@ -64,6 +87,26 @@ export function withComposePortOverrides( return { box: effective, overridden }; } +/** + * The box .env as docker compose will run it (`withComposePortOverrides`; `onOverride` hears each + * shell override first), checked before anything starts: a box listener inside the lease range + * (resolveTunnelPortRange) fails here, so `selfhost:deploy` and `selfhost:upgrade` stop before + * they write state or run docker compose, not only later inside Caddy's start.sh. + */ +export function loadBoxEnv( + envFile: string, + hostEnv: NodeJS.ProcessEnv = process.env, + onOverride: (name: string) => void = () => {} +): Record { + const { box, overridden } = withComposePortOverrides( + parseDotenv(readFileSync(envFile, 'utf8'), envFile), + hostEnv + ); + overridden.forEach(onOverride); + resolveTunnelPortRange(box); + return box; +} + export interface PortRange { start: number; end: number; @@ -92,6 +135,18 @@ function integer( const PORT = { min: 1024, max: 65535 }; +/** A box listener's port (BOX_RESERVED_PORTS), from the setting or its compose default. */ +function boxPort(box: Readonly>, name: string, fallback: number): number { + const raw = box[name]; + const bounds = UNPRIVILEGED_LISTENERS.includes(name) ? PORT : { min: 1, max: 65535 }; + if (!BOX_LISTEN_ADDRESSES.includes(name) || raw === undefined || raw === '') { + return integer(raw, fallback, name, bounds); + } + const port = raw.slice(raw.lastIndexOf(':') + 1); + if (port === '') throw new Error(`${name} must end in :, got ${raw}`); + return integer(port, fallback, name, bounds); +} + export function resolveTunnelPortRange(box: Readonly>): PortRange { const start = integer( box.REVERSE_TUNNEL_PORT_RANGE_START, @@ -112,7 +167,7 @@ export function resolveTunnelPortRange(box: Readonly>): P ); } for (const [name, fallback] of Object.entries(BOX_RESERVED_PORTS)) { - const port = integer(box[name], fallback, name, { min: 1, max: 65535 }); + const port = boxPort(box, name, fallback); if (port >= start && port <= end) { throw new Error( `REVERSE_TUNNEL_PORT_RANGE ${start}-${end} contains ${name} (${port}); a node could bind it` diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts index 9915c4621c..c74e7f69aa 100644 --- a/scripts/selfhost/caddy-start.test.ts +++ b/scripts/selfhost/caddy-start.test.ts @@ -15,7 +15,7 @@ import { join, resolve } from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; -import { BOX_RESERVED_PORTS } from './box-settings.js'; +import { BOX_LISTEN_ADDRESSES, BOX_RESERVED_PORTS } from './box-settings.js'; const START = resolve(import.meta.dirname, '../../deploy/selfhost/caddy/start.sh'); let bin: string; @@ -32,7 +32,10 @@ afterAll(() => rmSync(bin, { recursive: true, force: true })); function composeEnv(): Record { return { ...Object.fromEntries( - Object.entries(BOX_RESERVED_PORTS).map(([name, port]) => [name, String(port)]) + Object.entries(BOX_RESERVED_PORTS).map(([name, port]) => [ + name, + BOX_LISTEN_ADDRESSES.includes(name) ? `:${port}` : String(port), + ]) ), REVERSE_TUNNEL_PORT_RANGE_START: '20000', REVERSE_TUNNEL_PORT_RANGE_END: '29999', @@ -68,6 +71,30 @@ describe('caddy/start.sh', () => { } ); + // sam-mx's listen address: the port after the last ':' is checked, with or without a host. + it.each([':20001', '0.0.0.0:20001', '[::]:20001'])( + 'refuses SAM_MX_LISTEN=%s inside the lease range', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status).toBe(64); + expect(run.out).toContain('SAM_MX_LISTEN (20001) lies inside the reverse-tunnel range'); + } + ); + + // A malformed bound used to make `[ -ge ]` error, which `if` reads as false: the range check + // was skipped and Caddy started with a box port inside the real range. + it.each([ + { REVERSE_TUNNEL_PORT_RANGE_START: '1:2' }, + { REVERSE_TUNNEL_PORT_RANGE_END: '29999:1' }, + { REVERSE_TUNNEL_PORT_RANGE_START: '20000x' }, + { REVERSE_TUNNEL_PORT_RANGE_END: ' 29999' }, + ])('refuses a malformed lease range %j instead of skipping the check', (bad) => { + const run = startSh({ ...composeEnv(), CELLD_INTERNAL_PORT: '20001', ...bad }); + expect(run.status).toBe(64); + expect(run.out).toMatch(/RANGE_START\/END missing from gateway.env or not a number/); + expect(run.out).not.toContain('caddy run'); + }); + it('accepts the range edges just outside a port (control)', () => { const run = startSh({ ...composeEnv(), diff --git a/scripts/selfhost/deploy-steps.ts b/scripts/selfhost/deploy-steps.ts index 4290d5bce5..6de64cc26c 100644 --- a/scripts/selfhost/deploy-steps.ts +++ b/scripts/selfhost/deploy-steps.ts @@ -2,7 +2,7 @@ * Small steps of `pnpm selfhost:deploy` (deploy.ts), kept apart so the orchestration stays short. */ import { existsSync, readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { join, resolve } from 'node:path'; import { BOX_RESERVED_PORTS, gatewayEnvAction } from './box-settings.js'; import type { CelldWranglerConfig } from './celld-config.js'; @@ -10,6 +10,8 @@ import { replacePrivateFile } from './secret-files.js'; /** The repository checkout the self-host scripts run from. */ export const REPO_ROOT = resolve(import.meta.dirname, '../..'); +/** The box's compose project: docker-compose.yml, its .env, caddy/, frps/. */ +export const SELFHOST_DIR = join(REPO_ROOT, 'deploy/selfhost'); /** Progress output of the self-host scripts. */ export function log(message: string): void { diff --git a/scripts/selfhost/deploy.test.ts b/scripts/selfhost/deploy.test.ts index 7d1e723d2a..b220734692 100644 --- a/scripts/selfhost/deploy.test.ts +++ b/scripts/selfhost/deploy.test.ts @@ -170,8 +170,19 @@ describe('selfhost:deploy', { timeout: CHILD_TEST_TIMEOUT_MS }, () => { expect(refused.out).toContain('CELLD_INTERNAL_PORT from the shell environment overrides'); expect(refused.out).toMatch(/contains CELLD_INTERNAL_PORT \(20001\); a node could bind it/); expect(existsSync(join(state, 'gateway.env'))).toBe(false); + // Refused when the box is read, before anything is written (S4). + expect(existsSync(join(state, PLATFORM_KEYS_FILE))).toBe(false); // Control: the same box without the override initialises. const init = await runDeploy(envFile, ['--init']); expect(init.status, init.out).toBe(0); }); + + // S4: sam-mx's public port (SAM_MX_LISTEN, a listen address) is a box listener too. + it('refuses SAM_MX_LISTEN inside the lease range before writing anything', async () => { + const refused = await runDeploy(writeBox(dir, ['SAM_MX_LISTEN=:20025']), ['--init']); + expect(refused.status).not.toBe(0); + expect(refused.out).toMatch(/contains SAM_MX_LISTEN \(20025\); a node could bind it/); + expect(existsSync(join(state, PLATFORM_KEYS_FILE))).toBe(false); + expect(existsSync(join(state, 'gateway.env'))).toBe(false); + }); }); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 859c5b8d01..2823bff2fa 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -46,6 +46,7 @@ import type { WranglerToml } from '../deploy/types.js'; import { assertPresignCredentialIsScoped, celldChildEnv, + loadBoxEnv, presignVars, redactSecrets, renderGatewayEnv, @@ -53,7 +54,6 @@ import { STORAGE_SECRET_KEYS, type TunnelSettings, tunnelWorkerVars, - withComposePortOverrides, } from './box-settings.js'; import { verifyNewVersionServes } from './celld-adopt.js'; import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; @@ -75,6 +75,7 @@ import { log, redact, REPO_ROOT, + SELFHOST_DIR, syncGatewayEnv, } from './deploy-steps.js'; import { inboundMailWorkerVars } from './inbound-mail-settings.js'; @@ -92,12 +93,7 @@ import { type PlatformKeysMode, type PlatformKeysResult, } from './platform-keys.js'; -import { - assertPrivateFile, - ensurePrivateDir, - parseDotenv, - readSecretsFile, -} from './secret-files.js'; +import { assertPrivateFile, ensurePrivateDir, readSecretsFile } from './secret-files.js'; import { buildVmAgentBinaries, publishVmAgentArtifacts, @@ -190,15 +186,14 @@ function readDeployInputs(): DeployInputs { 'skip-vm-agent': { type: 'boolean', default: false }, }, }); - const envFile = resolve(values['env-file'] ?? join(REPO_ROOT, 'deploy/selfhost/.env')); + const envFile = resolve(values['env-file'] ?? join(SELFHOST_DIR, '.env')); // The .env holds the bucket credential, which can read every deployed secret. assertPrivateFile(envFile); - // Box ports as docker compose will run them: a shell override beats the .env (F21 L5). - const { box, overridden } = withComposePortOverrides( - parseDotenv(readFileSync(envFile, 'utf8'), envFile), - process.env + // Box ports as docker compose will run them (a shell override beats the .env, F21 L5), checked + // against the lease range before anything is written. + const box = loadBoxEnv(envFile, process.env, (name) => + log(`${name} from the shell environment overrides ${envFile}`) ); - for (const name of overridden) log(`${name} from the shell environment overrides ${envFile}`); // Same default and base directory docker compose uses for SAM_SELFHOST_STATE_DIR. const stateDir = resolve( dirname(envFile), diff --git a/scripts/selfhost/image-rebuilds.ts b/scripts/selfhost/image-rebuilds.ts index 4adf8f31ca..799e242b9c 100644 --- a/scripts/selfhost/image-rebuilds.ts +++ b/scripts/selfhost/image-rebuilds.ts @@ -3,12 +3,14 @@ * run `docker compose up -d --build` whenever any compose input changed; a build fetches base * images and modules from the network, so it now runs only for a service whose image would differ. */ -import { posix } from 'node:path'; +import { join, posix, relative } from 'node:path'; import { parse as parseYaml } from 'yaml'; +import { REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; + /** The compose file, relative to the repository root (what `git show :` reads). */ -export const COMPOSE_PATH = 'deploy/selfhost/docker-compose.yml'; +export const COMPOSE_PATH = relative(REPO_ROOT, join(SELFHOST_DIR, 'docker-compose.yml')); interface ComposeBuildService { build?: string | { context?: string; dockerfile?: string; args?: unknown }; diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts index 9cbfd84814..44be84b9fa 100644 --- a/scripts/selfhost/live/harness.ts +++ b/scripts/selfhost/live/harness.ts @@ -14,6 +14,7 @@ import { FRPC_DOWNLOAD_BASE_URL, FRPC_RELEASES, } from '../../../packages/cloud-init/src/reverse-tunnel'; +import { BOX_RESERVED_PORTS } from '../box-settings.js'; export const REPO_ROOT = resolve(import.meta.dirname, '../../..'); /** Gitignored scratch directory (see .tmp/README.md). */ @@ -109,24 +110,15 @@ export const LIVE_TUNNEL_RANGE = { start: 20000, end: 20099 }; /** * Every setting caddy/start.sh checks, on free ports: each box port docker-compose.yml passes - * and the lease range from gateway.env. Callers override what their test probes. + * (BOX_RESERVED_PORTS; a bare port is also a valid listen address for SAM_MX_LISTEN) and the lease + * range from gateway.env. Callers override what their test probes. */ export async function caddyBoxEnv(): Promise> { const env: Record = { REVERSE_TUNNEL_PORT_RANGE_START: String(LIVE_TUNNEL_RANGE.start), REVERSE_TUNNEL_PORT_RANGE_END: String(LIVE_TUNNEL_RANGE.end), }; - for (const name of [ - 'HTTP_PORT', - 'HTTPS_PORT', - 'CELLD_PORT', - 'CELLD_INTERNAL_PORT', - 'FRPS_BIND_PORT', - 'OBJECTSTORE_PORT', - 'OBJECTSTORE_CONSOLE_PORT', - 'MAIL_COLLECTOR_SMTP_PORT', - 'MAIL_COLLECTOR_UI_PORT', - ]) { + for (const name of Object.keys(BOX_RESERVED_PORTS)) { env[name] = String(await freePort()); } return env; diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 21cf4e6226..8f6ecae018 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -35,12 +35,10 @@ import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; -import { withComposePortOverrides } from './box-settings.js'; -import { log, REPO_ROOT } from './deploy-steps.js'; +import { loadBoxEnv } from './box-settings.js'; +import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; -import { assertPrivateFile, parseDotenv, replacePrivateFile } from './secret-files.js'; - -export const SELFHOST_DIR = join(REPO_ROOT, 'deploy/selfhost'); +import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; /** Suffix of the files under .state/ that docker compose services read (`env_file`). */ const GENERATED_STATE_FILE_SUFFIX = '.env'; @@ -137,11 +135,9 @@ export function loadBox( ): BoxContext { if (!existsSync(envFile)) throw new Error(`${envFile} does not exist`); assertPrivateFile(envFile); - // Ports as docker compose runs them (a shell override beats the .env), as deploy.ts reads them. - const { box } = withComposePortOverrides( - parseDotenv(readFileSync(envFile, 'utf8'), envFile), - process.env - ); + // Ports as docker compose runs them (a shell override beats the .env), as deploy.ts reads them, + // and checked against the lease range before the upgrade touches the checkout or the stack. + const box = loadBoxEnv(envFile); if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); return { box, diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 16a6446494..ca099c5947 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -12,6 +12,7 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { SELFHOST_DIR } from './deploy-steps.js'; import { imageRebuilds } from './image-rebuilds.js'; import { type BoxContext, @@ -19,7 +20,6 @@ import { loadBox, type RunResult, runUpgrade, - SELFHOST_DIR, UPGRADE_PENDING_FILE, } from './upgrade-lib.js'; @@ -292,6 +292,28 @@ describe('runUpgrade', () => { // Seen on a box, 2026-11-12: .env had COMPOSE_FILE listing an override file. The upgrade's // `docker compose -f docker-compose.yml up -d --build` replaced that list and recreated celld // without what the override added. +// S4: the box's ports are checked against the lease range when the upgrade loads the box, before it +// fetches, checks out or runs docker compose (not only inside Caddy's start.sh once it is up). +describe('loadBox refuses a box port inside the lease range', () => { + const envWith = (line: string) => { + const envFile = join(root, 'ports.env'); + writeFileSync(envFile, `CELLD_BUCKET=gs://fleet/celld\n${line}\n`, { mode: 0o600 }); + return envFile; + }; + + it.each(['SAM_MX_LISTEN=:20025', 'CELLD_INTERNAL_PORT=20001'])('%s', (line) => { + expect(() => loadBox(envWith(line), join(root, 'state'))).toThrow( + /REVERSE_TUNNEL_PORT_RANGE 20000-29999 contains/ + ); + }); + + it('control: the default listeners load', () => { + expect(loadBox(envWith('SAM_MX_LISTEN=:25'), join(root, 'state')).box.SAM_MX_LISTEN).toBe( + ':25' + ); + }); +}); + describe('runUpgrade with the box .env COMPOSE_FILE', () => { const boxFromEnv = (lines: string[]): BoxContext => { const envFile = join(root, 'real.env'); diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index 0049a50a6b..a45bf8b0d6 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -10,8 +10,8 @@ import { join, resolve } from 'node:path'; import { parseArgs } from 'node:util'; -import { celldPort } from './deploy-steps.js'; -import { loadBox, runUpgrade, SELFHOST_DIR } from './upgrade-lib.js'; +import { celldPort, SELFHOST_DIR } from './deploy-steps.js'; +import { loadBox, runUpgrade } from './upgrade-lib.js'; const { values } = parseArgs({ options: { From 73a3bf2ec136f44ad5e2a0ee14298d3448a4bffc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 07:57:33 +0000 Subject: [PATCH 15/65] fix(selfhost): strip client X-SAM-* headers on every route, not only node sockets A site-level request_header -X-SAM-* sorts before every handle, so the catch-all route to celld drops them too, and node-ws.caddy's forward_auth still copies the Worker's own X-SAM-* answer afterwards (the live forward_auth tests pass unchanged). A live test sends forged X-SAM-* headers to api, app and a preview host and checks celld sees none; it fails with the directive removed. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/caddy/Caddyfile | 6 ++++++ scripts/selfhost/caddy-logging-compose.test.ts | 9 +++++++++ .../selfhost/live/caddy-fragments.live.test.ts | 16 ++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/deploy/selfhost/caddy/Caddyfile b/deploy/selfhost/caddy/Caddyfile index 0e2e473abc..91940357f1 100644 --- a/deploy/selfhost/caddy/Caddyfile +++ b/deploy/selfhost/caddy/Caddyfile @@ -42,6 +42,12 @@ # celld never compresses responses. encode zstd gzip + # Client-supplied X-SAM-* headers (SAM's gateway routing and credential headers) never reach + # celld or a node, on any route, the catch-all below included. `request_header` sorts before + # every `handle`, so this runs before node-ws.caddy's forward_auth copies the Worker's own + # X-SAM-* answer onto the request. + request_header -X-SAM-* + # The mail collector's UI on its own host when the `mail-collector` profile is on # (caddy/start.sh); an empty file otherwise. import mail-collector/{$SAM_MAIL_COLLECTOR:off}.caddy diff --git a/scripts/selfhost/caddy-logging-compose.test.ts b/scripts/selfhost/caddy-logging-compose.test.ts index 6594570489..eb44b5f76c 100644 --- a/scripts/selfhost/caddy-logging-compose.test.ts +++ b/scripts/selfhost/caddy-logging-compose.test.ts @@ -62,6 +62,15 @@ describe('Caddy logging and keep-warm wiring', () => { expect(redaction).toContain('\t\tregexp "^/p/[^?]*" "/p/"'); }); + // Proven on the real image in live/caddy-fragments.live.test.ts; pinned here so a compose-only + // CI run notices it moving into a handle block or after the fragments. + it('strips client X-SAM-* headers at site level, before the sam.d routes', () => { + const site = caddyfile.slice(caddyfile.indexOf('*.{$SAM_DOMAIN} {')); + const strip = site.indexOf('\n\trequest_header -X-SAM-*\n'); + expect(strip).toBeGreaterThan(0); + expect(strip).toBeLessThan(site.indexOf('import sam.d/*.caddy')); + }); + it('keeps the keep-warm check on a route that never serves a request', () => { expect(caddyfile).toContain('import keep-warm/{$SAM_KEEP_WARM:on}.caddy'); expect(keepWarm).toMatch(/^@sam_keep_warm expression false$/m); diff --git a/scripts/selfhost/live/caddy-fragments.live.test.ts b/scripts/selfhost/live/caddy-fragments.live.test.ts index b84cd8c9c2..758ee17c5d 100644 --- a/scripts/selfhost/live/caddy-fragments.live.test.ts +++ b/scripts/selfhost/live/caddy-fragments.live.test.ts @@ -379,6 +379,22 @@ const FORGED = { const forwardAuth = () => celldSeen.filter((seen) => seen.url.startsWith('/api/self-host/gateway/node-websocket')); +describe('client X-SAM-* headers on ordinary routes', () => { + it.each(['api', 'app', `ws-${WORKSPACE}--3000`])( + 'never reach celld through the catch-all route (%s)', + async (host) => { + const reply = await send(host, '/api/projects', { ...FORGED, 'X-Other': 'kept' }); + expect(reply.status).toBe(200); + // Liveness: the request reached celld, with an ordinary header intact. + expect(celldSeen).toHaveLength(1); + expect(celldSeen[0]?.headers['x-other']).toBe('kept'); + expect( + Object.keys(celldSeen[0]?.headers ?? {}).filter((h) => h.startsWith('x-sam-')) + ).toEqual([]); + } + ); +}); + describe('forward_auth for node WebSockets', () => { it.each([WS_HOST, PORT_HOST])( 'strips client X-SAM-* headers before forward_auth and passes a refusal through (%s)', From f4224035c5809ab7d1e532b2be523897f5a9a2db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:04:03 +0000 Subject: [PATCH 16/65] test(selfhost): one Caddy runner, HTTPS client and Docker skip rule for the live suite A3: caddy-fragments, access-log-keep-warm and mail-collector each built the same docker run (host network, cap-drop ALL + NET_BIND_SERVICE, the caddy dir, start.sh), logs reader, TLS wait, teardown and https client. harness.ts now has startCaddy, runCaddyToExit and httpsGet; DOCKER and hasDocker move there from celld-lab.ts and every docker call uses DOCKER; every Docker test uses skipWithoutDocker (skipped without Docker locally, never in CI). celld-lab.ts's header names its real consumers, and celld-redirect writes its project with writeProject. S6: start() and celld deploy pass children an allowlisted environment (PATH, HOME, TMPDIR, LANG, RUST_LOG, DOCKER_*) instead of the whole host environment. Co-Authored-By: Claude Opus 5.5 --- .../live/access-log-keep-warm.live.test.ts | 360 ++++----- .../live/caddy-fragments.live.test.ts | 725 ++++++++---------- scripts/selfhost/live/celld-lab.ts | 24 +- .../selfhost/live/celld-redirect.live.test.ts | 14 +- scripts/selfhost/live/harness.ts | 175 ++++- .../selfhost/live/mail-collector.live.test.ts | 492 ++++++------ .../live/shared-flight-cancel.live.test.ts | 18 +- 7 files changed, 888 insertions(+), 920 deletions(-) diff --git a/scripts/selfhost/live/access-log-keep-warm.live.test.ts b/scripts/selfhost/live/access-log-keep-warm.live.test.ts index 3377aa1ef2..f1d6b25598 100644 --- a/scripts/selfhost/live/access-log-keep-warm.live.test.ts +++ b/scripts/selfhost/live/access-log-keep-warm.live.test.ts @@ -11,25 +11,25 @@ * sends nothing, and start.sh refuses invalid keep-warm and frp rate-limit settings and a box * port inside the reverse-tunnel lease range. */ -import { execFileSync, spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { createServer, type Server } from 'node:http'; -import { request as httpsRequest } from 'node:https'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { caddyBoxEnv, - caddyImage, + type CaddyRun, freePort, + httpsGet, LIVE_TUNNEL_RANGE, - REPO_ROOT, + runCaddyToExit, + skipWithoutDocker, sleep, + startCaddy as startBoxCaddy, waitFor, } from './harness'; const DOMAIN = 'sam.test'; -const CADDY_DIR = `${REPO_ROOT}/deploy/selfhost/caddy`; const GATEWAY_SECRET = `gw${randomBytes(24).toString('hex')}`; const SECRETS = { cookie: `ck${randomBytes(12).toString('hex')}`, @@ -44,12 +44,7 @@ interface Hit { url: string; } -interface Stack { - container: string; - https: number; - stdout: () => string; - stderr: () => string; -} +type Stack = CaddyRun; let celld: Server; let celldPort = 0; @@ -57,28 +52,6 @@ let healthStatus = 200; const hits: Hit[] = []; const stacks: Stack[] = []; -function caddyArgs(name: string, env: Record): string[] { - return [ - 'run', - '-d', - '--name', - name, - '--network', - 'host', - '-v', - `${CADDY_DIR}:/etc/caddy:ro`, - '--cap-drop', - 'ALL', - '--cap-add', - 'NET_BIND_SERVICE', - '--entrypoint', - '/bin/sh', - ...Object.entries(env).flatMap(([key, value]) => ['-e', `${key}=${value}`]), - caddyImage(), - '/etc/caddy/start.sh', - ]; -} - async function baseEnv(extra: Record): Promise> { return { ...(await caddyBoxEnv()), @@ -91,56 +64,13 @@ async function baseEnv(extra: Record): Promise): Promise { - const env = await baseEnv(extra); - const container = `sam-live-log-${randomBytes(4).toString('hex')}`; - execFileSync('docker', caddyArgs(container, env)); - const read = () => spawnSync('docker', ['logs', container], { encoding: 'utf8' }); - const stack: Stack = { - container, - https: Number(env.HTTPS_PORT), - stdout: () => read().stdout ?? '', - stderr: () => read().stderr ?? '', - }; + const stack = await startBoxCaddy(await baseEnv(extra)); stacks.push(stack); - await waitFor( - 'Caddy to serve TLS', - async () => { - try { - // Any HTTP answer means Caddy serves TLS; a stack whose upstream is down answers 502. - return (await get(stack, `app.${DOMAIN}`, '/ready')).status > 0; - } catch { - return false; - } - }, - 120_000, - stack.stderr - ); return stack; } -function get( - stack: Stack, - host: string, - path: string, - headers: Record = {} -): Promise<{ status: number }> { - return new Promise((done, fail) => { - const req = httpsRequest({ - host: '127.0.0.1', - port: stack.https, - servername: host, - rejectUnauthorized: false, - path, - headers: { Host: host, ...headers }, - }); - req.on('response', (res) => { - res.resume(); - res.on('end', () => done({ status: res.statusCode ?? 0 })); - }); - req.on('error', fail); - req.end(); - }); -} +const get = (stack: Stack, host: string, path: string, headers: Record = {}) => + httpsGet(stack.https, host, path, headers); function accessLines(stack: Stack): Array> { return stack @@ -152,162 +82,162 @@ function accessLines(stack: Stack): Array> { /** Removes every running stack, so pings counted next come only from the stack a test starts. */ function stopStacks(): void { - for (const stack of stacks.splice(0)) spawnSync('docker', ['rm', '-f', stack.container]); + for (const stack of stacks.splice(0)) stack.stop(); } function healthHitsSince(start: number): Hit[] { return hits.slice(start).filter((hit) => hit.url === '/health'); } -beforeAll(async () => { - celldPort = await freePort(); - celld = createServer((req, res) => { - hits.push({ host: req.headers.host ?? '', url: req.url ?? '' }); - if (req.url === '/health') { - res.statusCode = healthStatus; - res.end('health'); - return; - } - res.setHeader('Set-Cookie', `session=${SECRETS.responseCookie}`); - res.end('celld'); +// Needs Docker (harness skipWithoutDocker: skipped without it locally, never in CI). +describe.skipIf(skipWithoutDocker)('Caddy access log and keep-warm (live)', () => { + beforeAll(async () => { + celldPort = await freePort(); + celld = createServer((req, res) => { + hits.push({ host: req.headers.host ?? '', url: req.url ?? '' }); + if (req.url === '/health') { + res.statusCode = healthStatus; + res.end('health'); + return; + } + res.setHeader('Set-Cookie', `session=${SECRETS.responseCookie}`); + res.end('celld'); + }); + await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); }); - await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); -}); - -afterAll(async () => { - for (const stack of stacks) spawnSync('docker', ['rm', '-f', stack.container]); - await new Promise((done) => celld.close(() => done())); -}); -describe('access log', () => { - let stack: Stack; - beforeAll(async () => { - stack = await startCaddy({ SAM_KEEP_WARM: 'off' }); + afterAll(async () => { + for (const stack of stacks) stack.stop(); + await new Promise((done) => celld.close(() => done())); }); - it('logs one line per request with host, path, status and duration, and nothing secret', async () => { - const reply = await get(stack, `app.${DOMAIN}`, `/api/projects?token=${SECRETS.query}&x=1`, { - Cookie: `__Secure-better-auth.session_token=${SECRETS.cookie}`, - Authorization: `Bearer ${SECRETS.bearer}`, - 'X-SAM-Upstream-Authorization': SECRETS.samHeader, + describe('access log', () => { + let stack: Stack; + beforeAll(async () => { + stack = await startCaddy({ SAM_KEEP_WARM: 'off' }); }); - expect(reply.status).toBe(200); - // Liveness: the request did reach celld with its query, so redaction is in the log only. - expect(hits.some((hit) => hit.url.includes(SECRETS.query))).toBe(true); - - let line: Record | undefined; - await waitFor( - 'the access-log line', - async () => { - line = accessLines(stack).find((entry) => JSON.stringify(entry).includes('/api/projects')); - return line !== undefined; - }, - 10_000, - stack.stderr - ); - const request = line!.request as Record; - expect(request.host).toBe(`app.${DOMAIN}`); - expect(request.method).toBe('GET'); - expect(request.uri).toBe('/api/projects?'); - expect(request.headers).toBeUndefined(); - expect(line!.resp_headers).toBeUndefined(); - expect(line!.status).toBe(200); - expect(typeof line!.duration).toBe('number'); - const everything = stack.stdout() + stack.stderr(); - for (const secret of [...Object.values(SECRETS), GATEWAY_SECRET]) { - expect(everything).not.toContain(secret); - } - }); - - it('replaces a credential carried in the path, and leaves other paths alone', async () => { - const token = `pt${randomBytes(12).toString('hex')}`; - const cases: Array<[string, string, string]> = [ - [ - `api.${DOMAIN}`, - `/ai/proxy/${token}/anthropic/v1/messages`, - '/ai/proxy//anthropic/v1/messages', - ], - [`api.${DOMAIN}`, `/api/bootstrap/${token}`, '/api/bootstrap/'], - [ - `api.${DOMAIN}`, - `/api/projects/invite-links/${token}/request?x=1`, - '/api/projects/invite-links//request?', - ], - [`app.${DOMAIN}`, `/projects/invite/${token}`, '/projects/invite/'], - [`preview.${DOMAIN}`, `/p/proj/file/1/9999/${token}/index.html`, '/p/'], - [`api.${DOMAIN}`, '/api/projects/p1/sessions', '/api/projects/p1/sessions'], - ]; - for (const [host, path] of cases) expect((await get(stack, host, path)).status).toBe(200); - await waitFor('every path-case line', async () => { - const uris = accessLines(stack).map((line) => (line.request as { uri?: string }).uri); - return cases.every(([, , logged]) => uris.includes(logged)); + it('logs one line per request with host, path, status and duration, and nothing secret', async () => { + const reply = await get(stack, `app.${DOMAIN}`, `/api/projects?token=${SECRETS.query}&x=1`, { + Cookie: `__Secure-better-auth.session_token=${SECRETS.cookie}`, + Authorization: `Bearer ${SECRETS.bearer}`, + 'X-SAM-Upstream-Authorization': SECRETS.samHeader, + }); + expect(reply.status).toBe(200); + // Liveness: the request did reach celld with its query, so redaction is in the log only. + expect(hits.some((hit) => hit.url.includes(SECRETS.query))).toBe(true); + + let line: Record | undefined; + await waitFor( + 'the access-log line', + async () => { + line = accessLines(stack).find((entry) => + JSON.stringify(entry).includes('/api/projects') + ); + return line !== undefined; + }, + 10_000, + stack.stderr + ); + const request = line!.request as Record; + expect(request.host).toBe(`app.${DOMAIN}`); + expect(request.method).toBe('GET'); + expect(request.uri).toBe('/api/projects?'); + expect(request.headers).toBeUndefined(); + expect(line!.resp_headers).toBeUndefined(); + expect(line!.status).toBe(200); + expect(typeof line!.duration).toBe('number'); + + const everything = stack.stdout() + stack.stderr(); + for (const secret of [...Object.values(SECRETS), GATEWAY_SECRET]) { + expect(everything).not.toContain(secret); + } }); - // Liveness: the token reached celld unchanged; only the log is redacted. - expect(hits.filter((hit) => hit.url.includes(token))).toHaveLength(5); - expect(stack.stdout() + stack.stderr()).not.toContain(token); - }); - it('redacts the query of a proxy-error entry in Caddy own log', async () => { - const down = await startCaddy({ SAM_KEEP_WARM: 'off', CELLD_PORT: String(await freePort()) }); - expect((await get(down, `api.${DOMAIN}`, `/x?t=${SECRETS.query}`)).status).toBe(502); - await waitFor('the proxy error entry', async () => down.stderr().includes('/x?')); - expect(down.stdout() + down.stderr()).not.toContain(SECRETS.query); - }); -}); + it('replaces a credential carried in the path, and leaves other paths alone', async () => { + const token = `pt${randomBytes(12).toString('hex')}`; + const cases: Array<[string, string, string]> = [ + [ + `api.${DOMAIN}`, + `/ai/proxy/${token}/anthropic/v1/messages`, + '/ai/proxy//anthropic/v1/messages', + ], + [`api.${DOMAIN}`, `/api/bootstrap/${token}`, '/api/bootstrap/'], + [ + `api.${DOMAIN}`, + `/api/projects/invite-links/${token}/request?x=1`, + '/api/projects/invite-links//request?', + ], + [`app.${DOMAIN}`, `/projects/invite/${token}`, '/projects/invite/'], + [`preview.${DOMAIN}`, `/p/proj/file/1/9999/${token}/index.html`, '/p/'], + [`api.${DOMAIN}`, '/api/projects/p1/sessions', '/api/projects/p1/sessions'], + ]; + for (const [host, path] of cases) expect((await get(stack, host, path)).status).toBe(200); + await waitFor('every path-case line', async () => { + const uris = accessLines(stack).map((line) => (line.request as { uri?: string }).uri); + return cases.every(([, , logged]) => uris.includes(logged)); + }); + // Liveness: the token reached celld unchanged; only the log is redacted. + expect(hits.filter((hit) => hit.url.includes(token))).toHaveLength(5); + expect(stack.stdout() + stack.stderr()).not.toContain(token); + }); -describe('keep-warm', () => { - beforeEach(stopStacks); - it('sends GET /health on the API host while idle', async () => { - const start = hits.length; - await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); - await waitFor('three keep-warm pings', async () => healthHitsSince(start).length >= 3); - expect(healthHitsSince(start).every((hit) => hit.host === `api.${DOMAIN}`)).toBe(true); + it('redacts the query of a proxy-error entry in Caddy own log', async () => { + const down = await startCaddy({ SAM_KEEP_WARM: 'off', CELLD_PORT: String(await freePort()) }); + expect((await get(down, `api.${DOMAIN}`, `/x?t=${SECRETS.query}`)).status).toBe(502); + await waitFor('the proxy error entry', async () => down.stderr().includes('/x?')); + expect(down.stdout() + down.stderr()).not.toContain(SECRETS.query); + }); }); - it('a failing /health leaves real traffic untouched', async () => { - const stack = await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); - healthStatus = 503; - try { + describe('keep-warm', () => { + beforeEach(stopStacks); + it('sends GET /health on the API host while idle', async () => { const start = hits.length; - await waitFor('two failed pings', async () => healthHitsSince(start).length >= 2); - for (let i = 0; i < 3; i++) { - expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); + await waitFor('three keep-warm pings', async () => healthHitsSince(start).length >= 3); + expect(healthHitsSince(start).every((hit) => hit.host === `api.${DOMAIN}`)).toBe(true); + }); + + it('a failing /health leaves real traffic untouched', async () => { + const stack = await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); + healthStatus = 503; + try { + const start = hits.length; + await waitFor('two failed pings', async () => healthHitsSince(start).length >= 2); + for (let i = 0; i < 3; i++) { + expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + } + } finally { + healthStatus = 200; } - } finally { - healthStatus = 200; - } - }); + }); - it('SAM_KEEP_WARM=off sends nothing', async () => { - const stack = await startCaddy({ SAM_KEEP_WARM: 'off', SAM_KEEP_WARM_INTERVAL: '1s' }); - const start = hits.length; - await sleep(3_500); - expect(healthHitsSince(start)).toEqual([]); - // Liveness: this Caddy is serving. - expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); - }); + it('SAM_KEEP_WARM=off sends nothing', async () => { + const stack = await startCaddy({ SAM_KEEP_WARM: 'off', SAM_KEEP_WARM_INTERVAL: '1s' }); + const start = hits.length; + await sleep(3_500); + expect(healthHitsSince(start)).toEqual([]); + // Liveness: this Caddy is serving. + expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + }); - it.each([ - [{ SAM_KEEP_WARM: 'yes' }, /SAM_KEEP_WARM must be on or off/], - [{ SAM_KEEP_WARM_INTERVAL: '7s' }, /SAM_KEEP_WARM_INTERVAL must be 1s to 6s/], - [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '0' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], - [{ SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '2d' }, /SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be/], - // A shell override handed straight to docker compose (F21 L5): celld's operator port inside - // the lease range the deploy wrote to gateway.env. - [ - { CELLD_INTERNAL_PORT: String(LIVE_TUNNEL_RANGE.start + 1) }, - /CELLD_INTERNAL_PORT \(20001\) lies inside the reverse-tunnel range 20000-20099/, - ], - [{ REVERSE_TUNNEL_PORT_RANGE_END: '' }, /REVERSE_TUNNEL_PORT_RANGE_START\/END missing/], - ])('start.sh refuses %j', async (extra, message) => { - const container = `sam-live-log-${randomBytes(4).toString('hex')}`; - const run = spawnSync( - 'docker', - caddyArgs(container, await baseEnv(extra)).map((arg) => (arg === '-d' ? '--rm' : arg)), - { encoding: 'utf8', timeout: 60_000 } - ); - expect(run.status).toBe(64); - expect(run.stderr).toMatch(message); + it.each([ + [{ SAM_KEEP_WARM: 'yes' }, /SAM_KEEP_WARM must be on or off/], + [{ SAM_KEEP_WARM_INTERVAL: '7s' }, /SAM_KEEP_WARM_INTERVAL must be 1s to 6s/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '0' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '2d' }, /SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be/], + // A shell override handed straight to docker compose (F21 L5): celld's operator port inside + // the lease range the deploy wrote to gateway.env. + [ + { CELLD_INTERNAL_PORT: String(LIVE_TUNNEL_RANGE.start + 1) }, + /CELLD_INTERNAL_PORT \(20001\) lies inside the reverse-tunnel range 20000-20099/, + ], + [{ REVERSE_TUNNEL_PORT_RANGE_END: '' }, /REVERSE_TUNNEL_PORT_RANGE_START\/END missing/], + ])('start.sh refuses %j', async (extra, message) => { + const run = runCaddyToExit(await baseEnv(extra)); + expect(run.status).toBe(64); + expect(run.stderr).toMatch(message); + }); }); }); diff --git a/scripts/selfhost/live/caddy-fragments.live.test.ts b/scripts/selfhost/live/caddy-fragments.live.test.ts index 758ee17c5d..13d98b84c6 100644 --- a/scripts/selfhost/live/caddy-fragments.live.test.ts +++ b/scripts/selfhost/live/caddy-fragments.live.test.ts @@ -16,7 +16,6 @@ * Image: the box's Caddy image, built from deploy/selfhost/caddy/Dockerfile as compose builds it, * started through start.sh with the frp rate limit lowered to FRP_LOGIN_LIMIT. */ -import { execFileSync } from 'node:child_process'; import { createHash, randomBytes } from 'node:crypto'; import { createServer, @@ -25,20 +24,26 @@ import { type OutgoingHttpHeaders, type Server, } from 'node:http'; -import { request as httpsRequest } from 'node:https'; import { posix } from 'node:path'; import type { Duplex } from 'node:stream'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { caddyBoxEnv, caddyImage, freePort, REPO_ROOT, waitFor } from './harness'; +import { + caddyBoxEnv, + type CaddyRun, + freePort, + httpsGet, + type HttpsReply, + skipWithoutDocker, + startCaddy, +} from './harness'; const DOMAIN = 'sam.test'; const SECRET = randomBytes(32).toString('hex'); const WORKSPACE = '01krrtliveaaaaaaaaaaaaaaaa'; const WS_HOST = `ws-${WORKSPACE}.${DOMAIN}`; const PORT_HOST = `ws-${WORKSPACE}--3000.${DOMAIN}`; -const CADDY_DIR = `${REPO_ROOT}/deploy/selfhost/caddy`; /** frp connections one address may open per minute in this run (the box default is 60). */ const FRP_LOGIN_LIMIT = 3; @@ -59,7 +64,7 @@ let celld: Server; let node: Server; let frps: Server; let ports: { https: number; http: number; celld: number; frps: number; node: number }; -let container = ''; +let caddy: CaddyRun | undefined; const record = (req: IncomingMessage): Seen => ({ method: req.method ?? '', @@ -73,436 +78,370 @@ function acceptKey(key: string | string[] | undefined): string { .digest('base64'); } -beforeAll(async () => { - ports = { - https: await freePort(), - http: await freePort(), - celld: await freePort(), - frps: await freePort(), - node: await freePort(), - }; - celld = createServer((req, res) => { - celldSeen.push(record(req)); - if (req.url?.startsWith('/api/self-host/gateway/node-websocket')) { - const { status, headers } = decide(req); - res.writeHead(status, headers); - res.end(); - return; - } - res.end('celld'); - }); - node = createServer((req, res) => { - nodeSeen.push(record(req)); - res.setHeader('Set-Cookie', 'node_cookie=1'); - res.end('node'); +// Needs Docker (harness skipWithoutDocker: skipped without it locally, never in CI). +describe.skipIf(skipWithoutDocker)('the box Caddy routes (live)', () => { + beforeAll(async () => { + ports = { + https: await freePort(), + http: await freePort(), + celld: await freePort(), + frps: await freePort(), + node: await freePort(), + }; + celld = createServer((req, res) => { + celldSeen.push(record(req)); + if (req.url?.startsWith('/api/self-host/gateway/node-websocket')) { + const { status, headers } = decide(req); + res.writeHead(status, headers); + res.end(); + return; + } + res.end('celld'); + }); + node = createServer((req, res) => { + nodeSeen.push(record(req)); + res.setHeader('Set-Cookie', 'node_cookie=1'); + res.end('node'); + }); + node.on('upgrade', (req: IncomingMessage, socket: Duplex) => { + nodeSeen.push(record(req)); + const extra = Object.entries(nodeUpgradeHeaders) + .map(([name, value]) => `${name}: ${value}\r\n`) + .join(''); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${acceptKey(req.headers['sec-websocket-key'])}\r\n${extra}\r\n` + ); + socket.end(); + }); + // Stands in for frps: plain HTTP is enough to see which /~!frp requests Caddy let through. + frps = createServer((req, res) => { + frpsSeen.push(record(req)); + res.end('frps'); + }); + await new Promise((done) => celld.listen(ports.celld, '127.0.0.1', done)); + await new Promise((done) => node.listen(ports.node, '127.0.0.1', done)); + await new Promise((done) => frps.listen(ports.frps, '127.0.0.1', done)); + + caddy = await startCaddy({ + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + HTTP_PORT: String(ports.http), + HTTPS_PORT: String(ports.https), + CELLD_PORT: String(ports.celld), + FRPS_BIND_PORT: String(ports.frps), + REVERSE_TUNNEL_GATEWAY_SECRET: SECRET, + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: String(FRP_LOGIN_LIMIT), + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '1m', + }); }); - node.on('upgrade', (req: IncomingMessage, socket: Duplex) => { - nodeSeen.push(record(req)); - const extra = Object.entries(nodeUpgradeHeaders) - .map(([name, value]) => `${name}: ${value}\r\n`) - .join(''); - socket.write( - 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' + - `Sec-WebSocket-Accept: ${acceptKey(req.headers['sec-websocket-key'])}\r\n${extra}\r\n` - ); - socket.end(); + + afterAll(async () => { + caddy?.stop(); + await new Promise((done) => (celld ? celld.close(() => done()) : done())); + await new Promise((done) => (node ? node.close(() => done()) : done())); + await new Promise((done) => (frps ? frps.close(() => done()) : done())); }); - // Stands in for frps: plain HTTP is enough to see which /~!frp requests Caddy let through. - frps = createServer((req, res) => { - frpsSeen.push(record(req)); - res.end('frps'); + + beforeEach(() => { + celldSeen.length = 0; + nodeSeen.length = 0; + frpsSeen.length = 0; + nodeUpgradeHeaders = {}; + decide = () => ({ status: 401 }); }); - await new Promise((done) => celld.listen(ports.celld, '127.0.0.1', done)); - await new Promise((done) => node.listen(ports.node, '127.0.0.1', done)); - await new Promise((done) => frps.listen(ports.frps, '127.0.0.1', done)); - container = `sam-live-caddy-${randomBytes(4).toString('hex')}`; - const env = { - ...(await caddyBoxEnv()), - SAM_DOMAIN: DOMAIN, - SAM_TLS_MODE: 'internal', - HTTP_PORT: String(ports.http), - HTTPS_PORT: String(ports.https), - CELLD_PORT: String(ports.celld), - FRPS_BIND_PORT: String(ports.frps), - REVERSE_TUNNEL_GATEWAY_SECRET: SECRET, - SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: String(FRP_LOGIN_LIMIT), - SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '1m', - }; - // As docker-compose.yml runs it: start.sh as the entrypoint, only NET_BIND_SERVICE. - execFileSync('docker', [ - 'run', - '-d', - '--rm', - '--name', - container, - '--network', - 'host', - '--cap-drop', - 'ALL', - '--cap-add', - 'NET_BIND_SERVICE', - '-v', - `${CADDY_DIR}:/etc/caddy:ro`, - '--entrypoint', - '/bin/sh', - ...Object.entries(env).flatMap(([name, value]) => ['-e', `${name}=${value}`]), - caddyImage(), - '/etc/caddy/start.sh', - ]); - const logs = () => { - try { - return execFileSync('docker', ['logs', container], { encoding: 'utf8', stdio: 'pipe' }); - } catch (err) { - return String(err); - } - }; - await waitFor( - 'Caddy to serve TLS', - async () => { + /** One HTTPS request through Caddy with an exact raw path, as a WebSocket upgrade if asked. */ + function send( + host: string, + path: string, + headers: Record = {}, + upgrade = false + ): Promise { + const fullHost = host.includes('.') ? host : `${host}.${DOMAIN}`; + const upgradeHeaders: Record = upgrade + ? { + Connection: 'Upgrade', + Upgrade: 'websocket', + 'Sec-WebSocket-Version': '13', + 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), + } + : {}; + return httpsGet(ports.https, fullHost, path, { ...upgradeHeaders, ...headers }); + } + + /** What celld (Deno / workerd URL parsing) could treat as the gateway route, generously. */ + function couldBeGatewayPath(raw: string): boolean { + let path = (raw.split('?')[0] ?? '').replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, ''); + for (let i = 0; i < 3; i += 1) { try { - return (await send('app', '/')).status === 200; + path = decodeURIComponent(path); } catch { - return false; + break; } - }, - 120_000, - logs - ); -}); - -afterAll(async () => { - if (container) execFileSync('docker', ['rm', '-f', container], { stdio: 'ignore' }); - await new Promise((done) => (celld ? celld.close(() => done()) : done())); - await new Promise((done) => (node ? node.close(() => done()) : done())); - await new Promise((done) => (frps ? frps.close(() => done()) : done())); -}); - -beforeEach(() => { - celldSeen.length = 0; - nodeSeen.length = 0; - frpsSeen.length = 0; - nodeUpgradeHeaders = {}; - decide = () => ({ status: 401 }); -}); - -interface Reply { - status: number; - headers: IncomingHttpHeaders; -} - -/** One HTTPS request through Caddy with an exact raw path (Node does not normalize it). */ -function send( - host: string, - path: string, - headers: Record = {}, - upgrade = false -): Promise { - const fullHost = host.includes('.') ? host : `${host}.${DOMAIN}`; - return new Promise((done, fail) => { - const req = httpsRequest({ - host: '127.0.0.1', - port: ports.https, - servername: fullHost.toLowerCase(), - rejectUnauthorized: false, - method: 'GET', - path, - headers: { - Host: fullHost, - ...(upgrade - ? { - Connection: 'Upgrade', - Upgrade: 'websocket', - 'Sec-WebSocket-Version': '13', - 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), - } - : {}), - ...headers, - }, - }); - req.on('upgrade', (res: IncomingMessage, socket: Duplex) => { - socket.destroy(); - done({ status: res.statusCode ?? 0, headers: res.headers }); - }); - req.on('response', (res) => { - res.resume(); - res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers })); - }); - req.on('error', fail); - req.end(); - }); -} - -/** What celld (Deno / workerd URL parsing) could treat as the gateway route, generously. */ -function couldBeGatewayPath(raw: string): boolean { - let path = (raw.split('?')[0] ?? '').replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, ''); - for (let i = 0; i < 3; i += 1) { - try { - path = decodeURIComponent(path); - } catch { - break; } + path = posix.normalize(path.replaceAll('\\', '/').replace(/\/+/g, '/')).toLowerCase(); + return path.startsWith('/api/self-host/gateway'); } - path = posix.normalize(path.replaceAll('\\', '/').replace(/\/+/g, '/')).toLowerCase(); - return path.startsWith('/api/self-host/gateway'); -} -const HOSTS = ['api', 'app', `ws-${WORKSPACE}`, `ws-${WORKSPACE}--3000`, 'API']; -const CANONICAL = [ - '/api/self-host/gateway', - '/api/self-host/gateway/', - '/api/self-host/gateway/frps-plugin?op=Login', - '/api/self-host/gateway/node-websocket', -]; -const TRICKS = [ - '//api/self-host/gateway/frps-plugin', - '/api//self-host/gateway/frps-plugin', - '/api/self-host//gateway/node-websocket', - '/api/self-host/./gateway/frps-plugin', - '/api/self-host/x/../gateway/frps-plugin', - '/api/./self-host/gateway/', - '/api/self-host/gateway%2Ffrps-plugin', - '/api%2Fself-host%2Fgateway%2Ffrps-plugin', - '/api/self-host/%67ateway/frps-plugin', - '/api/self-host/gateway%252Ffrps-plugin', - '/API/SELF-HOST/GATEWAY/frps-plugin', - '/Api/Self-Host/Gateway', - '/api/self-host/gateway;x=1', - '/api/self-host/gateway%00/frps-plugin', - '/api/self-host/gateway/..%2Ffrps-plugin', - // Encoded hyphen: only the raw-request-path clause of the variant matcher sees these. - '/api/self%2Dhost/gateway/', - '/API/SELF%2DHOST/gateway', - '/api/self%252dhost/gateway/frps-plugin', - '/api/self%252Dhost/gateway/node-websocket', - // Encoded letters at any depth (F21 L1: the old matcher enumerated only the hyphen's spellings). - '/api/%73elf-host/gateway/frps-plugin', - '/api/%2573elf-host/gateway/frps-plugin', - '/api/%252573elf-host/gateway/node-websocket', - '/api/SELF-HOS%2554/gateway', - '/%61pi/self-host/gateway/frps-plugin', - '/%2561%2570%2569/self-host/gateway', - // Backslash separators (a WHATWG URL parser reads \ as / in http(s) URLs) and dot segments. - '/api\\self-host\\gateway\\frps-plugin', - '/api%5Cself-host%5Cgateway', - '/x\\..\\api\\self-host\\gateway\\frps-plugin', - '/api/x\\..\\self-host/gateway/frps-plugin', - '/api/x/%2e%2e/self-host/gateway/frps-plugin', - '/static/%2e%2e/api/%2573elf-host/gateway', - // Absolute-form request target. - `https://api.${DOMAIN}/api/self-host/gateway/frps-plugin`, - `https://api.${DOMAIN}/api/%2573elf-host/gateway`, -]; + const HOSTS = ['api', 'app', `ws-${WORKSPACE}`, `ws-${WORKSPACE}--3000`, 'API']; + const CANONICAL = [ + '/api/self-host/gateway', + '/api/self-host/gateway/', + '/api/self-host/gateway/frps-plugin?op=Login', + '/api/self-host/gateway/node-websocket', + ]; + const TRICKS = [ + '//api/self-host/gateway/frps-plugin', + '/api//self-host/gateway/frps-plugin', + '/api/self-host//gateway/node-websocket', + '/api/self-host/./gateway/frps-plugin', + '/api/self-host/x/../gateway/frps-plugin', + '/api/./self-host/gateway/', + '/api/self-host/gateway%2Ffrps-plugin', + '/api%2Fself-host%2Fgateway%2Ffrps-plugin', + '/api/self-host/%67ateway/frps-plugin', + '/api/self-host/gateway%252Ffrps-plugin', + '/API/SELF-HOST/GATEWAY/frps-plugin', + '/Api/Self-Host/Gateway', + '/api/self-host/gateway;x=1', + '/api/self-host/gateway%00/frps-plugin', + '/api/self-host/gateway/..%2Ffrps-plugin', + // Encoded hyphen: only the raw-request-path clause of the variant matcher sees these. + '/api/self%2Dhost/gateway/', + '/API/SELF%2DHOST/gateway', + '/api/self%252dhost/gateway/frps-plugin', + '/api/self%252Dhost/gateway/node-websocket', + // Encoded letters at any depth (F21 L1: the old matcher enumerated only the hyphen's spellings). + '/api/%73elf-host/gateway/frps-plugin', + '/api/%2573elf-host/gateway/frps-plugin', + '/api/%252573elf-host/gateway/node-websocket', + '/api/SELF-HOS%2554/gateway', + '/%61pi/self-host/gateway/frps-plugin', + '/%2561%2570%2569/self-host/gateway', + // Backslash separators (a WHATWG URL parser reads \ as / in http(s) URLs) and dot segments. + '/api\\self-host\\gateway\\frps-plugin', + '/api%5Cself-host%5Cgateway', + '/x\\..\\api\\self-host\\gateway\\frps-plugin', + '/api/x\\..\\self-host/gateway/frps-plugin', + '/api/x/%2e%2e/self-host/gateway/frps-plugin', + '/static/%2e%2e/api/%2573elf-host/gateway', + // Absolute-form request target. + `https://api.${DOMAIN}/api/self-host/gateway/frps-plugin`, + `https://api.${DOMAIN}/api/%2573elf-host/gateway`, + ]; -describe('internal gateway routes are never served publicly', () => { - it.each(HOSTS.flatMap((host) => CANONICAL.map((path) => [host, path] as const)))( - '404 on %s for %s, plain and upgrade', - async (host, path) => { - for (const upgrade of [false, true]) { - const reply = await send(host, path, {}, upgrade); - expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBe(404); + describe('internal gateway routes are never served publicly', () => { + it.each(HOSTS.flatMap((host) => CANONICAL.map((path) => [host, path] as const)))( + '404 on %s for %s, plain and upgrade', + async (host, path) => { + for (const upgrade of [false, true]) { + const reply = await send(host, path, {}, upgrade); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBe(404); + } + expect(celldSeen).toEqual([]); + expect(nodeSeen).toEqual([]); } - expect(celldSeen).toEqual([]); - expect(nodeSeen).toEqual([]); - } - ); + ); - // Non-workspace hosts only: on a ws-* host the Worker hands every request to the workspace - // proxy before any route (apps/api/src/index.ts; pinned by the workers test 'never forwards - // the gateway secret to a node, even when a request carrying it reaches the ws-* proxy'). - const API_HOSTS = ['api', 'app', 'API', 'App']; - it.each(API_HOSTS.flatMap((host) => TRICKS.map((path) => [host, path] as const)))( - 'no path trick on %s reaches the gateway route: %s', - async (host, path) => { - for (const upgrade of [false, true]) { - const reply = await send(host, path, {}, upgrade); - expect(reply.status, `${host}${path} upgrade=${upgrade}`).not.toBe(101); - expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBeGreaterThanOrEqual(400); + // Non-workspace hosts only: on a ws-* host the Worker hands every request to the workspace + // proxy before any route (apps/api/src/index.ts; pinned by the workers test 'never forwards + // the gateway secret to a node, even when a request carrying it reaches the ws-* proxy'). + const API_HOSTS = ['api', 'app', 'API', 'App']; + it.each(API_HOSTS.flatMap((host) => TRICKS.map((path) => [host, path] as const)))( + 'no path trick on %s reaches the gateway route: %s', + async (host, path) => { + for (const upgrade of [false, true]) { + const reply = await send(host, path, {}, upgrade); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).not.toBe(101); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBeGreaterThanOrEqual(400); + } + // Whatever Caddy did with it, nothing celld could route to the gateway arrived there. + expect(celldSeen.filter((seen) => couldBeGatewayPath(seen.url))).toEqual([]); + expect(nodeSeen).toEqual([]); } - // Whatever Caddy did with it, nothing celld could route to the gateway arrived there. - expect(celldSeen.filter((seen) => couldBeGatewayPath(seen.url))).toEqual([]); - expect(nodeSeen).toEqual([]); - } - ); + ); - it('control: ordinary API traffic and a preview app path naming self-hosting reach celld', async () => { - expect((await send('api', '/api/projects?q=self-host')).status).toBe(200); - expect((await send(`ws-${WORKSPACE}--3000`, '/docs/self-hosting')).status).toBe(200); - expect(celldSeen.map((seen) => seen.url)).toEqual([ - '/api/projects?q=self-host', - '/docs/self-hosting', - ]); - }); + it('control: ordinary API traffic and a preview app path naming self-hosting reach celld', async () => { + expect((await send('api', '/api/projects?q=self-host')).status).toBe(200); + expect((await send(`ws-${WORKSPACE}--3000`, '/docs/self-hosting')).status).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual([ + '/api/projects?q=self-host', + '/docs/self-hosting', + ]); + }); - // F21 L6: only the gateway prefix is refused; a public path that merely names "self-host" - // (a docs page, a project file called self-host) still reaches the app. - const PUBLIC = [ - ['app', '/docs/self-host/guide'], - ['app', '/blog/how-to-self-host'], - ['api', '/api/projects/p1/files/self-host/README.md'], - ['api', '/api/projects/p1/files/docs%2Fself-host'], - ['api', '/api/self-hosted'], - ['api', '/api/x/self-host'], - ] as const; - it.each(PUBLIC)('control: %s%s reaches celld', async (host, path) => { - expect((await send(host, path)).status, `${host}${path}`).toBe(200); - expect(celldSeen.map((seen) => seen.url)).toEqual([path]); + // F21 L6: only the gateway prefix is refused; a public path that merely names "self-host" + // (a docs page, a project file called self-host) still reaches the app. + const PUBLIC = [ + ['app', '/docs/self-host/guide'], + ['app', '/blog/how-to-self-host'], + ['api', '/api/projects/p1/files/self-host/README.md'], + ['api', '/api/projects/p1/files/docs%2Fself-host'], + ['api', '/api/self-hosted'], + ['api', '/api/x/self-host'], + ] as const; + it.each(PUBLIC)('control: %s%s reaches celld', async (host, path) => { + expect((await send(host, path)).status, `${host}${path}`).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual([path]); + }); }); -}); -describe('frp connections are rate limited per client address', () => { - it(`passes ${FRP_LOGIN_LIMIT} connections a minute to frps, then answers 429`, async () => { - const replies: number[] = []; - for (let i = 0; i < FRP_LOGIN_LIMIT + 2; i += 1) { - replies.push((await send('api', '/~!frp')).status); - } - expect(replies.slice(FRP_LOGIN_LIMIT)).toEqual([429, 429]); - expect(replies.slice(0, FRP_LOGIN_LIMIT).every((status) => status !== 429)).toBe(true); - expect(frpsSeen).toHaveLength(FRP_LOGIN_LIMIT); - // Control: the limit is the frp route's alone; the API on the same host still answers. - expect((await send('api', '/health')).status).toBe(200); - expect(celldSeen.map((seen) => seen.url)).toEqual(['/health']); + describe('frp connections are rate limited per client address', () => { + it(`passes ${FRP_LOGIN_LIMIT} connections a minute to frps, then answers 429`, async () => { + const replies: number[] = []; + for (let i = 0; i < FRP_LOGIN_LIMIT + 2; i += 1) { + replies.push((await send('api', '/~!frp')).status); + } + expect(replies.slice(FRP_LOGIN_LIMIT)).toEqual([429, 429]); + expect(replies.slice(0, FRP_LOGIN_LIMIT).every((status) => status !== 429)).toBe(true); + expect(frpsSeen).toHaveLength(FRP_LOGIN_LIMIT); + // Control: the limit is the frp route's alone; the API on the same host still answers. + expect((await send('api', '/health')).status).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual(['/health']); + }); }); -}); -const FORGED = { - 'X-SAM-Gateway-Secret': 'client-forged-secret', - 'X-SAM-Gateway-Original-Host': `api.${DOMAIN}`, - 'X-SAM-Upstream': '127.0.0.1:7001', - 'X-SAM-Upstream-Uri': '/forged', - 'X-SAM-Upstream-Authorization': 'Bearer forged', - 'X-SAM-Upstream-Cookie': 'forged=1', - 'x-sam-node-id': 'FORGED-NODE', - 'X-Sam-Workspace-Id': 'FORGED-WS', -}; + const FORGED = { + 'X-SAM-Gateway-Secret': 'client-forged-secret', + 'X-SAM-Gateway-Original-Host': `api.${DOMAIN}`, + 'X-SAM-Upstream': '127.0.0.1:7001', + 'X-SAM-Upstream-Uri': '/forged', + 'X-SAM-Upstream-Authorization': 'Bearer forged', + 'X-SAM-Upstream-Cookie': 'forged=1', + 'x-sam-node-id': 'FORGED-NODE', + 'X-Sam-Workspace-Id': 'FORGED-WS', + }; -const forwardAuth = () => - celldSeen.filter((seen) => seen.url.startsWith('/api/self-host/gateway/node-websocket')); + const forwardAuth = () => + celldSeen.filter((seen) => seen.url.startsWith('/api/self-host/gateway/node-websocket')); -describe('client X-SAM-* headers on ordinary routes', () => { - it.each(['api', 'app', `ws-${WORKSPACE}--3000`])( - 'never reach celld through the catch-all route (%s)', - async (host) => { - const reply = await send(host, '/api/projects', { ...FORGED, 'X-Other': 'kept' }); - expect(reply.status).toBe(200); - // Liveness: the request reached celld, with an ordinary header intact. - expect(celldSeen).toHaveLength(1); - expect(celldSeen[0]?.headers['x-other']).toBe('kept'); - expect( - Object.keys(celldSeen[0]?.headers ?? {}).filter((h) => h.startsWith('x-sam-')) - ).toEqual([]); - } - ); -}); + describe('client X-SAM-* headers on ordinary routes', () => { + it.each(['api', 'app', `ws-${WORKSPACE}--3000`])( + 'never reach celld through the catch-all route (%s)', + async (host) => { + const reply = await send(host, '/api/projects', { ...FORGED, 'X-Other': 'kept' }); + expect(reply.status).toBe(200); + // Liveness: the request reached celld, with an ordinary header intact. + expect(celldSeen).toHaveLength(1); + expect(celldSeen[0]?.headers['x-other']).toBe('kept'); + expect( + Object.keys(celldSeen[0]?.headers ?? {}).filter((h) => h.startsWith('x-sam-')) + ).toEqual([]); + } + ); + }); + + describe('forward_auth for node WebSockets', () => { + it.each([WS_HOST, PORT_HOST])( + 'strips client X-SAM-* headers before forward_auth and passes a refusal through (%s)', + async (host) => { + decide = () => ({ status: 401, headers: { 'Content-Type': 'application/json' } }); + const reply = await send(host, '/agent/ws', FORGED, true); + expect(reply.status).toBe(401); + const [auth, ...more] = forwardAuth(); + expect(more).toEqual([]); + expect(auth?.headers['x-sam-gateway-secret']).toBe(SECRET); + expect(auth?.headers['x-sam-gateway-original-host']).toBe(host); + expect(auth?.headers['x-forwarded-uri']).toBe('/agent/ws'); + for (const name of [ + 'x-sam-upstream', + 'x-sam-upstream-uri', + 'x-sam-upstream-authorization', + 'x-sam-upstream-cookie', + 'x-sam-node-id', + 'x-sam-workspace-id', + ]) { + expect(auth?.headers[name], name).toBeUndefined(); + } + expect(nodeSeen).toEqual([]); + } + ); -describe('forward_auth for node WebSockets', () => { - it.each([WS_HOST, PORT_HOST])( - 'strips client X-SAM-* headers before forward_auth and passes a refusal through (%s)', - async (host) => { - decide = () => ({ status: 401, headers: { 'Content-Type': 'application/json' } }); - const reply = await send(host, '/agent/ws', FORGED, true); - expect(reply.status).toBe(401); - const [auth, ...more] = forwardAuth(); - expect(more).toEqual([]); - expect(auth?.headers['x-sam-gateway-secret']).toBe(SECRET); - expect(auth?.headers['x-sam-gateway-original-host']).toBe(host); - expect(auth?.headers['x-forwarded-uri']).toBe('/agent/ws'); + it('proxies an authorized socket with exactly the Worker-decided headers', async () => { + decide = () => ({ + status: 200, + headers: { + 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, + 'X-SAM-Upstream-Uri': '/agent/ws?decided=1', + 'X-SAM-Upstream-Authorization': 'Bearer worker-decided', + 'X-SAM-Upstream-Cookie': '', + 'X-SAM-Node-Id': 'NODE-REAL', + 'X-SAM-Workspace-Id': 'WS-REAL', + }, + }); + const reply = await send( + WS_HOST, + '/agent/ws?client=1', + { ...FORGED, Authorization: 'Bearer client', Cookie: 'session=client' }, + true + ); + expect(reply.status).toBe(101); + const [upstream] = nodeSeen; + expect(upstream?.url).toBe('/agent/ws?decided=1'); + expect(upstream?.headers.authorization).toBe('Bearer worker-decided'); + expect(upstream?.headers.cookie ?? '').toBe(''); + expect(upstream?.headers['x-sam-node-id']).toBe('NODE-REAL'); + expect(upstream?.headers['x-sam-workspace-id']).toBe('WS-REAL'); + expect(upstream?.headers['x-forwarded-host']).toBe(WS_HOST); for (const name of [ + 'x-sam-gateway-secret', + 'x-sam-gateway-original-host', 'x-sam-upstream', 'x-sam-upstream-uri', 'x-sam-upstream-authorization', 'x-sam-upstream-cookie', - 'x-sam-node-id', - 'x-sam-workspace-id', ]) { - expect(auth?.headers[name], name).toBeUndefined(); + expect(upstream?.headers[name], name).toBeUndefined(); } - expect(nodeSeen).toEqual([]); - } - ); + }); + }); - it('proxies an authorized socket with exactly the Worker-decided headers', async () => { - decide = () => ({ + describe('Set-Cookie on port-preview sockets', () => { + const allowTo = (uri: string): Decision => ({ status: 200, headers: { 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, - 'X-SAM-Upstream-Uri': '/agent/ws?decided=1', - 'X-SAM-Upstream-Authorization': 'Bearer worker-decided', + 'X-SAM-Upstream-Uri': uri, + 'X-SAM-Upstream-Authorization': '', 'X-SAM-Upstream-Cookie': '', 'X-SAM-Node-Id': 'NODE-REAL', 'X-SAM-Workspace-Id': 'WS-REAL', }, }); - const reply = await send( - WS_HOST, - '/agent/ws?client=1', - { ...FORGED, Authorization: 'Bearer client', Cookie: 'session=client' }, - true - ); - expect(reply.status).toBe(101); - const [upstream] = nodeSeen; - expect(upstream?.url).toBe('/agent/ws?decided=1'); - expect(upstream?.headers.authorization).toBe('Bearer worker-decided'); - expect(upstream?.headers.cookie ?? '').toBe(''); - expect(upstream?.headers['x-sam-node-id']).toBe('NODE-REAL'); - expect(upstream?.headers['x-sam-workspace-id']).toBe('WS-REAL'); - expect(upstream?.headers['x-forwarded-host']).toBe(WS_HOST); - for (const name of [ - 'x-sam-gateway-secret', - 'x-sam-gateway-original-host', - 'x-sam-upstream', - 'x-sam-upstream-uri', - 'x-sam-upstream-authorization', - 'x-sam-upstream-cookie', - ]) { - expect(upstream?.headers[name], name).toBeUndefined(); - } - }); -}); -describe('Set-Cookie on port-preview sockets', () => { - const allowTo = (uri: string): Decision => ({ - status: 200, - headers: { - 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, - 'X-SAM-Upstream-Uri': uri, - 'X-SAM-Upstream-Authorization': '', - 'X-SAM-Upstream-Cookie': '', - 'X-SAM-Node-Id': 'NODE-REAL', - 'X-SAM-Workspace-Id': 'WS-REAL', - }, - }); - - it('drops a Set-Cookie the workspace app sends on its 101 upgrade', async () => { - decide = () => allowTo('/workspaces/W/ports/3000/hmr'); - nodeUpgradeHeaders = { 'Set-Cookie': 'sam_port_access=from-the-app; Path=/' }; - const reply = await send(PORT_HOST, '/hmr', {}, true); - expect(reply.status).toBe(101); - expect(nodeSeen).toHaveLength(1); - expect(reply.headers['set-cookie']).toBeUndefined(); - }); + it('drops a Set-Cookie the workspace app sends on its 101 upgrade', async () => { + decide = () => allowTo('/workspaces/W/ports/3000/hmr'); + nodeUpgradeHeaders = { 'Set-Cookie': 'sam_port_access=from-the-app; Path=/' }; + const reply = await send(PORT_HOST, '/hmr', {}, true); + expect(reply.status).toBe(101); + expect(nodeSeen).toHaveLength(1); + expect(reply.headers['set-cookie']).toBeUndefined(); + }); - it("control: SAM's own port-token redirect keeps its cookie", async () => { - decide = () => ({ - status: 302, - headers: { - Location: `https://${PORT_HOST}/app`, - 'Set-Cookie': 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', - }, + it("control: SAM's own port-token redirect keeps its cookie", async () => { + decide = () => ({ + status: 302, + headers: { + Location: `https://${PORT_HOST}/app`, + 'Set-Cookie': 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', + }, + }); + const reply = await send(PORT_HOST, '/app?port_token=t', {}, true); + expect(reply.status).toBe(302); + expect(reply.headers['set-cookie']).toEqual([ + 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', + ]); + expect(nodeSeen).toEqual([]); }); - const reply = await send(PORT_HOST, '/app?port_token=t', {}, true); - expect(reply.status).toBe(302); - expect(reply.headers['set-cookie']).toEqual([ - 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', - ]); - expect(nodeSeen).toEqual([]); - }); - it('control: the agent socket on a non-port host is not a port preview', async () => { - decide = () => allowTo('/agent/ws'); - nodeUpgradeHeaders = { 'X-Node-Marker': 'reached' }; - const reply = await send(WS_HOST, '/agent/ws', {}, true); - expect(reply.status).toBe(101); - expect(reply.headers['x-node-marker']).toBe('reached'); + it('control: the agent socket on a non-port host is not a port preview', async () => { + decide = () => allowTo('/agent/ws'); + nodeUpgradeHeaders = { 'X-Node-Marker': 'reached' }; + const reply = await send(WS_HOST, '/agent/ws', {}, true); + expect(reply.status).toBe(101); + expect(reply.headers['x-node-marker']).toBe('reached'); + }); }); }); diff --git a/scripts/selfhost/live/celld-lab.ts b/scripts/selfhost/live/celld-lab.ts index 97bbb00e23..574a64a983 100644 --- a/scripts/selfhost/live/celld-lab.ts +++ b/scripts/selfhost/live/celld-lab.ts @@ -1,16 +1,17 @@ /** * A celld node on loopback for the live suite: the box's object store (the pinned MinIO image), - * the pinned celld binary serving from it, and `celld deploy` of a probe project. Shared by every - * live test that runs a Worker on the real runtime, so each test states only what it probes. + * the pinned celld binary serving from it, and `celld deploy` of a probe project, so a test that + * runs a Worker on the real runtime states only what it probes (shared-flight-cancel today). + * writeProject also serves tests that run `celld dev` on a bare project (celld-redirect). */ import { spawnSync, type SpawnSyncReturns } from 'node:child_process'; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { parse } from 'yaml'; import { resolveEsbuild } from '../celld-binary.js'; -import { freePort, REPO_ROOT, type Running, start, waitFor } from './harness'; +import { childEnv, DOCKER, freePort, REPO_ROOT, type Running, start, waitFor } from './harness'; /** The object store image docker-compose.yml pins (digest); `mc` ships in it. */ export const OBJECTSTORE_IMAGE = ( @@ -19,16 +20,6 @@ export const OBJECTSTORE_IMAGE = ( } ).services.objectstore.image; -/** - * The docker CLI from a fixed system directory, never resolved through a caller-controlled PATH - * (as harness.ts does for tar and openssl). Empty when docker is not installed. - */ -export const DOCKER = - ['/usr/bin/docker', '/usr/local/bin/docker', '/bin/docker'].find((path) => existsSync(path)) ?? - ''; -export const hasDocker = - DOCKER !== '' && spawnSync(DOCKER, ['version'], { stdio: 'ignore' }).status === 0; - export interface ObjectStore { port: number; /** `http://127.0.0.1:` */ @@ -153,11 +144,10 @@ export async function celldNode( deploy: (project) => spawnSync(binary, ['deploy', project, ...bucketArgs()], { encoding: 'utf8', - env: { - ...process.env, + env: childEnv({ ...store.env(), CELLD_ESBUILD: resolveEsbuild(join(REPO_ROOT, 'apps/api')), - }, + }), }), serve: async (project) => { const running = node.start(); diff --git a/scripts/selfhost/live/celld-redirect.live.test.ts b/scripts/selfhost/live/celld-redirect.live.test.ts index 1965aafcca..5f6439fd2f 100644 --- a/scripts/selfhost/live/celld-redirect.live.test.ts +++ b/scripts/selfhost/live/celld-redirect.live.test.ts @@ -6,13 +6,14 @@ * case records why the guard exists: celld's default fetch follows a 302 to an internal service * and hands back its body (res.redirected stays false, so nothing downstream can tell). */ -import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { ensureCelldBinary, resolveEsbuild } from '../celld-binary.js'; +import { writeProject } from './celld-lab'; import { freePort, LIVE_TMP, REPO_ROOT, type Running, start, waitFor } from './harness'; const NETWORK_HOSTS = join(REPO_ROOT, 'packages/worker-core/src/network-hosts/index.ts'); @@ -75,12 +76,11 @@ beforeAll(async () => { await new Promise((done) => edge.listen(ports.edge, '127.0.0.1', done)); mkdirSync(LIVE_TMP, { recursive: true }); - const project = mkdtempSync(join(LIVE_TMP, 'celld-redirect-')); - writeFileSync( - join(project, 'wrangler.json'), - JSON.stringify({ name: 'redirect-probe', main: 'worker.js', compatibility_date: '2026-01-01' }) - ); - writeFileSync(join(project, 'worker.js'), WORKER); + const project = writeProject(mkdtempSync(join(LIVE_TMP, 'celld-redirect-')), { + name: 'redirect-probe', + worker: WORKER, + vars: {}, + }); const binary = await ensureCelldBinary(join(LIVE_TMP, 'celld-bin')); celld = start( 'bash', diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts index 44be84b9fa..8d9d728076 100644 --- a/scripts/selfhost/live/harness.ts +++ b/scripts/selfhost/live/harness.ts @@ -3,11 +3,14 @@ * binaries (checksum-pinned by the same table cloud-init uses), real Caddy in Docker, and * stub upstreams. Nothing here talks to a SAM deployment or a cloud provider. */ -import { type ChildProcess, execFileSync, spawn } from 'node:child_process'; -import { createHash } from 'node:crypto'; +import { type ChildProcess, execFileSync, spawn, spawnSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'; +import { request as httpsRequest } from 'node:https'; import { createServer } from 'node:net'; import { basename, join, resolve } from 'node:path'; +import type { Duplex } from 'node:stream'; import { DEFAULT_FRPC_VERSION, @@ -22,6 +25,37 @@ export const LIVE_TMP = join(REPO_ROOT, '.tmp', 'selfhost-live'); /** System tools run by absolute path, never resolved through a caller-controlled PATH. */ const TAR = '/usr/bin/tar'; const OPENSSL = '/usr/bin/openssl'; +/** + * The docker CLI from a fixed system directory, never resolved through a caller-controlled PATH + * (as for tar and openssl). Empty when docker is not installed. + */ +export const DOCKER = + ['/usr/bin/docker', '/usr/local/bin/docker', '/bin/docker'].find((path) => existsSync(path)) ?? + ''; +export const hasDocker = + DOCKER !== '' && spawnSync(DOCKER, ['version'], { stdio: 'ignore' }).status === 0; +/** + * The one skip rule for tests that need Docker: skipped on a machine without a working Docker, + * never in CI, where a missing Docker must fail the job rather than pass it empty. + */ +export const skipWithoutDocker = !hasDocker && !process.env.CI; + +/** + * Host variables a test child process may inherit (as the deploy's celldChildEnv does): what the + * tools need to run and find their caches. Host secrets and cloud credentials stay out. + */ +const INHERITED_ENV = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'RUST_LOG']; + +/** The allowlisted host environment (plus any DOCKER_* setting) with `extra` on top. */ +export function childEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = {}; + for (const [name, value] of Object.entries(process.env)) { + if (value !== undefined && (INHERITED_ENV.includes(name) || name.startsWith('DOCKER_'))) { + env[name] = value; + } + } + return { ...env, ...extra }; +} /** A free loopback TCP port (the kernel picks it; closed before returning). */ export async function freePort(): Promise { @@ -66,7 +100,7 @@ export interface Running { /** Start a process, capturing combined output for assertions and failure messages. */ export function start(command: string, args: string[], env: NodeJS.ProcessEnv = {}): Running { - const child = spawn(command, args, { env: { ...process.env, ...env } }); + const child = spawn(command, args, { env: childEnv(env) }); let output = ''; child.stdout?.on('data', (chunk: Buffer) => (output += chunk.toString())); child.stderr?.on('data', (chunk: Buffer) => (output += chunk.toString())); @@ -83,6 +117,8 @@ export function start(command: string, args: string[], env: NodeJS.ProcessEnv = } const CADDY_IMAGE = 'sam-selfhost-caddy:live-test'; +/** The box's Caddy config directory, mounted read-only at /etc/caddy as compose mounts it. */ +export const CADDY_DIR = join(REPO_ROOT, 'deploy/selfhost/caddy'); let caddyBuilt = false; /** @@ -93,13 +129,7 @@ let caddyBuilt = false; */ export function caddyImage(): string { if (!caddyBuilt) { - execFileSync( - 'docker', - ['build', '-q', '-t', CADDY_IMAGE, join(REPO_ROOT, 'deploy/selfhost/caddy')], - { - stdio: 'pipe', - } - ); + execFileSync(DOCKER, ['build', '-q', '-t', CADDY_IMAGE, CADDY_DIR], { stdio: 'pipe' }); caddyBuilt = true; } return CADDY_IMAGE; @@ -124,6 +154,131 @@ export async function caddyBoxEnv(): Promise> { return env; } +/** The `docker run` arguments that start the box's Caddy as docker-compose.yml runs it. */ +function caddyRunArgs(name: string, env: Record, detach: boolean): string[] { + return [ + 'run', + detach ? '-d' : '--rm', + '--name', + name, + '--network', + 'host', + // compose: only the capability to bind 80/443. + '--cap-drop', + 'ALL', + '--cap-add', + 'NET_BIND_SERVICE', + '-v', + `${CADDY_DIR}:/etc/caddy:ro`, + // compose: start.sh checks the settings, then execs Caddy. + '--entrypoint', + '/bin/sh', + ...Object.entries(env).flatMap(([key, value]) => ['-e', `${key}=${value}`]), + caddyImage(), + '/etc/caddy/start.sh', + ]; +} + +export interface CaddyRun { + container: string; + /** The HTTPS port (env.HTTPS_PORT). */ + https: number; + stdout: () => string; + stderr: () => string; + /** Removes the container (idempotent). */ + stop: () => void; +} + +/** + * Start the box's Caddy image through start.sh, exactly as docker-compose.yml does, with `env` + * (start with caddyBoxEnv() so start.sh's checks pass), and wait until it answers HTTPS on + * env.HTTPS_PORT with any status (a stack whose upstream is down answers 502). + */ +export async function startCaddy(env: Record): Promise { + const container = `sam-live-caddy-${randomBytes(4).toString('hex')}`; + execFileSync(DOCKER, caddyRunArgs(container, env, true), { stdio: 'pipe' }); + const logs = () => spawnSync(DOCKER, ['logs', container], { encoding: 'utf8' }); + const run: CaddyRun = { + container, + https: Number(env.HTTPS_PORT), + stdout: () => logs().stdout ?? '', + stderr: () => logs().stderr ?? '', + stop: () => void spawnSync(DOCKER, ['rm', '-f', container], { stdio: 'ignore' }), + }; + try { + await waitFor( + 'Caddy to serve TLS', + async () => { + try { + return (await httpsGet(run.https, `app.${env.SAM_DOMAIN}`, '/')).status > 0; + } catch { + return false; + } + }, + 120_000, + run.stderr + ); + } catch (error) { + run.stop(); + throw error; + } + return run; +} + +/** Run the box's Caddy image in the foreground until start.sh or Caddy exits. */ +export function runCaddyToExit(env: Record): { + status: number | null; + stderr: string; +} { + const name = `sam-live-caddy-${randomBytes(4).toString('hex')}`; + const run = spawnSync(DOCKER, caddyRunArgs(name, env, false), { + encoding: 'utf8', + timeout: 60_000, + }); + return { status: run.status, stderr: run.stderr ?? '' }; +} + +export interface HttpsReply { + status: number; + headers: IncomingHttpHeaders; + body: string; +} + +/** + * One HTTPS request to Caddy on 127.0.0.1:`port` for `host` (SNI and Host), with the exact raw + * `path` (Node does not normalize it) and the box's self-signed certificate accepted. For a + * request with WebSocket upgrade headers, a 101 reply's socket is closed at once. + */ +export function httpsGet( + port: number, + host: string, + path: string, + headers: Record = {} +): Promise { + return new Promise((done, fail) => { + const req = httpsRequest({ + host: '127.0.0.1', + port, + servername: host.toLowerCase(), + rejectUnauthorized: false, + method: 'GET', + path, + headers: { Host: host, ...headers }, + }); + req.on('upgrade', (res: IncomingMessage, socket: Duplex) => { + socket.destroy(); + done({ status: res.statusCode ?? 0, headers: res.headers, body: '' }); + }); + req.on('response', (res) => { + let body = ''; + res.on('data', (chunk: Buffer) => (body += chunk.toString())); + res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers, body })); + }); + req.on('error', fail); + req.end(); + }); +} + export const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); /** Poll until `check` is truthy or the deadline passes. */ diff --git a/scripts/selfhost/live/mail-collector.live.test.ts b/scripts/selfhost/live/mail-collector.live.test.ts index 47ea820db8..182663f550 100644 --- a/scripts/selfhost/live/mail-collector.live.test.ts +++ b/scripts/selfhost/live/mail-collector.live.test.ts @@ -12,106 +12,63 @@ import { execFileSync, spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; -import { request as httpsRequest } from 'node:https'; import { connect } from 'node:net'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { parse } from 'yaml'; -import { caddyBoxEnv, caddyImage, freePort, REPO_ROOT, waitFor } from './harness'; +import { + caddyBoxEnv, + type CaddyRun, + DOCKER, + freePort, + httpsGet, + REPO_ROOT, + runCaddyToExit, + skipWithoutDocker, + startCaddy as startBoxCaddy, + waitFor, +} from './harness'; const DOMAIN = 'sam.test'; -const CADDY_DIR = `${REPO_ROOT}/deploy/selfhost/caddy`; const PASSWORD = randomBytes(32).toString('hex'); const USER = 'collector'; -interface Stack { - container: string; - https: number; - logs: () => string; -} - const collectorHits: string[] = []; const celldHits: string[] = []; let collector: Server; let celld: Server; let collectorPort = 0; let celldPort = 0; -const stacks: Stack[] = []; - -function dockerArgs(name: string, env: Record): string[] { - return [ - 'run', - '-d', - '--name', - name, - '--network', - 'host', - '-v', - `${CADDY_DIR}:/etc/caddy:ro`, - '--cap-drop', - 'ALL', - '--cap-add', - 'NET_BIND_SERVICE', - '--entrypoint', - '/bin/sh', - ...Object.entries(env).flatMap(([key, value]) => ['-e', `${key}=${value}`]), - caddyImage(), - '/etc/caddy/start.sh', - ]; -} +const stacks: CaddyRun[] = []; +/** Other containers a test started (the real collector), removed after the file. */ +const containers: string[] = []; -async function startCaddy(extra: Record): Promise { - const https = await freePort(); - const container = `sam-live-mail-${randomBytes(4).toString('hex')}`; - execFileSync( - 'docker', - dockerArgs(container, { - ...(await caddyBoxEnv()), - SAM_DOMAIN: DOMAIN, - SAM_TLS_MODE: 'internal', - HTTPS_PORT: String(https), - CELLD_PORT: String(celldPort), - REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), - ...extra, - }) - ); - const logs = () => spawnSync('docker', ['logs', container], { encoding: 'utf8' }).stderr ?? ''; - const stack = { container, https, logs }; +async function startCaddy(extra: Record): Promise { + const stack = await startBoxCaddy({ + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + CELLD_PORT: String(celldPort), + REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), + ...extra, + }); stacks.push(stack); - await waitFor( - 'Caddy to serve TLS', - async () => { - try { - return (await get(stack, `app.${DOMAIN}`)).status === 200; - } catch { - return false; - } - }, - 120_000, - logs - ); return stack; } -function get(stack: Stack, host: string, auth?: string): Promise<{ status: number; body: string }> { - return new Promise((done, fail) => { - const req = httpsRequest({ - host: '127.0.0.1', - port: stack.https, - servername: host, - rejectUnauthorized: false, - path: '/api/v1/messages', - headers: { Host: host, ...(auth ? { Authorization: auth } : {}) }, - }); - req.on('response', (res) => { - let body = ''; - res.on('data', (chunk: Buffer) => (body += chunk.toString())); - res.on('end', () => done({ status: res.statusCode ?? 0, body })); - }); - req.on('error', fail); - req.end(); - }); +async function get( + stack: CaddyRun, + host: string, + auth?: string +): Promise<{ status: number; body: string }> { + const reply = await httpsGet( + stack.https, + host, + '/api/v1/messages', + auth ? { Authorization: auth } : {} + ); + return { status: reply.status, body: reply.body }; } const basic = (user: string, password: string) => @@ -124,226 +81,221 @@ const ON = { MAIL_COLLECTOR_UI_PASSWORD: PASSWORD, }; -beforeAll(async () => { - collectorPort = await freePort(); - celldPort = await freePort(); - collector = createServer((req, res) => { - collectorHits.push(req.url ?? ''); - res.end('collector'); - }); - celld = createServer((req, res) => { - celldHits.push(`${req.headers.host ?? ''}${req.url ?? ''}`); - res.end('celld'); - }); - await new Promise((done) => collector.listen(collectorPort, '127.0.0.1', done)); - await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); -}); - -afterAll(async () => { - for (const stack of stacks) spawnSync('docker', ['rm', '-f', stack.container]); - await new Promise((done) => collector.close(() => done())); - await new Promise((done) => celld.close(() => done())); -}); - -describe('mail collector route, collector on', () => { - let stack: Stack; +// Needs Docker (harness skipWithoutDocker: skipped without it locally, never in CI). +describe.skipIf(skipWithoutDocker)('mail collector (live)', () => { beforeAll(async () => { - stack = await startCaddy({ ...ON, MAIL_COLLECTOR_UI_PORT: String(collectorPort) }); + collectorPort = await freePort(); + celldPort = await freePort(); + collector = createServer((req, res) => { + collectorHits.push(req.url ?? ''); + res.end('collector'); + }); + celld = createServer((req, res) => { + celldHits.push(`${req.headers.host ?? ''}${req.url ?? ''}`); + res.end('celld'); + }); + await new Promise((done) => collector.listen(collectorPort, '127.0.0.1', done)); + await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); }); - it('refuses requests without the password and never forwards them', async () => { - collectorHits.length = 0; - for (const auth of [undefined, basic(USER, 'wrong'), basic('admin', PASSWORD), 'Bearer x']) { - expect((await get(stack, `mail.${DOMAIN}`, auth)).status).toBe(401); - } - expect(collectorHits).toEqual([]); + afterAll(async () => { + for (const stack of stacks) stack.stop(); + for (const name of containers) spawnSync(DOCKER, ['rm', '-f', name], { stdio: 'ignore' }); + await new Promise((done) => collector.close(() => done())); + await new Promise((done) => celld.close(() => done())); }); - it('control: the generated password reaches the collector UI', async () => { - collectorHits.length = 0; - const reply = await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD)); - expect(reply).toEqual({ status: 200, body: 'collector' }); - expect(collectorHits).toEqual(['/api/v1/messages']); - }); + describe('mail collector route, collector on', () => { + let stack: CaddyRun; + beforeAll(async () => { + stack = await startCaddy({ ...ON, MAIL_COLLECTOR_UI_PORT: String(collectorPort) }); + }); + + it('refuses requests without the password and never forwards them', async () => { + collectorHits.length = 0; + for (const auth of [undefined, basic(USER, 'wrong'), basic('admin', PASSWORD), 'Bearer x']) { + expect((await get(stack, `mail.${DOMAIN}`, auth)).status).toBe(401); + } + expect(collectorHits).toEqual([]); + }); - it('keeps the plaintext password out of the running Caddy process', () => { - const environ = execFileSync('docker', ['exec', stack.container, 'cat', '/proc/1/environ'], { - encoding: 'utf8', + it('control: the generated password reaches the collector UI', async () => { + collectorHits.length = 0; + const reply = await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD)); + expect(reply).toEqual({ status: 200, body: 'collector' }); + expect(collectorHits).toEqual(['/api/v1/messages']); }); - expect(environ).not.toContain(PASSWORD); - expect(environ).toMatch(/MAIL_COLLECTOR_UI_HASH=\$2a\$/); - }); - it('control: other SAM hosts still go to celld', async () => { - expect((await get(stack, `app.${DOMAIN}`)).body).toBe('celld'); + it('keeps the plaintext password out of the running Caddy process', () => { + const environ = execFileSync(DOCKER, ['exec', stack.container, 'cat', '/proc/1/environ'], { + encoding: 'utf8', + }); + expect(environ).not.toContain(PASSWORD); + expect(environ).toMatch(/MAIL_COLLECTOR_UI_HASH=\$2a\$/); + }); + + it('control: other SAM hosts still go to celld', async () => { + expect((await get(stack, `app.${DOMAIN}`)).body).toBe('celld'); + }); }); -}); -describe('mail collector route, collector off', () => { - it('does not route the mail host to the collector', async () => { - const stack = await startCaddy({ - SAM_MAIL_COLLECTOR: 'off', - MAIL_COLLECTOR_UI_PORT: String(collectorPort), + describe('mail collector route, collector off', () => { + it('does not route the mail host to the collector', async () => { + const stack = await startCaddy({ + SAM_MAIL_COLLECTOR: 'off', + MAIL_COLLECTOR_UI_PORT: String(collectorPort), + }); + collectorHits.length = 0; + celldHits.length = 0; + expect((await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD))).body).toBe('celld'); + expect(collectorHits).toEqual([]); + expect(celldHits).toEqual([`mail.${DOMAIN}/api/v1/messages`]); }); - collectorHits.length = 0; - celldHits.length = 0; - expect((await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD))).body).toBe('celld'); - expect(collectorHits).toEqual([]); - expect(celldHits).toEqual([`mail.${DOMAIN}/api/v1/messages`]); }); -}); -describe('mail collector on without its password', () => { - it.each([ - ['no password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: '' }], - ['a short password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: 'hunter2' }], - ['an unknown switch value', { ...ON, SAM_MAIL_COLLECTOR: 'yes' }], - ])('refuses to start Caddy with %s', async (_, env) => { - const name = `sam-live-mail-${randomBytes(4).toString('hex')}`; - stacks.push({ container: name, https: 0, logs: () => '' }); - execFileSync( - 'docker', - dockerArgs(name, { + describe('mail collector on without its password', () => { + it.each([ + ['no password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: '' }], + ['a short password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: 'hunter2' }], + ['an unknown switch value', { ...ON, SAM_MAIL_COLLECTOR: 'yes' }], + ])('refuses to start Caddy with %s', async (_, env) => { + const run = runCaddyToExit({ ...(await caddyBoxEnv()), SAM_DOMAIN: DOMAIN, SAM_TLS_MODE: 'internal', REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), ...env, - }) - ); - const exit = await waitFor('Caddy to exit', () => { - const state = spawnSync( - 'docker', - ['inspect', '-f', '{{.State.Status}} {{.State.ExitCode}}', name], - { - encoding: 'utf8', - } - ).stdout.trim(); - return state.startsWith('exited') ? state : ''; + }); + expect(run.status).toBe(64); + expect(run.stderr).toMatch( + /caddy: (the mail collector is on without|SAM_MAIL_COLLECTOR must)/ + ); }); - expect(exit).toBe('exited 64'); }); -}); -/** The mail-collector service exactly as docker-compose.yml defines it, on free ports. */ -function collectorService(smtpPort: number, uiPort: number): { image: string; command: string[] } { - const compose = parse( - readFileSync(`${REPO_ROOT}/deploy/selfhost/docker-compose.yml`, 'utf8') - ) as { - services: Record; - }; - const service = compose.services['mail-collector']!; - const command = service.command.map((arg) => - arg - .replace('${MAIL_COLLECTOR_SMTP_PORT:-1025}', String(smtpPort)) - .replace('${MAIL_COLLECTOR_UI_PORT:-8025}', String(uiPort)) - ); - return { image: service.image, command }; -} + /** The mail-collector service exactly as docker-compose.yml defines it, on free ports. */ + function collectorService( + smtpPort: number, + uiPort: number + ): { image: string; command: string[] } { + const compose = parse( + readFileSync(`${REPO_ROOT}/deploy/selfhost/docker-compose.yml`, 'utf8') + ) as { + services: Record; + }; + const service = compose.services['mail-collector']!; + const command = service.command.map((arg) => + arg + .replace('${MAIL_COLLECTOR_SMTP_PORT:-1025}', String(smtpPort)) + .replace('${MAIL_COLLECTOR_UI_PORT:-8025}', String(uiPort)) + ); + return { image: service.image, command }; + } -/** One plaintext SMTP exchange, the way the Worker talks to the collector (SMTP_TLS=none). */ -function sendPlainSmtp(port: number, to: string, subject: string): Promise { - const script = [ - 'EHLO api.sam.test', - 'MAIL FROM:', - `RCPT TO:<${to}>`, - 'DATA', - `From: sign-in@sam.test\r\nTo: ${to}\r\nSubject: ${subject}\r\n\r\nYour code is 123456\r\n.`, - 'QUIT', - ]; - return new Promise((done, fail) => { - const replies: string[] = []; - const socket = connect(port, '127.0.0.1'); - let buffer = ''; - socket.on('data', (chunk: Buffer) => { - buffer += chunk.toString(); - const lines = buffer.split('\r\n'); - buffer = lines.pop() ?? ''; - for (const line of lines) { - if (!/^\d{3} /.test(line)) continue; - replies.push(line.slice(0, 3)); - const next = script.shift(); - if (next) socket.write(`${next}\r\n`); - } + /** One plaintext SMTP exchange, the way the Worker talks to the collector (SMTP_TLS=none). */ + function sendPlainSmtp(port: number, to: string, subject: string): Promise { + const script = [ + 'EHLO api.sam.test', + 'MAIL FROM:', + `RCPT TO:<${to}>`, + 'DATA', + `From: sign-in@sam.test\r\nTo: ${to}\r\nSubject: ${subject}\r\n\r\nYour code is 123456\r\n.`, + 'QUIT', + ]; + return new Promise((done, fail) => { + const replies: string[] = []; + const socket = connect(port, '127.0.0.1'); + let buffer = ''; + socket.on('data', (chunk: Buffer) => { + buffer += chunk.toString(); + const lines = buffer.split('\r\n'); + buffer = lines.pop() ?? ''; + for (const line of lines) { + if (!/^\d{3} /.test(line)) continue; + replies.push(line.slice(0, 3)); + const next = script.shift(); + if (next) socket.write(`${next}\r\n`); + } + }); + socket.on('close', () => done(replies)); + socket.on('error', fail); }); - socket.on('close', () => done(replies)); - socket.on('error', fail); - }); -} + } -describe('the real collector (Mailpit) as compose runs it', () => { - const password = randomBytes(32).toString('hex'); - let smtpPort = 0; - let uiPort = 0; - const name = `sam-live-mailpit-${randomBytes(4).toString('hex')}`; + describe('the real collector (Mailpit) as compose runs it', () => { + const password = randomBytes(32).toString('hex'); + let smtpPort = 0; + let uiPort = 0; + const name = `sam-live-mailpit-${randomBytes(4).toString('hex')}`; - beforeAll(async () => { - smtpPort = await freePort(); - uiPort = await freePort(); - const { image, command } = collectorService(smtpPort, uiPort); - stacks.push({ container: name, https: 0, logs: () => '' }); - execFileSync('docker', [ - 'run', - '-d', - '--name', - name, - '--network', - 'host', - '--user', - '65534:65534', - '--read-only', - '--tmpfs', - '/tmp', - '--cap-drop', - 'ALL', - '-e', - `MP_UI_AUTH=${USER}:${password}`, - image, - ...command, - ]); - await waitFor('Mailpit to listen', async () => { - try { - return (await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`)).status === 401; - } catch { - return false; - } + beforeAll(async () => { + smtpPort = await freePort(); + uiPort = await freePort(); + const { image, command } = collectorService(smtpPort, uiPort); + containers.push(name); + execFileSync(DOCKER, [ + 'run', + '-d', + '--name', + name, + '--network', + 'host', + '--user', + '65534:65534', + '--read-only', + '--tmpfs', + '/tmp', + '--cap-drop', + 'ALL', + '-e', + `MP_UI_AUTH=${USER}:${password}`, + image, + ...command, + ]); + await waitFor('Mailpit to listen', async () => { + try { + return (await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`)).status === 401; + } catch { + return false; + } + }); }); - }); - it('accepts plaintext SMTP on loopback and shows the message to the password only', async () => { - expect(await sendPlainSmtp(smtpPort, 'owner@example.com', 'live code')).toEqual([ - '220', - '250', - '250', - '250', - '354', - '250', - '221', - ]); - const unauthenticated = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`); - expect(unauthenticated.status).toBe(401); - const wrong = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { - headers: { Authorization: basic(USER, 'wrong') }, + it('accepts plaintext SMTP on loopback and shows the message to the password only', async () => { + expect(await sendPlainSmtp(smtpPort, 'owner@example.com', 'live code')).toEqual([ + '220', + '250', + '250', + '250', + '354', + '250', + '221', + ]); + const unauthenticated = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`); + expect(unauthenticated.status).toBe(401); + const wrong = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { + headers: { Authorization: basic(USER, 'wrong') }, + }); + expect(wrong.status).toBe(401); + const list = (await ( + await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { + headers: { Authorization: basic(USER, password) }, + }) + ).json()) as { messages: Array<{ Subject: string; To: Array<{ Address: string }> }> }; + expect(list.messages).toEqual([ + expect.objectContaining({ + Subject: 'live code', + To: [expect.objectContaining({ Address: 'owner@example.com' })], + }), + ]); }); - expect(wrong.status).toBe(401); - const list = (await ( - await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { - headers: { Authorization: basic(USER, password) }, - }) - ).json()) as { messages: Array<{ Subject: string; To: Array<{ Address: string }> }> }; - expect(list.messages).toEqual([ - expect.objectContaining({ - Subject: 'live code', - To: [expect.objectContaining({ Address: 'owner@example.com' })], - }), - ]); - }); - it('refuses the send API without the password too', async () => { - const res = await fetch(`http://127.0.0.1:${uiPort}/api/v1/send`, { - method: 'POST', - body: '{}', + it('refuses the send API without the password too', async () => { + const res = await fetch(`http://127.0.0.1:${uiPort}/api/v1/send`, { + method: 'POST', + body: '{}', + }); + expect(res.status).toBe(401); }); - expect(res.status).toBe(401); }); }); diff --git a/scripts/selfhost/live/shared-flight-cancel.live.test.ts b/scripts/selfhost/live/shared-flight-cancel.live.test.ts index df1655644a..2e716b6d4f 100644 --- a/scripts/selfhost/live/shared-flight-cancel.live.test.ts +++ b/scripts/selfhost/live/shared-flight-cancel.live.test.ts @@ -26,14 +26,16 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS } from '../../../apps/api/src/lib/shared-flight'; import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from '../../../apps/api/src/services/config-read-deadline'; import { ensureCelldBinary } from '../celld-binary.js'; +import { celldNode, type ObjectStore, startObjectStore, writeProject } from './celld-lab'; import { - celldNode, - hasDocker, - type ObjectStore, - startObjectStore, - writeProject, -} from './celld-lab'; -import { freePort, LIVE_TMP, REPO_ROOT, type Running, sleep, waitFor } from './harness'; + freePort, + LIVE_TMP, + REPO_ROOT, + type Running, + skipWithoutDocker, + sleep, + waitFor, +} from './harness'; const SETTINGS_CACHE = join(REPO_ROOT, 'apps/api/src/services/admin-settings-cache.ts'); const SHARED_FLIGHT = join(REPO_ROOT, 'apps/api/src/lib/shared-flight.ts'); @@ -281,7 +283,7 @@ async function expectJoinersAnswer(path: string, bound: number): Promise { +describe.skipIf(skipWithoutDocker)('an aborted request does not poison celld', () => { beforeAll(async () => { const upstreamPort = await freePort(); const proxyPort = await freePort(); From 096c6a7ae6ff2f40d7d91c4683e3bb249f2d0e5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:04:51 +0000 Subject: [PATCH 17/65] test(selfhost): type the malformed-range cases for the selfhost type check Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/caddy-start.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts index c74e7f69aa..06c5766c05 100644 --- a/scripts/selfhost/caddy-start.test.ts +++ b/scripts/selfhost/caddy-start.test.ts @@ -83,7 +83,7 @@ describe('caddy/start.sh', () => { // A malformed bound used to make `[ -ge ]` error, which `if` reads as false: the range check // was skipped and Caddy started with a box port inside the real range. - it.each([ + it.each>([ { REVERSE_TUNNEL_PORT_RANGE_START: '1:2' }, { REVERSE_TUNNEL_PORT_RANGE_END: '29999:1' }, { REVERSE_TUNNEL_PORT_RANGE_START: '20000x' }, From c4fac57ca6703342d7522a77780f4cf0ac3f2aa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:11:49 +0000 Subject: [PATCH 18/65] docs(tasks): L22 task file records PR 2 shipped and PR 3 progress Co-Authored-By: Claude Opus 5.5 --- .../2026-11-19-l22-selfhost-core-packaging.md | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md index 9acbbc032b..901447db45 100644 --- a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md +++ b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md @@ -66,18 +66,36 @@ and trimmed. Nothing in L22 may change Cloudflare behaviour. - [x] Review fixes: security H1 (upgrade forwarding + no key minting over a prior deploy), M1 atomic platform-keys write, M2 deploy/selfhost/.gitignore, M3 create-account --secrets; architecture MEDIUMs (go.mod filter, scripts/ in boundary test, reverse-tunnel limits shared from the Worker) -- [ ] task-completion-validator, CI, CodeRabbit, merge, Deploy Production +- [x] task-completion-validator PASS (MEDIUM fixed), CI, CodeRabbit (9 threads fixed), merged #2902 + as fa04695d2, Deploy Production 44478774764 success ### PR 3 (L22c): box runtime (self-host only) -- [ ] deploy/selfhost compose (no key-agent, fence, docker-proxy, metadata-proxy), Caddy with the - F21 fixes, frps, celld/start.sh, objectstore, .env.example, gcp-bootstrap.sh -- [ ] F11 fix -- [ ] Docker live tests + CI job on self-host paths only (D9) -- [ ] Operator README marked experimental, including R2_S3_REGION for s3:// +- [x] deploy/selfhost compose (no key-agent, fence, docker-proxy, metadata-proxy), Caddy with the + F21 fixes (L1 double-encoding, L5 ports as compose runs them, L6 narrow 404, L7 frp Login + limit), frps, objectstore, .env.example, gcp-bootstrap.sh +- [x] F11 fix: upgrade builds only the local images whose build inputs changed, then `up -d` + without `--build` (`image-rebuilds.ts`) +- [x] Docker live tests + CI job on self-host paths only (D9) +- [x] Operator README marked experimental, including R2_S3_REGION for s3:// +- [x] Rebased onto main after #2902 (upgrade retry/box-scoped compose kept, F11 merged in) +- [x] Review fixes: architecture (CI filters, no build in Validate Deploy Scripts, live harness + dedup, gcp-bootstrap pinned to GCP_REQUIRED_APIS / SA_PROJECT_ROLES, loadBoxEnv); security + MEDIUMs (shared-pool refusal, celld/frps no caps + read-only, 24-char objectstore secret, + sam-mx port reserved + deploy-time port check) and LOWs (site-level X-SAM-* strip, child env + allowlist, build-arg README note) +- [ ] Security HIGH (gcp-bootstrap pool/* binding admits a user credential naming the pool; same + shape in main's guided setup): Worker fix is SAM task 01M7SB8FRZ08M5NEX9WGM74X61 / PR #2905. + Coordinator: do not merge PR 3 until #2905 is deployed, then re-run security-auditor. - [ ] BOX: fresh teardown + rebuild from this head; prove 0255 lease table on a fresh box; L19 celld teardown OWED (guided login not installed); L13 metered ceiling only if a platform AI key exists +- [ ] task-completion-validator, CI, CodeRabbit, merge, Deploy Production + +Not fixed here (accepted as tracked by the coordinator): F21 L4 `port_range_cooling_down` is +fail-fast in `apps/api/src/selfhost/reverse-tunnel/leases.ts` and the shared Worker failure path; +idea 01M7MK0PCF032CT45Z45HRSDEQ. Security LOWs left: access-log redaction matches literal path +spellings only; frp Login limit is per address (IPv6 rotation). ## Acceptance criteria From 14bf56405dbae03789860ab9834b6d5bfc25d58e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:21:01 +0000 Subject: [PATCH 19/65] chore(quality): reviewed baseline entry for the deploy harness fleet fixture The PR-range Gitleaks scan flags the deploy test harness's fixed objectstore secret, lengthened in 6ffc0c89d to meet the 24-character minimum. It is a synthetic fixture; the entry pins that exact finding and expires in 30 days. Co-Authored-By: Claude Opus 5.5 --- scripts/quality/gitleaks-reviewed-baseline.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/quality/gitleaks-reviewed-baseline.json b/scripts/quality/gitleaks-reviewed-baseline.json index 0c71302bf3..92d108a988 100644 --- a/scripts/quality/gitleaks-reviewed-baseline.json +++ b/scripts/quality/gitleaks-reviewed-baseline.json @@ -236,6 +236,14 @@ "3ea24e85ceb78d673fcb02e42f5d44dfabe7a97fa680f090d0fcf1e79c0eff74", "e2345bc2c8f9744b9067ec77eebb1d7baa52999404834bfb429fb63579062263" ] + }, + { + "classification": "synthetic-test-fixture", + "reason": "PR #2906 commit range: scripts/selfhost/deploy-harness.ts BASE_BOX_ENV sets AWS_SECRET_ACCESS_KEY to a fixed, human-readable fleet fixture lengthened to 24+ characters for the objectstore minimum (commit 6ffc0c89d). It is the deploy test harness box .env, never a real credential. Exact finding only.", + "owner": "security", + "reviewedAt": "2026-11-19T08:20:34.012Z", + "expiresAt": "2026-12-19T08:20:34.012Z", + "digests": ["bf079eb1d64eb9f1ada2812def7fc669b390aaa9b56fc1010923fe4095706b31"] } ] } From adaf1c0553d45b7c900a19991833ac007ebb2585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:28:27 +0000 Subject: [PATCH 20/65] fix(selfhost): resolve every compose-interpolated variable from the shell, not only ports Docker Compose takes every variable its files interpolate from the invoking shell before --env-file, but the deploy and upgrade applied shell precedence only to BOX_RESERVED_PORTS. An exported CELLD_BUCKET or SAM_DOMAIN made selfhost:deploy publish with the .env value while docker compose ran celld and Caddy with the shell's. loadBoxEnv now collects the variables referenced in docker-compose.yml and every file the box's COMPOSE_FILE selects (composeFilesFor, moved to compose-env.ts so box-settings can reuse it without an import cycle), and applies a differing shell value for each, plus every box port. Each override is reported by name only. withComposePortOverrides is renamed withComposeShellOverrides; README and .env.example describe the general rule. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/.env.example | 6 +- deploy/selfhost/README.md | 16 +-- scripts/selfhost/box-settings.test.ts | 144 +++++++++++++++++++++++--- scripts/selfhost/box-settings.ts | 39 ++++--- scripts/selfhost/compose-env.ts | 69 ++++++++++++ scripts/selfhost/deploy-harness.ts | 13 ++- scripts/selfhost/deploy.ts | 6 +- scripts/selfhost/upgrade-lib.ts | 31 ++---- scripts/selfhost/upgrade.test.ts | 2 +- 9 files changed, 254 insertions(+), 72 deletions(-) create mode 100644 scripts/selfhost/compose-env.ts diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example index 4eeafb2efd..ef0f6396e0 100644 --- a/deploy/selfhost/.env.example +++ b/deploy/selfhost/.env.example @@ -34,9 +34,9 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # AWS_ACCESS_KEY_ID=sam-objectstore # AWS_SECRET_ACCESS_KEY= # at least 24 characters (the store refuses less): openssl rand -hex 24 -# Loopback ports (host network). Change only on conflict, and only here: a port set in the shell -# also overrides this file for docker compose, and Caddy refuses to start if any of them lies in -# the reverse-tunnel range below. +# Loopback ports (host network). Change only on conflict, and only here: a variable set in the +# shell overrides this file for docker compose (and the deploy), and Caddy refuses to start if any +# port lies in the reverse-tunnel range below. # CELLD_PORT=8080 # CELLD_INTERNAL_PORT=7001 # FRPS_BIND_PORT=7000 diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 2f87c968db..c40c91db46 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -117,6 +117,12 @@ repository, so it never notices an `.env` edit. ## Settings worth knowing +**Shell variables beat `.env`.** Docker Compose takes every variable its files interpolate +(`docker-compose.yml` and any file `COMPOSE_FILE` selects) from the shell before `.env`, so +`selfhost:deploy` and `selfhost:upgrade` do the same: an exported `CELLD_BUCKET`, `SAM_DOMAIN` or +port is what the deploy publishes and checks, and each one is logged by name. Shell variables no +compose file uses are ignored. Set the box in `.env`, not the shell. + **Object store and presigned uploads.** Uploads (attachments, snapshots) go from the browser straight to the fleet bucket when `R2_S3_ENDPOINT` is set and `.state/secrets.env` holds a credential scoped to the R2 prefix (`R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`; never the fleet @@ -132,12 +138,10 @@ celld does not qualify for production. It refuses to start unless `AWS_ACCESS_KE range to both the Worker and `.state/gateway.env`, and refuses a range that contains a box port (`CELLD_PORT`, `CELLD_INTERNAL_PORT`, `FRPS_BIND_PORT`, `OBJECTSTORE_*`, `HTTP(S)_PORT`, `MAIL_COLLECTOR_*`, and the port of sam-mx's `SAM_MX_LISTEN`): a node leased one of those would -receive traffic meant for it. Docker Compose takes a port from the shell before `.env`, so -`selfhost:deploy` and `selfhost:upgrade` check shell overrides too, as soon as they read `.env` -and before anything starts, and Caddy's `start.sh` refuses to start when a port it is given lies -in the range. celld, frps and the mail collector run without capabilities, so their ports must be -1024 or above. Set ports in `.env`, not -the shell. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and +receive traffic meant for it. The deploy and upgrade check the ports as Docker Compose will run +them (shell variables included, see below) as soon as they read `.env` and before anything starts, +and Caddy's `start.sh` refuses to start when a port it is given lies in the range. celld, frps and +the mail collector run without capabilities, so their ports must be 1024 or above. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and Caddy present to the Worker's loopback-only gateway routes (`/api/self-host/gateway/*`, which Caddy answers with 404 from outside). When `gateway.env` changes, the deploy stops until the stack is restarted (`docker compose up -d`), so the Worker never assumes settings frps is not diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index 7e2fce4aec..a7bc2e766d 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -27,9 +27,10 @@ import { resolveTunnelSettings, trimSlashes, tunnelWorkerVars, - withComposePortOverrides, + withComposeShellOverrides, } from './box-settings.js'; -import { syncGatewayEnv } from './deploy-steps.js'; +import { composeFileVariables, composeVariableNames } from './compose-env.js'; +import { SELFHOST_DIR, syncGatewayEnv } from './deploy-steps.js'; import { parseDotenv } from './secret-files.js'; const SECRET = 'ab'.repeat(32); @@ -259,27 +260,88 @@ describe('BOX_RESERVED_PORTS', () => { }); }); -describe('withComposePortOverrides (F21 L5)', () => { - it('applies a shell port override, as docker compose does, and reports it', () => { - const { box, overridden } = withComposePortOverrides( - { CELLD_INTERNAL_PORT: '7001', SAM_DOMAIN: 'box.example' }, - { CELLD_INTERNAL_PORT: '20001', SAM_DOMAIN: 'other.example', PATH: '/usr/bin' } +// Compose takes every variable it interpolates from the shell before --env-file, so the deploy and +// upgrade must too: a shell CELLD_BUCKET or SAM_DOMAIN would otherwise make the deploy publish with +// the .env value while celld and Caddy run with the shell's. +describe('withComposeShellOverrides (F21 L5)', () => { + const composeNames = composeFileVariables({}, SELFHOST_DIR); + + it('applies a shell override of any compose variable, as docker compose does, and reports it', () => { + const { box, overridden } = withComposeShellOverrides( + { CELLD_BUCKET: 'gs://fleet/celld', SAM_DOMAIN: 'box.example', CELLD_INTERNAL_PORT: '7001' }, + { + CELLD_BUCKET: 'gs://other/celld', + SAM_DOMAIN: 'other.example', + CELLD_INTERNAL_PORT: '7001', + }, + composeNames + ); + expect(overridden).toEqual(['CELLD_BUCKET', 'SAM_DOMAIN']); + expect(box).toEqual({ + CELLD_BUCKET: 'gs://other/celld', + SAM_DOMAIN: 'other.example', + CELLD_INTERNAL_PORT: '7001', + }); + }); + + it('applies a shell port override, so the range check sees the port compose will bind', () => { + const { box, overridden } = withComposeShellOverrides( + { CELLD_INTERNAL_PORT: '7001' }, + { CELLD_INTERNAL_PORT: '20001' }, + composeNames ); expect(overridden).toEqual(['CELLD_INTERNAL_PORT']); - expect(box).toEqual({ CELLD_INTERNAL_PORT: '20001', SAM_DOMAIN: 'box.example' }); - // ...so the range check sees the port compose will really bind. expect(() => resolveTunnelPortRange(box)).toThrow(/contains CELLD_INTERNAL_PORT \(20001\)/); }); + it('ignores shell variables no compose file interpolates, even ones the .env sets', () => { + const { box, overridden } = withComposeShellOverrides( + { FOO_UNRELATED: 'from-env', SAM_DOMAIN: 'box.example' }, + { FOO_UNRELATED: 'from-shell', PATH: '/usr/bin', HOME: '/root' }, + composeNames + ); + expect(overridden).toEqual([]); + expect(box).toEqual({ FOO_UNRELATED: 'from-env', SAM_DOMAIN: 'box.example' }); + }); + + it('keeps every box port covered even when no compose file references it', () => { + const { box, overridden } = withComposeShellOverrides({}, { FRPS_BIND_PORT: '25000' }, []); + expect(overridden).toEqual(['FRPS_BIND_PORT']); + expect(() => resolveTunnelPortRange(box)).toThrow(/contains FRPS_BIND_PORT \(25000\)/); + }); + it('control: without a shell override the .env value is checked and passes', () => { - const { box, overridden } = withComposePortOverrides({ CELLD_INTERNAL_PORT: '7001' }, {}); + const { box, overridden } = withComposeShellOverrides( + { CELLD_INTERNAL_PORT: '7001' }, + {}, + composeNames + ); expect(overridden).toEqual([]); expect(resolveTunnelPortRange(box)).toEqual({ start: 20000, end: 29999 }); }); +}); - it('also catches a shell port for a name the .env never set', () => { - const { box } = withComposePortOverrides({}, { FRPS_BIND_PORT: '25000' }); - expect(() => resolveTunnelPortRange(box)).toThrow(/contains FRPS_BIND_PORT \(25000\)/); +describe('composeVariableNames', () => { + it('finds every interpolated value, not escapes, keys or comments', () => { + const names = composeVariableNames( + [ + '# ${IN_A_COMMENT}', + 'services:', + ' app:', + ' image: ${IMAGE:-x}', + ' command: ["$$ESCAPED", "$BARE", "${OUTER:-${INNER}}", "${REQUIRED:?set it}"]', + ' environment:', + ' ${AS_A_KEY}: plain', + ].join('\n') + ); + expect([...names].sort()).toEqual(['BARE', 'IMAGE', 'INNER', 'OUTER', 'REQUIRED']); + }); + + it('covers the settings the deploy publishes from docker-compose.yml', () => { + const names = composeFileVariables({}, SELFHOST_DIR); + for (const name of ['CELLD_BUCKET', 'SAM_DOMAIN', 'SAM_TLS_MODE', 'SAM_MX_LISTEN']) { + expect(names.has(name), name).toBe(true); + } }); }); @@ -331,13 +393,16 @@ describe('loadBoxEnv (S4: checked before anything starts)', () => { }; it('refuses a box listener inside the lease range, from the .env or the shell', () => { - expect(() => loadBoxEnv(box(['SAM_MX_LISTEN=:20025']), {})).toThrow( + expect(() => loadBoxEnv(box(['SAM_MX_LISTEN=:20025']), SELFHOST_DIR, {})).toThrow( /contains SAM_MX_LISTEN \(20025\)/ ); const reported: string[] = []; expect(() => - loadBoxEnv(box(['CELLD_INTERNAL_PORT=7001']), { CELLD_INTERNAL_PORT: '20001' }, (name) => - reported.push(name) + loadBoxEnv( + box(['CELLD_INTERNAL_PORT=7001']), + SELFHOST_DIR, + { CELLD_INTERNAL_PORT: '20001' }, + (name) => reported.push(name) ) ).toThrow(/contains CELLD_INTERNAL_PORT \(20001\)/); // The override is reported before the refusal, so the operator sees where it came from. @@ -346,9 +411,54 @@ describe('loadBoxEnv (S4: checked before anything starts)', () => { it('control: returns the box with shell overrides applied', () => { expect( - loadBoxEnv(box(['SAM_DOMAIN=box.example', 'CELLD_PORT=8080']), { CELLD_PORT: '8081' }) + loadBoxEnv(box(['SAM_DOMAIN=box.example', 'CELLD_PORT=8080']), SELFHOST_DIR, { + CELLD_PORT: '8081', + }) ).toEqual({ SAM_DOMAIN: 'box.example', CELLD_PORT: '8081' }); }); + + // docker-compose.yml passes CELLD_BUCKET to celld and SAM_DOMAIN to Caddy: the deploy must + // publish with the values they run with, and say which came from the shell (never the value). + it('applies and reports a shell CELLD_BUCKET and SAM_DOMAIN, ignoring unrelated variables', () => { + const reported: string[] = []; + const loaded = loadBoxEnv( + box(['CELLD_BUCKET=gs://fleet/celld', 'SAM_DOMAIN=box.example', 'FOO_UNRELATED=env']), + SELFHOST_DIR, + { + CELLD_BUCKET: 'gs://shell/celld', + SAM_DOMAIN: 'shell.example', + FOO_UNRELATED: 'shell', + PATH: '/usr/bin', + }, + (name) => reported.push(name) + ); + expect(reported).toEqual(['CELLD_BUCKET', 'SAM_DOMAIN']); + expect(loaded).toEqual({ + CELLD_BUCKET: 'gs://shell/celld', + SAM_DOMAIN: 'shell.example', + FOO_UNRELATED: 'env', + }); + }); + + it('includes the variables of an overlay the .env selects with COMPOSE_FILE', () => { + const dir = mkdtempSync(join(tmpdir(), 'sam-box-overlay-')); + const overlay = join(dir, 'overlay.yml'); + writeFileSync( + overlay, + 'services:\n celld:\n environment:\n X: ${OVERLAY_SETTING:-x}\n' + ); + const shell = { OVERLAY_SETTING: 'shell' }; + const selected = loadBoxEnv( + box([`COMPOSE_FILE=docker-compose.yml:${overlay}`, 'OVERLAY_SETTING=env']), + SELFHOST_DIR, + shell + ); + expect(selected.OVERLAY_SETTING).toBe('shell'); + // Control: without the overlay selected, compose never reads the variable. + expect(loadBoxEnv(box(['OVERLAY_SETTING=env']), SELFHOST_DIR, shell).OVERLAY_SETTING).toBe( + 'env' + ); + }); }); describe('gatewayEnvAction', () => { diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index 3888bd3122..771934a1db 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -18,6 +18,7 @@ import { MIN_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE, } from '../../apps/api/src/selfhost/reverse-tunnel/limits.js'; +import { composeFileVariables } from './compose-env.js'; import { DEFAULT_MAIL_COLLECTOR_SMTP_PORT, DEFAULT_MAIL_COLLECTOR_UI_PORT, @@ -65,20 +66,26 @@ const UNPRIVILEGED_LISTENERS: readonly string[] = [ ]; /** - * The box settings with the port values docker compose will actually run with. Compose takes a - * variable from the shell before the .env file, so `CELLD_INTERNAL_PORT=20001 docker compose up` - * runs celld's operator API on 20001 whatever the .env says. The deploy and upgrade run in the - * operator's shell, so they apply the same override to every box port before checking the lease - * range, and report each one. (caddy/start.sh repeats the check inside the running stack, for a - * compose command run from another shell.) + * The box settings with the values docker compose will actually run with. Compose takes every + * variable it interpolates from the shell before the .env file, so `CELLD_BUCKET=... docker + * compose up` runs celld on that bucket and `CELLD_INTERNAL_PORT=20001 docker compose up` runs + * celld's operator API on 20001, whatever the .env says. The deploy and upgrade run in the + * operator's shell, so they apply the same precedence to every name in `composeVariables` (what + * the box's compose files interpolate, composeFileVariables) and to every box port, and report + * each override by name. Other shell variables (PATH, ...) are not compose's and are ignored. + * (caddy/start.sh repeats the port check inside the running stack, for a compose command run + * from another shell.) */ -export function withComposePortOverrides( +export function withComposeShellOverrides( box: Readonly>, - hostEnv: NodeJS.ProcessEnv + hostEnv: NodeJS.ProcessEnv, + composeVariables: Iterable ): { box: Record; overridden: string[] } { const effective: Record = { ...box }; const overridden: string[] = []; - for (const name of Object.keys(BOX_RESERVED_PORTS)) { + // Box ports stay covered even if a compose file stops referencing one. + const names = new Set([...composeVariables, ...Object.keys(BOX_RESERVED_PORTS)]); + for (const name of [...names].sort((a, b) => a.localeCompare(b))) { const value = hostEnv[name]; if (value === undefined || value === box[name]) continue; effective[name] = value; @@ -88,19 +95,23 @@ export function withComposePortOverrides( } /** - * The box .env as docker compose will run it (`withComposePortOverrides`; `onOverride` hears each - * shell override first), checked before anything starts: a box listener inside the lease range + * The box .env as docker compose will run it (`withComposeShellOverrides` over the variables of + * every compose file the .env selects from `composeDir`; `onOverride` hears each shell override, + * by name, first), checked before anything starts: a box listener inside the lease range * (resolveTunnelPortRange) fails here, so `selfhost:deploy` and `selfhost:upgrade` stop before * they write state or run docker compose, not only later inside Caddy's start.sh. */ export function loadBoxEnv( envFile: string, + composeDir: string, hostEnv: NodeJS.ProcessEnv = process.env, onOverride: (name: string) => void = () => {} ): Record { - const { box, overridden } = withComposePortOverrides( - parseDotenv(readFileSync(envFile, 'utf8'), envFile), - hostEnv + const fromFile = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + const { box, overridden } = withComposeShellOverrides( + fromFile, + hostEnv, + composeFileVariables(fromFile, composeDir) ); overridden.forEach(onOverride); resolveTunnelPortRange(box); diff --git a/scripts/selfhost/compose-env.ts b/scripts/selfhost/compose-env.ts new file mode 100644 index 0000000000..67b7199af0 --- /dev/null +++ b/scripts/selfhost/compose-env.ts @@ -0,0 +1,69 @@ +/** + * Which compose files a box runs with, and which variables docker compose interpolates from them. + * Compose takes each interpolated variable from the invoking shell before `--env-file`, so the + * deploy and upgrade must resolve exactly these names the same way (box-settings.ts loadBoxEnv). + */ +import { existsSync, readFileSync } from 'node:fs'; +import { isAbsolute, resolve } from 'node:path'; + +import { parse as parseYaml } from 'yaml'; + +/** + * The compose files a box runs with. `COMPOSE_FILE` in .env adds files to the stack, and docker + * compose reads it only when no `-f` is given: an explicit `-f docker-compose.yml` silently drops + * every other file, so a recreate loses what they add. Scripted compose calls must therefore pass + * this whole list. Split on COMPOSE_PATH_SEPARATOR (default `:`, as compose does on Linux); + * relative entries are resolved against `composeDir`, the directory holding the compose files. + */ +export function composeFilesFor( + box: Readonly>, + composeDir: string +): string[] { + const separator = box.COMPOSE_PATH_SEPARATOR || ':'; + const listed = (box.COMPOSE_FILE ?? '') + .split(separator) + .map((entry) => entry.trim()) + .filter(Boolean); + return (listed.length > 0 ? listed : ['docker-compose.yml']).map((entry) => + isAbsolute(entry) ? entry : resolve(composeDir, entry) + ); +} + +/** + * `$$` (compose's escape for a literal `$`) or one reference: `$NAME`, `${NAME}`, `${NAME:-x}`, + * `${NAME?err}` and the other `${NAME...}` forms. A nested default (`${A:-${B}}`) is matched + * again at its own `$`. + */ +const REFERENCE = /\$\$|\$\{?([A-Za-z_][A-Za-z0-9_]*)/g; + +/** Every variable a compose file interpolates: compose reads values, not keys or comments. */ +export function composeVariableNames(composeText: string): Set { + const names = new Set(); + const visit = (node: unknown): void => { + if (typeof node === 'string') { + for (const match of node.matchAll(REFERENCE)) if (match[1]) names.add(match[1]); + } else if (Array.isArray(node)) { + node.forEach(visit); + } else if (node !== null && typeof node === 'object') { + Object.values(node).forEach(visit); + } + }; + visit(parseYaml(composeText)); + return names; +} + +/** + * Every variable the box's compose files (composeFilesFor) interpolate. A selected file that does + * not exist is skipped: docker compose refuses to run with it, so no running value can disagree. + */ +export function composeFileVariables( + box: Readonly>, + composeDir: string +): Set { + const names = new Set(); + for (const file of composeFilesFor(box, composeDir)) { + if (!existsSync(file)) continue; + for (const name of composeVariableNames(readFileSync(file, 'utf8'))) names.add(name); + } + return names; +} diff --git a/scripts/selfhost/deploy-harness.ts b/scripts/selfhost/deploy-harness.ts index 6f3c40e569..fe65739667 100644 --- a/scripts/selfhost/deploy-harness.ts +++ b/scripts/selfhost/deploy-harness.ts @@ -7,6 +7,8 @@ import { writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { BOX_RESERVED_PORTS } from './box-settings.js'; +import { composeFileVariables } from './compose-env.js'; +import { SELFHOST_DIR } from './deploy-steps.js'; const DEPLOY = resolve(import.meta.dirname, 'deploy.ts'); /** The repository's own tsx, not `npx tsx` (npx resolution costs seconds under load). */ @@ -36,10 +38,15 @@ export function runTsx( env: NodeJS.ProcessEnv = {} ): Promise<{ status: number; out: string }> { return new Promise((done, fail) => { - // The deploy honours shell port overrides as docker compose does (withComposePortOverrides), - // so the test runner's own environment must not leak any: only `env` sets them. + // The deploy honours a shell value for every variable compose interpolates, as docker compose + // does (withComposeShellOverrides), so the test runner's own environment must not leak any: + // only `env` sets them. const inherited = { ...process.env }; - for (const name of Object.keys(BOX_RESERVED_PORTS)) delete inherited[name]; + const composeNames = [ + ...composeFileVariables({}, SELFHOST_DIR), + ...Object.keys(BOX_RESERVED_PORTS), + ]; + for (const name of composeNames) delete inherited[name]; const child = spawn(TSX, [script, ...args], { env: { ...inherited, ...env } }); let out = ''; child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 2823bff2fa..56210ac57d 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -189,9 +189,9 @@ function readDeployInputs(): DeployInputs { const envFile = resolve(values['env-file'] ?? join(SELFHOST_DIR, '.env')); // The .env holds the bucket credential, which can read every deployed secret. assertPrivateFile(envFile); - // Box ports as docker compose will run them (a shell override beats the .env, F21 L5), checked - // against the lease range before anything is written. - const box = loadBoxEnv(envFile, process.env, (name) => + // The box as docker compose will run it (a shell variable any compose file interpolates beats + // the .env, F21 L5), its ports checked against the lease range before anything is written. + const box = loadBoxEnv(envFile, SELFHOST_DIR, process.env, (name) => log(`${name} from the shell environment overrides ${envFile}`) ); // Same default and base directory docker compose uses for SAM_SELFHOST_STATE_DIR. diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 8f6ecae018..6ab0304a9d 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -33,9 +33,10 @@ import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; -import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { dirname, join, relative, resolve } from 'node:path'; import { loadBoxEnv } from './box-settings.js'; +import { composeFilesFor } from './compose-env.js'; import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; @@ -95,27 +96,6 @@ function runCommand(command: string, args: string[], env?: NodeJS.ProcessEnv): R return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr }; } -/** - * The compose files a box runs with. `COMPOSE_FILE` in .env adds files to the stack, and docker - * compose reads it only when no `-f` is given: an explicit `-f docker-compose.yml` silently drops - * every other file, so a recreate loses what they add. Scripted compose calls must therefore pass - * this whole list. Split on COMPOSE_PATH_SEPARATOR (default `:`, as compose does on Linux); - * relative entries are resolved against `composeDir`, the directory holding the compose files. - */ -export function composeFilesFor( - box: Readonly>, - composeDir: string -): string[] { - const separator = box.COMPOSE_PATH_SEPARATOR || ':'; - const listed = (box.COMPOSE_FILE ?? '') - .split(separator) - .map((entry) => entry.trim()) - .filter(Boolean); - return (listed.length > 0 ? listed : ['docker-compose.yml']).map((entry) => - isAbsolute(entry) ? entry : resolve(composeDir, entry) - ); -} - /** `docker compose` arguments for this box: every compose file, then its .env, then `args`. */ function composeArgs(ctx: Pick, args: string[]): string[] { return [ @@ -135,9 +115,10 @@ export function loadBox( ): BoxContext { if (!existsSync(envFile)) throw new Error(`${envFile} does not exist`); assertPrivateFile(envFile); - // Ports as docker compose runs them (a shell override beats the .env), as deploy.ts reads them, - // and checked against the lease range before the upgrade touches the checkout or the stack. - const box = loadBoxEnv(envFile); + // The box as docker compose runs it (a shell variable any compose file interpolates beats the + // .env), as deploy.ts reads it, its ports checked against the lease range before the upgrade + // touches the checkout or the stack. + const box = loadBoxEnv(envFile, SELFHOST_DIR); if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); return { box, diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index ca099c5947..6c1d309464 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -12,11 +12,11 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { composeFilesFor } from './compose-env.js'; import { SELFHOST_DIR } from './deploy-steps.js'; import { imageRebuilds } from './image-rebuilds.js'; import { type BoxContext, - composeFilesFor, loadBox, type RunResult, runUpgrade, From 17e44dac91d674bc87bb469c29387e489b2a23f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:29:19 +0000 Subject: [PATCH 21/65] fix(selfhost): refuse a bare port for SAM_MX_LISTEN SAM_MX_LISTEN=2525 passed both the deploy's and Caddy start.sh's checks, but sam-mx hands it to Go's net.Listen("tcp", "2525"), which fails with "missing port in address", so the inbound-mail service restart-looped. Both validators now require a listen address with a host/port separator, [host]:port (:2525, 0.0.0.0:2525, [::]:2525), and refuse a bare port with a clear message. The live Caddy harness passes `:` for listen addresses. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 4 +++- deploy/selfhost/caddy/start.sh | 11 ++++++++++- scripts/selfhost/box-settings.test.ts | 18 +++++++++++++++--- scripts/selfhost/box-settings.ts | 12 ++++++++++-- scripts/selfhost/caddy-start.test.ts | 23 ++++++++++++++++++++++- scripts/selfhost/live/harness.ts | 7 ++++--- 6 files changed, 64 insertions(+), 11 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index c40c91db46..499152e72c 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -141,7 +141,9 @@ range to both the Worker and `.state/gateway.env`, and refuses a range that cont receive traffic meant for it. The deploy and upgrade check the ports as Docker Compose will run them (shell variables included, see below) as soon as they read `.env` and before anything starts, and Caddy's `start.sh` refuses to start when a port it is given lies in the range. celld, frps and -the mail collector run without capabilities, so their ports must be 1024 or above. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and +the mail collector run without capabilities, so their ports must be 1024 or above. +`SAM_MX_LISTEN` is a listen address, `[host]:port` (`:25`, `0.0.0.0:2525`, `[::]:2525`): a bare +port is refused, because sam-mx cannot listen on one. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and Caddy present to the Worker's loopback-only gateway routes (`/api/self-host/gateway/*`, which Caddy answers with 404 from outside). When `gateway.env` changes, the deploy stops until the stack is restarted (`docker compose up -d`), so the Worker never assumes settings frps is not diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh index 805b852f09..2d88f70573 100644 --- a/deploy/selfhost/caddy/start.sh +++ b/deploy/selfhost/caddy/start.sh @@ -71,7 +71,16 @@ for bound in "$start" "$end"; do ;; esac done -# SAM_MX_LISTEN is a listen address ([host]:port): its port is the part after the last ':'. +# SAM_MX_LISTEN is a listen address ([host]:port): its port is the part after the last ':'. sam-mx +# hands it to Go's net.Listen, which refuses a bare port, so the inbound-mail service would +# restart-loop: refuse it here. +case "${SAM_MX_LISTEN:-}" in +*:*) ;; +*) + echo "caddy: SAM_MX_LISTEN must be a listen address [host]:port (e.g. :25 or 0.0.0.0:2525), not a bare port" >&2 + exit 64 + ;; +esac for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT OBJECTSTORE_PORT \ OBJECTSTORE_CONSOLE_PORT MAIL_COLLECTOR_SMTP_PORT MAIL_COLLECTOR_UI_PORT SAM_MX_LISTEN; do eval "port=\"\${$name:-}\"" diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index a7bc2e766d..50dfd601e7 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -92,11 +92,15 @@ describe('tunnel port range', () => { }) ).toThrow(new RegExp(`contains ${name} \\(${fallback}\\)`)); } - expect(() => resolveTunnelPortRange({ [name]: '20500' })).toThrow( + const prefix = BOX_LISTEN_ADDRESSES.includes(name) ? ':' : ''; + expect(() => resolveTunnelPortRange({ [name]: `${prefix}20500` })).toThrow( new RegExp(`contains ${name} \\(20500\\)`) ); // Control: the same listener moved just outside the range is accepted. - expect(resolveTunnelPortRange({ [name]: '30000' })).toEqual({ start: 20000, end: 29999 }); + expect(resolveTunnelPortRange({ [name]: `${prefix}30000` })).toEqual({ + start: 20000, + end: 29999, + }); } ); @@ -346,7 +350,7 @@ describe('composeVariableNames', () => { }); describe('sam-mx listen address and unprivileged listeners (S4)', () => { - it.each([':20500', '0.0.0.0:20500', '[::]:20500', '20500'])( + it.each([':20500', '0.0.0.0:20500', '[::]:20500'])( 'fails the deploy when SAM_MX_LISTEN=%s lies in the range', (listen) => { expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( @@ -363,6 +367,14 @@ describe('sam-mx listen address and unprivileged listeners (S4)', () => { }); }); + // sam-mx hands it to Go's net.Listen, which refuses a bare port ("missing port in address"), so + // `2525` would leave the inbound-mail service restart-looping. + it.each(['2525', '20500', '25'])('refuses the bare port SAM_MX_LISTEN=%s', (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( + /SAM_MX_LISTEN must be a listen address \[host\]:port/ + ); + }); + it.each(['0.0.0.0:', ':x', 'smtp'])('refuses a malformed SAM_MX_LISTEN %s', (listen) => { expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow(/SAM_MX_LISTEN/); }); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index 771934a1db..df8746ce65 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -49,7 +49,8 @@ export const BOX_RESERVED_PORTS: Readonly> = { /** * Settings in BOX_RESERVED_PORTS that hold a listen address (`[host]:port`, sam-mx's `:25`) - * rather than a bare port: the port is the part after the last ':'. + * rather than a bare port: the port is the part after the last ':', and a value without one is + * refused (caddy/start.sh refuses it too). */ export const BOX_LISTEN_ADDRESSES: readonly string[] = ['SAM_MX_LISTEN']; @@ -153,7 +154,14 @@ function boxPort(box: Readonly>, name: string, fallback: if (!BOX_LISTEN_ADDRESSES.includes(name) || raw === undefined || raw === '') { return integer(raw, fallback, name, bounds); } - const port = raw.slice(raw.lastIndexOf(':') + 1); + // sam-mx passes it to Go's net.Listen, which refuses a bare port ("missing port in address"). + const separator = raw.lastIndexOf(':'); + if (separator < 0) { + throw new Error( + `${name} must be a listen address [host]:port (e.g. :${raw}), not a bare port: got ${raw}` + ); + } + const port = raw.slice(separator + 1); if (port === '') throw new Error(`${name} must end in :, got ${raw}`); return integer(port, fallback, name, bounds); } diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts index 06c5766c05..54f04783c7 100644 --- a/scripts/selfhost/caddy-start.test.ts +++ b/scripts/selfhost/caddy-start.test.ts @@ -64,7 +64,8 @@ describe('caddy/start.sh', () => { it.each(Object.keys(BOX_RESERVED_PORTS))( 'refuses to start when %s lies inside the lease range', (name) => { - const run = startSh({ ...composeEnv(), [name]: '20001' }); + const value = BOX_LISTEN_ADDRESSES.includes(name) ? ':20001' : '20001'; + const run = startSh({ ...composeEnv(), [name]: value }); expect(run.status).toBe(64); expect(run.out).toContain(`${name} (20001) lies inside the reverse-tunnel range 20000-29999`); expect(run.out).not.toContain('caddy run'); @@ -81,6 +82,26 @@ describe('caddy/start.sh', () => { } ); + // sam-mx hands SAM_MX_LISTEN to Go's net.Listen, which refuses a bare port ("missing port in + // address"): accepting `2525` here let the inbound-mail service restart-loop. + it.each(['2525', '25', ''])( + 'refuses SAM_MX_LISTEN=%j, which is not a listen address', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status).toBe(64); + expect(run.out).toContain('SAM_MX_LISTEN must be a listen address [host]:port'); + expect(run.out).not.toContain('caddy run'); + } + ); + + it.each([':2525', '0.0.0.0:2525', '[::]:2525'])( + 'control: accepts the listen address SAM_MX_LISTEN=%s', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status, run.out).toBe(0); + } + ); + // A malformed bound used to make `[ -ge ]` error, which `if` reads as false: the range check // was skipped and Caddy started with a box port inside the real range. it.each>([ diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts index 8d9d728076..720a8f8397 100644 --- a/scripts/selfhost/live/harness.ts +++ b/scripts/selfhost/live/harness.ts @@ -17,7 +17,7 @@ import { FRPC_DOWNLOAD_BASE_URL, FRPC_RELEASES, } from '../../../packages/cloud-init/src/reverse-tunnel'; -import { BOX_RESERVED_PORTS } from '../box-settings.js'; +import { BOX_LISTEN_ADDRESSES, BOX_RESERVED_PORTS } from '../box-settings.js'; export const REPO_ROOT = resolve(import.meta.dirname, '../../..'); /** Gitignored scratch directory (see .tmp/README.md). */ @@ -140,7 +140,7 @@ export const LIVE_TUNNEL_RANGE = { start: 20000, end: 20099 }; /** * Every setting caddy/start.sh checks, on free ports: each box port docker-compose.yml passes - * (BOX_RESERVED_PORTS; a bare port is also a valid listen address for SAM_MX_LISTEN) and the lease + * (BOX_RESERVED_PORTS; a listen address such as SAM_MX_LISTEN gets `:`) and the lease * range from gateway.env. Callers override what their test probes. */ export async function caddyBoxEnv(): Promise> { @@ -149,7 +149,8 @@ export async function caddyBoxEnv(): Promise> { REVERSE_TUNNEL_PORT_RANGE_END: String(LIVE_TUNNEL_RANGE.end), }; for (const name of Object.keys(BOX_RESERVED_PORTS)) { - env[name] = String(await freePort()); + const port = String(await freePort()); + env[name] = BOX_LISTEN_ADDRESSES.includes(name) ? `:${port}` : port; } return env; } From a06613f1267d3333a54dae1415d9abfaaa998756 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:35:26 +0000 Subject: [PATCH 22/65] test(selfhost): verify Caddy's certificate in the live suite (Sonar S4830, S5527) httpsGet turned TLS verification off (rejectUnauthorized: false). The live harness now reads the root of the Caddy container's internal CA (/data/caddy/pki/authorities/local/root.crt) once Caddy starts, and httpsGet trusts exactly that root with `ca` and checks the certificate against the request's host (servername, lowercased), so certificate and hostname checks stay on. Every request's Host is inside the *.SAM_DOMAIN wildcard Caddy serves, so no test needed a mismatch. Co-Authored-By: Claude Opus 5.5 --- .../live/access-log-keep-warm.live.test.ts | 2 +- .../live/caddy-fragments.live.test.ts | 3 +- scripts/selfhost/live/harness.ts | 46 ++++++++++++++----- .../selfhost/live/mail-collector.live.test.ts | 2 +- 4 files changed, 39 insertions(+), 14 deletions(-) diff --git a/scripts/selfhost/live/access-log-keep-warm.live.test.ts b/scripts/selfhost/live/access-log-keep-warm.live.test.ts index f1d6b25598..3f65bb7ebd 100644 --- a/scripts/selfhost/live/access-log-keep-warm.live.test.ts +++ b/scripts/selfhost/live/access-log-keep-warm.live.test.ts @@ -70,7 +70,7 @@ async function startCaddy(extra: Record): Promise { } const get = (stack: Stack, host: string, path: string, headers: Record = {}) => - httpsGet(stack.https, host, path, headers); + httpsGet(stack, host, path, headers); function accessLines(stack: Stack): Array> { return stack diff --git a/scripts/selfhost/live/caddy-fragments.live.test.ts b/scripts/selfhost/live/caddy-fragments.live.test.ts index 13d98b84c6..e6c1a6f0e6 100644 --- a/scripts/selfhost/live/caddy-fragments.live.test.ts +++ b/scripts/selfhost/live/caddy-fragments.live.test.ts @@ -168,7 +168,8 @@ describe.skipIf(skipWithoutDocker)('the box Caddy routes (live)', () => { 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), } : {}; - return httpsGet(ports.https, fullHost, path, { ...upgradeHeaders, ...headers }); + if (!caddy) return Promise.reject(new Error('Caddy did not start')); + return httpsGet(caddy, fullHost, path, { ...upgradeHeaders, ...headers }); } /** What celld (Deno / workerd URL parsing) could treat as the gateway route, generously. */ diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts index 720a8f8397..a30edf06cc 100644 --- a/scripts/selfhost/live/harness.ts +++ b/scripts/selfhost/live/harness.ts @@ -180,10 +180,19 @@ function caddyRunArgs(name: string, env: Record, detach: boolean ]; } -export interface CaddyRun { - container: string; +/** Where Caddy's internal CA (tls/internal.caddy) keeps its root certificate, in the container. */ +const CADDY_LOCAL_ROOT = '/data/caddy/pki/authorities/local/root.crt'; + +/** What httpsGet needs to reach one Caddy: its HTTPS port and the CA that signs its certificate. */ +export interface HttpsTarget { /** The HTTPS port (env.HTTPS_PORT). */ https: number; + /** PEM of the root that signs the certificate Caddy serves (its internal CA). */ + ca: string; +} + +export interface CaddyRun extends HttpsTarget { + container: string; stdout: () => string; stderr: () => string; /** Removes the container (idempotent). */ @@ -192,8 +201,9 @@ export interface CaddyRun { /** * Start the box's Caddy image through start.sh, exactly as docker-compose.yml does, with `env` - * (start with caddyBoxEnv() so start.sh's checks pass), and wait until it answers HTTPS on - * env.HTTPS_PORT with any status (a stack whose upstream is down answers 502). + * (start with caddyBoxEnv() so start.sh's checks pass; SAM_TLS_MODE internal), read the root of + * its internal CA, and wait until it answers HTTPS on env.HTTPS_PORT with a certificate that root + * verifies, with any status (a stack whose upstream is down answers 502). */ export async function startCaddy(env: Record): Promise { const container = `sam-live-caddy-${randomBytes(4).toString('hex')}`; @@ -202,16 +212,28 @@ export async function startCaddy(env: Record): Promise const run: CaddyRun = { container, https: Number(env.HTTPS_PORT), + ca: '', stdout: () => logs().stdout ?? '', stderr: () => logs().stderr ?? '', stop: () => void spawnSync(DOCKER, ['rm', '-f', container], { stdio: 'ignore' }), }; try { + run.ca = await waitFor( + "Caddy's internal CA root", + () => { + const read = spawnSync(DOCKER, ['exec', container, 'cat', CADDY_LOCAL_ROOT], { + encoding: 'utf8', + }); + return read.status === 0 && read.stdout.includes('BEGIN CERTIFICATE') ? read.stdout : ''; + }, + 120_000, + run.stderr + ); await waitFor( 'Caddy to serve TLS', async () => { try { - return (await httpsGet(run.https, `app.${env.SAM_DOMAIN}`, '/')).status > 0; + return (await httpsGet(run, `app.${env.SAM_DOMAIN}`, '/')).status > 0; } catch { return false; } @@ -246,12 +268,13 @@ export interface HttpsReply { } /** - * One HTTPS request to Caddy on 127.0.0.1:`port` for `host` (SNI and Host), with the exact raw - * `path` (Node does not normalize it) and the box's self-signed certificate accepted. For a - * request with WebSocket upgrade headers, a 101 reply's socket is closed at once. + * One HTTPS request to Caddy on 127.0.0.1:`target.https` for `host` (SNI and Host), with the exact + * raw `path` (Node does not normalize it). The certificate is verified against Caddy's internal CA + * (`target.ca`) and must name `host`, so a test cannot pass against the wrong site. For a request + * with WebSocket upgrade headers, a 101 reply's socket is closed at once. */ export function httpsGet( - port: number, + target: HttpsTarget, host: string, path: string, headers: Record = {} @@ -259,9 +282,10 @@ export function httpsGet( return new Promise((done, fail) => { const req = httpsRequest({ host: '127.0.0.1', - port, + port: target.https, + // SNI, and the name the certificate is checked against (DNS names are case-insensitive). servername: host.toLowerCase(), - rejectUnauthorized: false, + ca: target.ca, method: 'GET', path, headers: { Host: host, ...headers }, diff --git a/scripts/selfhost/live/mail-collector.live.test.ts b/scripts/selfhost/live/mail-collector.live.test.ts index 182663f550..539d7e961f 100644 --- a/scripts/selfhost/live/mail-collector.live.test.ts +++ b/scripts/selfhost/live/mail-collector.live.test.ts @@ -63,7 +63,7 @@ async function get( auth?: string ): Promise<{ status: number; body: string }> { const reply = await httpsGet( - stack.https, + stack, host, '/api/v1/messages', auth ? { Authorization: auth } : {} From 0a16c1e0feff55b0d723d2a8c3217cc5d8a0fce3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:35:26 +0000 Subject: [PATCH 23/65] ci(selfhost-live): install dependencies without lifecycle scripts (Sonar S6505) Nothing in the job needs one: celld runs esbuild's own bin entry (resolveEsbuild), which finds the platform package without esbuild's postinstall, and the build and live tests pass after a fresh `pnpm install --frozen-lockfile --ignore-scripts`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index adfc23ecde..339dd74a78 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1268,8 +1268,10 @@ jobs: node-version: '22' cache: 'pnpm' + # No lifecycle scripts: nothing in this job needs one. celld runs esbuild's own bin entry + # (celld-binary.ts resolveEsbuild), which finds the platform binary without a postinstall. - name: Install dependencies - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-scripts # celld bundles API modules (worker-core's shared-flight) through their built dist/, and the # live tests type-check against them. From 23db935a3150038521ef1f8991a7e51c7f36ec12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:35:26 +0000 Subject: [PATCH 24/65] fix(selfhost): run the Caddy image as a non-root user (Sonar S6471) The image now ends with USER 7101:7101. setcap gives /usr/bin/caddy cap_net_bind_service, so the unprivileged process still binds 80/443 with NET_BIND_SERVICE as the one capability compose leaves it (checked: uid 7101, CapEff 0x400, listening on :80 and :443 with --cap-drop ALL --cap-add NET_BIND_SERVICE). /data and /config belong to 7101 in the image. A box upgraded from a root Caddy has root-owned 0700 files in caddy-data and caddy-config, which uid 7101 could not read. A one-shot caddy-volumes service (root with only CHOWN and DAC_READ_SEARCH, no network, no-new-privileges) chowns both volumes to 7101 before every Caddy start; Caddy depends on it completing. DAC_READ_SEARCH is needed for the second and later runs (without it chown cannot walk 7101-owned 0700 directories). Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 5 +++++ deploy/selfhost/caddy/Dockerfile | 8 ++++++++ deploy/selfhost/docker-compose.yml | 25 ++++++++++++++++++++++++- 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 499152e72c..29b04beadf 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -108,6 +108,11 @@ images by digest. Caddy's modules (the DNS provider, `CADDY_DNS_MODULE`, and cad pinned by version and verified against the Go checksum database, and the build fails unless the binary carries exactly those versions; `sam-mx` modules are pinned by `go.sum`. +Neither image runs as root. Caddy runs as uid 7101 and binds 80/443 through its binary's file +capability (`NET_BIND_SERVICE`, the one capability compose leaves it). Before each start, the +one-shot `caddy-volumes` service hands the `caddy-data` and `caddy-config` volumes to that uid, +so a box whose certificates were written by an older, root Caddy keeps them. + A build still downloads from the network (Docker Hub, the Go module proxy, Alpine packages). The content is pinned, so a changed upstream fails the build rather than changing the image. diff --git a/deploy/selfhost/caddy/Dockerfile b/deploy/selfhost/caddy/Dockerfile index 52330b705d..45380af3ab 100644 --- a/deploy/selfhost/caddy/Dockerfile +++ b/deploy/selfhost/caddy/Dockerfile @@ -36,3 +36,11 @@ RUN set -eu; \ FROM caddy:2.11.9@sha256:ce773ec7a742ce15ee6bf2bb5f65882b9e2a4487b10733e6f1484f86e6b5d8bc COPY --from=build /usr/bin/caddy /usr/bin/caddy +# Never root. The file capability is the only privilege: it lets the unprivileged process bind +# 80/443, and compose keeps NET_BIND_SERVICE as the one capability (docker-compose.yml, service +# caddy). Set here rather than trusting COPY to carry the builder's. Caddy's state (XDG_DATA_HOME +# /data, XDG_CONFIG_HOME /config) belongs to the same uid; an existing box's volumes, written by +# a root Caddy, are handed over by the caddy-volumes service. +RUN setcap cap_net_bind_service=+ep /usr/bin/caddy \ + && chown -R 7101:7101 /data /config +USER 7101:7101 diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml index c81538c454..aafab1f178 100644 --- a/deploy/selfhost/docker-compose.yml +++ b/deploy/selfhost/docker-compose.yml @@ -70,6 +70,25 @@ services: # "Address already in use"; Docker's restart backoff covers that. restart: unless-stopped + # One-shot, before Caddy: Caddy runs as uid 7101 (caddy/Dockerfile), but a box upgraded from a + # release whose Caddy ran as root has root-owned files in its volumes, which Caddy could then no + # longer read or renew. Hands both volumes to 7101 and exits; idempotent, so it runs every start. + # Root only for this, with just the capabilities chown needs (CHOWN, and DAC_READ_SEARCH to walk + # directories 7101 already owns with mode 0700). + caddy-volumes: + image: sam-selfhost-caddy:local + pull_policy: never + network_mode: none + user: '0:0' + cap_drop: [ALL] + cap_add: [CHOWN, DAC_READ_SEARCH] + security_opt: ['no-new-privileges:true'] + entrypoint: ['/bin/chown', '-R', '7101:7101', '/data', '/config'] + volumes: + - caddy-data:/data + - caddy-config:/config + restart: 'no' + caddy: # Built only by `docker compose build caddy` (or when the image is missing): caddy/Dockerfile # pins both base images by digest and both modules by version. caddy/.dockerignore keeps the @@ -84,7 +103,11 @@ services: # Internet-facing and holds the DNS-01 identity: only the capability to bind 80/443. cap_drop: [ALL] cap_add: [NET_BIND_SERVICE] - depends_on: [celld] + depends_on: + celld: + condition: service_started + caddy-volumes: + condition: service_completed_successfully # Validates its settings (start.sh: mail collector password, keep-warm, frp login rate limit, # and that no box port lies inside the reverse-tunnel range) before starting Caddy. entrypoint: ['/bin/sh', '/etc/caddy/start.sh'] From 2661e088ebd809a2817a1b76a5192fb87ae237b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:35:26 +0000 Subject: [PATCH 25/65] chore(selfhost): clear Sonar code smells in the box scripts - S131: every `case` in caddy/start.sh and gcp-bootstrap.sh has a default arm. - S7688: gcp-bootstrap.sh is a bash script, so its tests use [[ ]]. - S7776: INHERITED_ENV (live harness) and UNPRIVILEGED_LISTENERS are Sets. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/caddy/start.sh | 3 +++ deploy/selfhost/gcp-bootstrap.sh | 35 +++++++++++++++++--------------- scripts/selfhost/box-settings.ts | 6 +++--- scripts/selfhost/live/harness.ts | 4 ++-- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh index 2d88f70573..58f0cf2ded 100644 --- a/deploy/selfhost/caddy/start.sh +++ b/deploy/selfhost/caddy/start.sh @@ -46,6 +46,7 @@ case "${SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:-60}" in echo "caddy: SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be a positive integer" >&2 exit 64 ;; +*) ;; esac case "${SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:-1m}" in [1-9]s | [1-9][0-9]s | [1-9]m | [1-9][0-9]m | 1h) ;; @@ -69,6 +70,7 @@ for bound in "$start" "$end"; do echo "caddy: REVERSE_TUNNEL_PORT_RANGE_START/END missing from gateway.env or not a number; run pnpm selfhost:deploy --init" >&2 exit 64 ;; + *) ;; esac done # SAM_MX_LISTEN is a listen address ([host]:port): its port is the part after the last ':'. sam-mx @@ -90,6 +92,7 @@ for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT O echo "caddy: $name must be set to a port number (docker-compose.yml passes every box port)" >&2 exit 64 ;; + *) ;; esac if [ "$port" -ge "$start" ] && [ "$port" -le "$end" ]; then echo "caddy: $name ($port) lies inside the reverse-tunnel range $start-$end; a node could be leased it. Change the port or REVERSE_TUNNEL_PORT_RANGE_START/END, then pnpm selfhost:deploy --init" >&2 diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index 0a13a0d269..8ebee5c1dd 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -59,9 +59,9 @@ NODE_ROLES=(roles/compute.instanceAdmin.v1 roles/compute.securityAdmin) die() { echo "gcp-bootstrap: $*" >&2; exit 1; } # `--flag value`: refuse a trailing flag with no value instead of failing on `shift 2`. -need_value() { [ "$2" -ge 2 ] || die "$1 needs a value (see --help)"; } +need_value() { [[ "$2" -ge 2 ]] || die "$1 needs a value (see --help)"; } -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --) shift ;; --project) need_value "$1" $#; PROJECT="$2"; shift 2 ;; @@ -79,10 +79,13 @@ done # grep checks below are line by line: refuse any value with a newline before they run. for value in "$PROJECT" "$API_URL" "$POOL_ID" "$PROVIDER_ID" "$SA_ID"; do - case "$value" in *$'\n'*|*$'\r'*) die "arguments must not contain line breaks" ;; esac + case "$value" in + *$'\n'*|*$'\r'*) die "arguments must not contain line breaks" ;; + *) ;; + esac done -[ -n "$PROJECT" ] || die "--project is required" -[ -n "$API_URL" ] || die "--api-url is required (https://api.)" +[[ -n "$PROJECT" ]] || die "--project is required" +[[ -n "$API_URL" ]] || die "--api-url is required (https://api.)" ISSUER="${API_URL%/}" case "$ISSUER" in https://api.*) ;; @@ -95,7 +98,7 @@ printf '%s' "$PROJECT" | grep -Eq '^[a-z][a-z0-9-]{4,28}[a-z0-9]$' || die "inval if command -v sha256sum >/dev/null 2>&1; then hash_cmd=(sha256sum); else hash_cmd=(shasum -a 256); fi INSTALL_HASH="$(printf '%s' "$ISSUER" | "${hash_cmd[@]}" | cut -c1-8)" -[ -n "$POOL_ID" ] || POOL_ID="sam-${INSTALL_HASH}" +[[ -n "$POOL_ID" ]] || POOL_ID="sam-${INSTALL_HASH}" printf '%s' "$POOL_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --pool-id: $POOL_ID" printf '%s' "$PROVIDER_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --provider-id: $PROVIDER_ID" printf '%s' "$SA_ID" | grep -Eq '^[a-z][a-z0-9-]{5,29}$' || die "invalid --service-account: $SA_ID" @@ -104,7 +107,7 @@ CONDITION="assertion.iss == '${ISSUER}'" # Read-only calls run in every mode; changes go through `change`. change() { - if [ "$DRY_RUN" -eq 1 ]; then + if [[ "$DRY_RUN" -eq 1 ]]; then printf 'would run: gcloud'; printf ' %q' "$@"; printf '\n' else gcloud "$@" @@ -116,7 +119,7 @@ change_retry() { local attempt for attempt in 1 2 3 4 5; do change "$@" && return 0 - [ "$attempt" -lt 5 ] && sleep "${GCP_BOOTSTRAP_RETRY_SECONDS:-5}" + [[ "$attempt" -lt 5 ]] && sleep "${GCP_BOOTSTRAP_RETRY_SECONDS:-5}" done return 1 } @@ -124,7 +127,7 @@ change_retry() { command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH" # The OIDC provider trusts the issuer the install advertises: check it before trusting it. -if [ "$CHECK_ISSUER" -eq 1 ]; then +if [[ "$CHECK_ISSUER" -eq 1 ]]; then discovery="$(curl -fsS --max-time 10 "${ISSUER}/.well-known/openid-configuration" 2>/dev/null)" \ || die "could not read ${ISSUER}/.well-known/openid-configuration: the node setup trusts this install's token issuer, so it runs once the install answers (after \`pnpm selfhost:deploy\`; README order). --skip-issuer-check skips the check if you are sure ${ISSUER} is right." issuer_re="$(printf '%s' "$ISSUER" | sed 's/[.]/\\./g')" @@ -134,7 +137,7 @@ fi PROJECT_NUMBER="$(gcloud projects describe "$PROJECT" --format='value(projectNumber)' 2>/dev/null)" \ || die "cannot read project ${PROJECT}; run 'gcloud auth login' as a project owner" -[ -n "$PROJECT_NUMBER" ] || die "project ${PROJECT} has no project number" +[[ -n "$PROJECT_NUMBER" ]] || die "project ${PROJECT} has no project number" echo "Project ${PROJECT} (${PROJECT_NUMBER}), issuer ${ISSUER}, pool ${POOL_ID}" echo "Note: use a project dedicated to SAM nodes. The node service account's roles apply to the whole project, so in a shared project it could also change the box VM and its firewall." @@ -147,7 +150,7 @@ change services enable "${NODE_APIS[@]}" --project="$PROJECT" # "exists" would then try to create a provider in a deleted pool (R13 D5). if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" \ --location=global --format='value(state)' 2>/dev/null)"; then - [ "$pool_state" != "DELETED" ] \ + [[ "$pool_state" != "DELETED" ]] \ || die "workload identity pool ${POOL_ID} was deleted (Google keeps a deleted pool for 30 days, and its id cannot be reused until it is purged). Either undelete it: gcloud iam workload-identity-pools undelete ${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --pool-id and put the new values in the platform credential (Admin -> Credentials)." # The service account binding below is pool-wide, so every provider in the pool would be # admitted: reuse the pool only when each provider in it (deleted ones too, which can be @@ -156,8 +159,8 @@ if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --projec --location=global --workload-identity-pool="$POOL_ID" --show-deleted \ --format='value(name,oidc.issuerUri)')" || die "cannot list the providers of pool ${POOL_ID}" while IFS=$'\t' read -r provider_name provider_issuer; do - [ -n "$provider_name" ] || continue - if [ "${provider_name##*/}" != "$PROVIDER_ID" ] || [ "$provider_issuer" != "$ISSUER" ]; then + [[ -n "$provider_name" ]] || continue + if [[ "${provider_name##*/}" != "$PROVIDER_ID" ]] || [[ "$provider_issuer" != "$ISSUER" ]]; then die "pool ${POOL_ID} is not dedicated to this install: its provider ${provider_name##*/} already trusts ${provider_issuer:-a non-OIDC issuer}, and the node service account would admit every provider in the pool. Use another --pool-id." fi done <<<"$pool_providers" @@ -171,12 +174,12 @@ fi if provider_state="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ --format='value(state)' 2>/dev/null)"; then - [ "$provider_state" != "DELETED" ] \ + [[ "$provider_state" != "DELETED" ]] \ || die "provider ${POOL_ID}/${PROVIDER_ID} was deleted (Google keeps it for 30 days). Undelete it: gcloud iam workload-identity-pools providers undelete ${PROVIDER_ID} --workload-identity-pool=${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --provider-id ." current="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ --format='value(oidc.issuerUri)')" - [ "$current" = "$ISSUER" ] \ + [[ "$current" = "$ISSUER" ]] \ || die "provider ${POOL_ID}/${PROVIDER_ID} already trusts ${current}, not ${ISSUER}; refusing to retarget it. Use another --pool-id." echo "provider ${PROVIDER_ID}: exists, issuer ${ISSUER}" else @@ -216,7 +219,7 @@ change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project=" --member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" \ --condition=None --quiet --format=none -[ "$DRY_RUN" -eq 1 ] && echo "Dry run: nothing was changed." +[[ "$DRY_RUN" -eq 1 ]] && echo "Dry run: nothing was changed." # The shape parseGcpCredential (apps/api/src/services/provider-credential-codecs.ts) reads. cat < = new Set([ 'CELLD_PORT', 'CELLD_INTERNAL_PORT', 'FRPS_BIND_PORT', 'MAIL_COLLECTOR_SMTP_PORT', 'MAIL_COLLECTOR_UI_PORT', -]; +]); /** * The box settings with the values docker compose will actually run with. Compose takes every @@ -150,7 +150,7 @@ const PORT = { min: 1024, max: 65535 }; /** A box listener's port (BOX_RESERVED_PORTS), from the setting or its compose default. */ function boxPort(box: Readonly>, name: string, fallback: number): number { const raw = box[name]; - const bounds = UNPRIVILEGED_LISTENERS.includes(name) ? PORT : { min: 1, max: 65535 }; + const bounds = UNPRIVILEGED_LISTENERS.has(name) ? PORT : { min: 1, max: 65535 }; if (!BOX_LISTEN_ADDRESSES.includes(name) || raw === undefined || raw === '') { return integer(raw, fallback, name, bounds); } diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts index a30edf06cc..78c3093529 100644 --- a/scripts/selfhost/live/harness.ts +++ b/scripts/selfhost/live/harness.ts @@ -44,13 +44,13 @@ export const skipWithoutDocker = !hasDocker && !process.env.CI; * Host variables a test child process may inherit (as the deploy's celldChildEnv does): what the * tools need to run and find their caches. Host secrets and cloud credentials stay out. */ -const INHERITED_ENV = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'RUST_LOG']; +const INHERITED_ENV: ReadonlySet = new Set(['PATH', 'HOME', 'TMPDIR', 'LANG', 'RUST_LOG']); /** The allowlisted host environment (plus any DOCKER_* setting) with `extra` on top. */ export function childEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { const env: NodeJS.ProcessEnv = {}; for (const [name, value] of Object.entries(process.env)) { - if (value !== undefined && (INHERITED_ENV.includes(name) || name.startsWith('DOCKER_'))) { + if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('DOCKER_'))) { env[name] = value; } } From 795bf674f9caa1d5bfaa4f3e89d09acf3bceb90b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:41:16 +0000 Subject: [PATCH 26/65] test(selfhost): read the non-root Caddy's environment as a privileged reader Caddy now runs as uid 7101 from a binary with a file capability, which makes the process non-dumpable: its /proc/1/environ is readable only by root with CAP_SYS_PTRACE, so the password-hash check reads it with `docker exec --privileged --user 0`. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/live/mail-collector.live.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/scripts/selfhost/live/mail-collector.live.test.ts b/scripts/selfhost/live/mail-collector.live.test.ts index 539d7e961f..da562b8696 100644 --- a/scripts/selfhost/live/mail-collector.live.test.ts +++ b/scripts/selfhost/live/mail-collector.live.test.ts @@ -127,9 +127,13 @@ describe.skipIf(skipWithoutDocker)('mail collector (live)', () => { }); it('keeps the plaintext password out of the running Caddy process', () => { - const environ = execFileSync(DOCKER, ['exec', stack.container, 'cat', '/proc/1/environ'], { - encoding: 'utf8', - }); + // Caddy runs as uid 7101 from a binary with a file capability, which makes the process + // non-dumpable: only a privileged reader (root with CAP_SYS_PTRACE) may see its environment. + const environ = execFileSync( + DOCKER, + ['exec', '--privileged', '--user', '0', stack.container, 'cat', '/proc/1/environ'], + { encoding: 'utf8' } + ); expect(environ).not.toContain(PASSWORD); expect(environ).toMatch(/MAIL_COLLECTOR_UI_HASH=\$2a\$/); }); From 754d86cde62b4a87af32d351f4f4bf44aded6a75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:48:34 +0000 Subject: [PATCH 27/65] docs(selfhost): README and gcp-bootstrap messages from the fresh BOX install A fresh install from the README (box round R18) found: - pnpm install needs a C/C++ toolchain (better-sqlite3); - step 3 writes .state/secrets.env before .state exists; - the first minutes after adding the GCP credential look broken (IAM propagation: impersonation 403s, migration-pending, possibly an hour of 'Price unavailable'); - an API-created node defaults to a Hetzner location; - without a GitHub App or GitLab no project, so no agent session, can be created; - gcp-bootstrap's expected first IAM-binding failure printed no retry notice, and its shared-pool refusal named the wrong cause for a second provider trusting the same issuer. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 21 +++++++++++++---- deploy/selfhost/gcp-bootstrap.sh | 11 ++++++--- scripts/selfhost/gcp-bootstrap.test.ts | 23 +++++++++++++++---- scripts/selfhost/testdata/fake-gcloud-iam.mjs | 7 ++++++ 4 files changed, 50 insertions(+), 12 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 29b04beadf..725b535966 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -22,7 +22,9 @@ DNS of their own. The fleet bucket (`CELLD_BUCKET`) is the durable copy of every ## Prerequisites - A Linux VM (GCE is what the team tests) with Docker Engine and the Compose plugin, Node.js 22, - pnpm 9 and git, and a checkout of this repository. + pnpm 9, git, a C/C++ build toolchain (`make`, `g++`, `python3`; on Ubuntu + `apt-get install build-essential`: `pnpm install` compiles `better-sqlite3`), and a checkout of + this repository. - A domain with a wildcard record `*.SAM_DOMAIN` pointing at the VM. SAM serves `api.`, `app.`, `ws-.` and `ws---.` under it; the apex is unused. - Inbound TCP 80 and 443 to the VM (and 25 for inbound agent email). @@ -44,7 +46,8 @@ From the repository root on the VM: 2. `cp deploy/selfhost/.env.example deploy/selfhost/.env && chmod 600 deploy/selfhost/.env`, then edit it. The comments in `.env.example` explain every setting. The bucket credential in it can read every Worker secret, so the file must stay private (the scripts refuse a readable one). -3. Optional: secrets for the Worker go in `deploy/selfhost/.state/secrets.env` (mode 0600), for +3. Optional: secrets for the Worker go in `deploy/selfhost/.state/secrets.env` (mode 0600; create + the directory first with `mkdir -m 700 deploy/selfhost/.state`), for example `SMTP_PASSWORD=...` and `BOOTSTRAP_OWNER_EMAIL=you@example.com`. With an owner email set, only that address can claim the new install by signing in with an emailed code. 4. `pnpm selfhost:deploy --init`: generates the platform keys (`.state/platform-keys.json`; back @@ -64,7 +67,14 @@ From the repository root on the VM: It runs after step 7 because it checks the token issuer the running install advertises. It creates a workload identity pool and provider trusting only this install, and a node service account, then prints the credential JSON to paste in **Admin -> Credentials** (Cloud Provider, - GCP). Add machines to the installation pool in **Admin -> Infrastructure**. + GCP). Add machines to the installation pool in **Admin -> Infrastructure**. For the first + few minutes after the credential is added, Google is still propagating the new service + account: the box logs impersonation 403s and the pool shows `migration-pending` until the + catalog publishes on its own. If the first price refresh falls in that window, machines show + "Price unavailable" until the next retry (`gcpCatalog.priceRetryMinutes`, 60 by default). + A node created through the API without `vmLocation` defaults to a Hetzner location (`nbg1`), + so pass a zone the pool offers. A previously deleted pool id is refused (Google keeps it for 30 days); pass a new + `--pool-id`. **Use a GCP project dedicated to SAM's nodes**, not the box's: the node service account's roles apply to the whole project, so in a shared project it could change or delete the box VM and its firewall. An existing `--pool-id` is reused only when its sole provider is this @@ -189,7 +199,10 @@ bucket's deploy manifests, so the bucket credential is the install's master key. network or the cloud metadata server on the box. - **Sealed secrets**: no key agent or KMS-backed encryption of the Worker's secrets. - **Guided credential login** (sandboxed agent sign-in on the box). -- **Hosted git.** +- **Hosted git.** Every project needs a repository, so on this install users can create projects + and run agents only once a GitHub App (the `GITHUB_*` Worker secrets in `.state/secrets.env`) + or a GitLab integration is configured. + Without one, sign-in, administration and nodes work, but no agent session can start. - **Backup, restore and teardown** commands. Back up the fleet bucket and `.state/` yourself. Do not put data on this box that you could not afford to lose or leak. diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index 8ebee5c1dd..4bc1106ad3 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -119,7 +119,9 @@ change_retry() { local attempt for attempt in 1 2 3 4 5; do change "$@" && return 0 - [[ "$attempt" -lt 5 ]] && sleep "${GCP_BOOTSTRAP_RETRY_SECONDS:-5}" + [[ "$attempt" -lt 5 ]] || break + echo "Retrying in ${GCP_BOOTSTRAP_RETRY_SECONDS:-5}s (attempt ${attempt} of 5): a new service account takes a few seconds to appear to IAM, so the error above is expected once." + sleep "${GCP_BOOTSTRAP_RETRY_SECONDS:-5}" done return 1 } @@ -160,8 +162,11 @@ if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --projec --format='value(name,oidc.issuerUri)')" || die "cannot list the providers of pool ${POOL_ID}" while IFS=$'\t' read -r provider_name provider_issuer; do [[ -n "$provider_name" ]] || continue - if [[ "${provider_name##*/}" != "$PROVIDER_ID" ]] || [[ "$provider_issuer" != "$ISSUER" ]]; then - die "pool ${POOL_ID} is not dedicated to this install: its provider ${provider_name##*/} already trusts ${provider_issuer:-a non-OIDC issuer}, and the node service account would admit every provider in the pool. Use another --pool-id." + if [[ "${provider_name##*/}" != "$PROVIDER_ID" ]]; then + die "pool ${POOL_ID} holds provider ${provider_name##*/} (issuer ${provider_issuer:-not OIDC}) besides ${PROVIDER_ID}, deleted providers included, and the node service account would admit every provider in the pool. Use another --pool-id." + fi + if [[ "$provider_issuer" != "$ISSUER" ]]; then + die "pool ${POOL_ID} is not dedicated to this install: its provider ${PROVIDER_ID} trusts ${provider_issuer:-a non-OIDC issuer}, not ${ISSUER}. Use another --pool-id." fi done <<<"$pool_providers" echo "pool ${POOL_ID}: exists" diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index d7d5fdd398..c5bf6a6f85 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -157,10 +157,20 @@ describe('pnpm selfhost:gcp-bootstrap', () => { other ); expect(result.status).not.toBe(0); - expect(result.stderr).toContain(`already trusts ${ISSUER}`); + expect(result.stderr).toContain(`provider sam-api trusts ${ISSUER}, not ${other}`); expect(gcp().providers['sam-api'].issuer).toBe(ISSUER); }); + it('says a failed first IAM binding on the new service account is being retried', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER], ISSUER, { + FAKE_GCLOUD_FAIL_ONCE: 'projects add-iam-policy-binding', + GCP_BOOTSTRAP_RETRY_SECONDS: '0', + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('Retrying in 0s (attempt 1 of 5)'); + expect(gcp().bindings.length).toBeGreaterThan(0); + }); + // S1: the node service account binding is pool-wide, so a reused pool must hold nothing but // this install's provider. describe('an existing --pool-id', () => { @@ -185,9 +195,8 @@ describe('pnpm selfhost:gcp-bootstrap', () => { seedPool({ 'github-actions': { issuer: 'https://token.actions.githubusercontent.com' } }); const result = run(args); expect(result.status).not.toBe(0); - expect(result.stderr).toContain('pool sam-shared is not dedicated to this install'); expect(result.stderr).toContain( - 'provider github-actions already trusts https://token.actions.githubusercontent.com' + 'pool sam-shared holds provider github-actions (issuer https://token.actions.githubusercontent.com) besides sam-api' ); expect(changes(result)).toEqual([]); expect(gcp().bindings).toEqual([]); @@ -197,7 +206,9 @@ describe('pnpm selfhost:gcp-bootstrap', () => { seedPool({ 'sam-api': { issuer: ISSUER }, 'sam-api-2': { issuer: ISSUER } }); const result = run(args); expect(result.status).not.toBe(0); - expect(result.stderr).toContain('provider sam-api-2 already trusts'); + expect(result.stderr).toContain( + `holds provider sam-api-2 (issuer ${ISSUER}) besides sam-api` + ); expect(changes(result)).toEqual([]); }); @@ -205,7 +216,9 @@ describe('pnpm selfhost:gcp-bootstrap', () => { seedPool({ other: { issuer: 'https://idp.example.com', state: 'DELETED' } }); const result = run(args); expect(result.status).not.toBe(0); - expect(result.stderr).toContain('provider other already trusts https://idp.example.com'); + expect(result.stderr).toContain( + 'holds provider other (issuer https://idp.example.com) besides sam-api' + ); expect(changes(result)).toEqual([]); }); diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index 7c59935cd9..81e020295f 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -26,6 +26,13 @@ const fail = (message) => { process.exit(1); }; const out = (text) => process.stdout.write(`${text}\n`); +// FAKE_GCLOUD_FAIL_ONCE=: the first matching call fails, as a new service +// account's first IAM binding does on real GCP while it propagates. +const failOnce = process.env.FAKE_GCLOUD_FAIL_ONCE; +if (failOnce && cmd.startsWith(failOnce) && !existsSync(join(STATE, 'failed-once'))) { + writeFileSync(join(STATE, 'failed-once'), cmd); + fail('Service account does not exist (propagating)'); +} const format = flag('format') ?? ''; if (cmd.startsWith('projects describe')) out('123456789012'); From ba95e290915d8e67ac6e5570c13bb0bff2273653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:52:28 +0000 Subject: [PATCH 28/65] docs(selfhost): build steps share the box's egress; task file records BOX R18 and owed proofs Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 5 +- .../2026-11-19-l22-selfhost-core-packaging.md | 60 +++++++++++++------ 2 files changed, 47 insertions(+), 18 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 725b535966..94f4748d2c 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -124,7 +124,10 @@ one-shot `caddy-volumes` service hands the `caddy-data` and `caddy-config` volum so a box whose certificates were written by an older, root Caddy keeps them. A build still downloads from the network (Docker Hub, the Go module proxy, Alpine packages). The -content is pinned, so a changed upstream fails the build rather than changing the image. +content is pinned, so a changed upstream fails the build rather than changing the image. A build +step has the same unrestricted network access as everything else on this box, the cloud metadata +server included (see [Not included yet](#not-included-yet)): pinning, not a fence, is what keeps an +upstream from changing what runs. After changing a build argument in `.env` (`CADDY_DNS_MODULE`), run `docker compose build caddy` yourself, then `docker compose up -d`: `selfhost:upgrade` rebuilds only for changes in the diff --git a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md index 901447db45..5315c37e7a 100644 --- a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md +++ b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md @@ -69,37 +69,63 @@ and trimmed. Nothing in L22 may change Cloudflare behaviour. - [x] task-completion-validator PASS (MEDIUM fixed), CI, CodeRabbit (9 threads fixed), merged #2902 as fa04695d2, Deploy Production 44478774764 success -### PR 3 (L22c): box runtime (self-host only) +### PR 3 (L22c): box runtime (self-host only), #2906 - [x] deploy/selfhost compose (no key-agent, fence, docker-proxy, metadata-proxy), Caddy with the F21 fixes (L1 double-encoding, L5 ports as compose runs them, L6 narrow 404, L7 frp Login limit), frps, objectstore, .env.example, gcp-bootstrap.sh -- [x] F11 fix: upgrade builds only the local images whose build inputs changed, then `up -d` - without `--build` (`image-rebuilds.ts`) +- [x] F11: builds are explicit and change-gated. Upgrade builds only the local images whose build + inputs changed, then `up -d` without `--build` (`image-rebuilds.ts`). Both images pin base + images by digest and modules by checksum. Build steps keep the box's unrestricted egress + (metadata server included), as the runtime does, because the egress fence (L23) is held; + the README says so. - [x] Docker live tests + CI job on self-host paths only (D9) - [x] Operator README marked experimental, including R2_S3_REGION for s3:// - [x] Rebased onto main after #2902 (upgrade retry/box-scoped compose kept, F11 merged in) -- [x] Review fixes: architecture (CI filters, no build in Validate Deploy Scripts, live harness - dedup, gcp-bootstrap pinned to GCP_REQUIRED_APIS / SA_PROJECT_ROLES, loadBoxEnv); security - MEDIUMs (shared-pool refusal, celld/frps no caps + read-only, 24-char objectstore secret, - sam-mx port reserved + deploy-time port check) and LOWs (site-level X-SAM-* strip, child env - allowlist, build-arg README note) +- [x] Review fixes: + - Architecture: CI filters, no build in Validate Deploy Scripts, live harness dedup, + gcp-bootstrap pinned to GCP_REQUIRED_APIS / SA_PROJECT_ROLES, loadBoxEnv. + - Security MEDIUMs: shared-pool refusal, celld/frps with no caps and read-only, 24-char + objectstore secret, sam-mx port reserved plus a deploy-time port check. + - Security LOWs: site-level X-SAM-* strip, child env allowlist, build-arg README note. + - Codex P2s: shell precedence for every compose variable; SAM_MX_LISTEN must be host:port. + - SonarCloud: live-suite TLS verification, `--ignore-scripts`, non-root Caddy plus the + caddy-volumes ownership hand-off, smells. + - Secret Scan: reviewed-baseline entry for the synthetic deploy-harness fixture. - [ ] Security HIGH (gcp-bootstrap pool/* binding admits a user credential naming the pool; same shape in main's guided setup): Worker fix is SAM task 01M7SB8FRZ08M5NEX9WGM74X61 / PR #2905. Coordinator: do not merge PR 3 until #2905 is deployed, then re-run security-auditor. -- [ ] BOX: fresh teardown + rebuild from this head; prove 0255 lease table on a fresh box; - L19 celld teardown OWED (guided login not installed); L13 metered ceiling only if a platform - AI key exists -- [ ] task-completion-validator, CI, CodeRabbit, merge, Deploy Production +- [x] BOX round R18 (fresh teardown + README rebuild from c4fac57ca, upgrade to 795bf674f): + - Passed: install, admin by email, GCP reverse-tunnel node heartbeat through frps, the 0255 + lease table on fresh D1, and an upgrade that rebuilt only Caddy. Evidence is in the #2906 + body. + - README findings fixed in 754d86cde. +- [x] Owed, as agreed by the coordinator on 2026-11-19: + - Agent session on a box: owed to the first slice that gives a box a repository source + (hosted git). Main plus L22 cannot create a project: artifacts is disabled and there is no + GitHub/GitLab app. + - L19 celld guided-login teardown: no gVisor; guided login is held. + - L13 metered ceiling: the box has no platform AI key. +- [x] task-completion-validator: the agent-session gap is recorded as owed (above) and the HIGH + is blocked on #2905. The live suite passed locally at 795bf674f (6 files, 208 tests); CI + `Self-host Live (Docker)` runs on every head. +- [ ] CI green, merge after #2905 deploys plus a security re-review, Deploy Production -Not fixed here (accepted as tracked by the coordinator): F21 L4 `port_range_cooling_down` is -fail-fast in `apps/api/src/selfhost/reverse-tunnel/leases.ts` and the shared Worker failure path; -idea 01M7MK0PCF032CT45Z45HRSDEQ. Security LOWs left: access-log redaction matches literal path -spellings only; frp Login limit is per address (IPv6 rotation). +Not fixed here (accepted as tracked by the coordinator): +- F21 L4 `port_range_cooling_down` is fail-fast in `apps/api/src/selfhost/reverse-tunnel/leases.ts` + and in the shared Worker failure path; idea 01M7MK0PCF032CT45Z45HRSDEQ. +- Security LOWs: access-log redaction matches literal path spellings only, and the frp Login limit + is per address (IPv6 rotation). +- Worker defects seen again on the BOX, all outside L22's scope and reported to the coordinator: + - `DEFAULT_VM_LOCATION` nbg1 on GCP-only installs. + - A 60-minute price backoff after a transient first failure. + - JWT kid `key-1970-01`. + - A node shows healthy before its first heartbeat. ## Acceptance criteria - Cloudflare Worker import graph unchanged by PRs 2-3; Worker behaviour unchanged except the bounded joins in PR 1. - A box installed from main alone deploys, serves the app, creates an admin by email, runs one - agent session and heartbeats a reverse-tunnel node. + agent session and heartbeats a reverse-tunnel node. (The agent session is OWED to the hosted-git + slice, per the coordinator on 2026-11-19; every other part was proven in BOX round R18.) From 7ae5db3dddefa861670d3be498bc7a3367b7994d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:52:40 +0000 Subject: [PATCH 29/65] docs(tasks): format L22 task file Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-19-l22-selfhost-core-packaging.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md index 5315c37e7a..79372151c6 100644 --- a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md +++ b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md @@ -112,6 +112,7 @@ and trimmed. Nothing in L22 may change Cloudflare behaviour. - [ ] CI green, merge after #2905 deploys plus a security re-review, Deploy Production Not fixed here (accepted as tracked by the coordinator): + - F21 L4 `port_range_cooling_down` is fail-fast in `apps/api/src/selfhost/reverse-tunnel/leases.ts` and in the shared Worker failure path; idea 01M7MK0PCF032CT45Z45HRSDEQ. - Security LOWs: access-log redaction matches literal path spellings only, and the frp Login limit From 6124df80c3518a5d9b992edaacacbb33cdfa832b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 11:19:18 +0000 Subject: [PATCH 30/65] task: plan self-host-only hosted git landing --- .../2026-11-19-selfhost-hosted-git-h2.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 tasks/active/2026-11-19-selfhost-hosted-git-h2.md diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md new file mode 100644 index 0000000000..709a5b1c7c --- /dev/null +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -0,0 +1,27 @@ +# H2: SAM-hosted git on self-host only + +## Problem +A box built from main needs a repository source before it can create a project and run an agent. Owner D7 narrowed: HostedGitRepo is celld-only, never a Cloudflare export, binding, import or migration. Main v23 is unrelated and untouched. + +## Research and preflight +Classes: cross-component, business logic, security sensitive, infra, docs sync. Main 08abf1393 already has L16's backend fallback selection and L22b's single self-host entry. L22c #2906 remains open, held on #2905 and security review; coordinator confirmed import/trim can proceed while celld wiring and BOX wait for L22c main. Integration has hosted-git runtime and conformance fixtures, but shared routes import local implementation (M4 HIGH-4). + +Trace: project-create -> resolved Artifacts backend -> seed/import via backend remoteFetch -> authenticated self-host git HTTP -> HostedGitRepo SQLite. Runtime callback -> active workspace/current generation -> backend createToken with workspace identity -> git HTTP rechecks membership/lifecycle/generation -> push commits ref. Cloudflare keeps binding or null and global fetch, with no registered fallback. + +Use existing L16 selection, extend its optional token context and fetch/import contract. Move implementation under selfhost; preserve Cloudflare semantics. Import with git checkout paths, no cherry-pick. Tests must exercise real git over smart HTTP and prove import-graph detection by introducing a forbidden import. Relevant lessons: callback routing/auth rule 34; DO interleaving rule 45; cross-boundary/vertical tests rules 23/35; no secret readback rule 83. Docs: operator README only (experimental self-host slice). + +## Checklist +- [ ] Fresh branch from main; import selected integration paths and trim +- [ ] Move DO and hosted-git services under selfhost; dgit/pako excluded from Worker graph +- [ ] Extend generic fallback seam: workspace-bound token context, remoteFetch and import; remove shared local-backend branches +- [ ] Wire celld-only binding/export/tag via L22 single entry after L22c lands +- [ ] Add conformance/auth/lifecycle/token tests and import-graph violation proof +- [ ] Document self-host repository support and limits +- [ ] Local lint/typecheck/tests/build; security, Cloudflare, architecture and completion reviews +- [ ] Draft PR then ready/CI/CodeRabbit request and wait +- [ ] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off +- [ ] BOX existing bucket-mode deploy adds selfhost-hosted-git-v1; create project; OpenCode free reply; agent push verified; cleanup and BOX FREE +- [ ] Merge main; all gates current head; announce merging/merged SHA; production success; idea SHIPPED + +## Acceptance +No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; no CF migration. Shared seam inert on Cloudflare. BOX upgrade succeeds with new celld tag, project creation and actual short free-model agent reply/push work. Every resource created by this task cleaned up. All required gates pass on merge head. From cd175f708471c8a2b7a75625329e976d425b99de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 11:56:55 +0000 Subject: [PATCH 31/65] fix(selfhost): GCP bootstrap trusts platform tokens only; refuse disabled pools Security re-review after #2905 (MEDIUM): the bootstrap provider admitted every token of this install's issuer, with a pool/* binding. A user who claimed the pool in SAM before the operator saved the platform credential could still reach the node service account. - Provider condition adds assertion.user_id.startsWith('platform:'). SAM signs platform: only for the installation's own credential (gcpIdentityTokenUserId). Re-running narrows a provider made by an earlier version (update-oidc). - Refuse a disabled pool or provider (state stays ACTIVE when disabled, and neither exchanges tokens) with the enable command (Codex review). - README and the binding comment describe #2905's guard instead of the stale "known gap". Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 10 +-- deploy/selfhost/gcp-bootstrap.sh | 46 ++++++++--- scripts/selfhost/gcp-bootstrap.test.ts | 76 +++++++++++++++++-- scripts/selfhost/testdata/fake-gcloud-iam.mjs | 9 ++- 4 files changed, 119 insertions(+), 22 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 94f4748d2c..59acbeff0c 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -78,11 +78,11 @@ From the repository root on the VM: **Use a GCP project dedicated to SAM's nodes**, not the box's: the node service account's roles apply to the whole project, so in a shared project it could change or delete the box VM and its firewall. An existing `--pool-id` is reused only when its sole provider is this - install's. Known gap: the service account trusts every token this install signs for that - provider, and SAM does not yet stop a user's own GCP credential from naming this pool, so a - user of the install could act as the node service account (fix tracked as SAM task - 01M7SB8FRZ08M5NEX9WGM74X61). Until then, give accounts on a GCP-node install only to people - you would trust with that project. + install's. The provider admits only tokens SAM signs for the installation's own credential + (`assertion.user_id` starts with `platform:`), and re-running the script narrows a provider + made by an earlier version. SAM also refuses a user's GCP credential that names a pool the + platform credential already holds, so add the printed credential in Admin -> Credentials as + soon as the script finishes. `pnpm selfhost:deploy --dry-run` prints the Worker configuration it would deploy, secrets redacted. diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index 4bc1106ad3..3765f225bf 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -103,7 +103,12 @@ printf '%s' "$POOL_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --poo printf '%s' "$PROVIDER_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --provider-id: $PROVIDER_ID" printf '%s' "$SA_ID" | grep -Eq '^[a-z][a-z0-9-]{5,29}$' || die "invalid --service-account: $SA_ID" SA_EMAIL="${SA_ID}@${PROJECT}.iam.gserviceaccount.com" -CONDITION="assertion.iss == '${ISSUER}'" +# Only tokens SAM signs for the installation's own (platform) credential: SAM sets +# user_id = platform: for those and the bare owner id for a user's credential +# (gcpIdentityTokenUserId in apps/api/src/services/gcp-sts.ts). So a user's GCP credential that +# names this pool cannot reach the node service account, even if that user claimed the pool in +# SAM before the operator saved the platform credential. +CONDITION="assertion.iss == '${ISSUER}' && assertion.user_id.startsWith('platform:')" # Read-only calls run in every mode; changes go through `change`. change() { @@ -154,6 +159,12 @@ if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --projec --location=global --format='value(state)' 2>/dev/null)"; then [[ "$pool_state" != "DELETED" ]] \ || die "workload identity pool ${POOL_ID} was deleted (Google keeps a deleted pool for 30 days, and its id cannot be reused until it is purged). Either undelete it: gcloud iam workload-identity-pools undelete ${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --pool-id and put the new values in the platform credential (Admin -> Credentials)." + # A disabled pool still reports state ACTIVE (`disabled` is a separate field) and exchanges no + # tokens, so every node exchange would fail later. + pool_disabled="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" \ + --location=global --format='value(disabled)')" || die "cannot read workload identity pool ${POOL_ID}" + [[ "${pool_disabled,,}" != "true" ]] \ + || die "workload identity pool ${POOL_ID} is disabled, and a disabled pool exchanges no tokens. Either enable it: gcloud iam workload-identity-pools update ${POOL_ID} --project=${PROJECT} --location=global --no-disabled, then run this again; or pass --pool-id ." # The service account binding below is pool-wide, so every provider in the pool would be # admitted: reuse the pool only when each provider in it (deleted ones too, which can be # undeleted) is PROVIDER_ID trusting this install's issuer. @@ -181,15 +192,30 @@ if provider_state="$(gcloud iam workload-identity-pools providers describe "$PRO --format='value(state)' 2>/dev/null)"; then [[ "$provider_state" != "DELETED" ]] \ || die "provider ${POOL_ID}/${PROVIDER_ID} was deleted (Google keeps it for 30 days). Undelete it: gcloud iam workload-identity-pools providers undelete ${PROVIDER_ID} --workload-identity-pool=${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --provider-id ." + provider_disabled="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(disabled)')" || die "cannot read provider ${POOL_ID}/${PROVIDER_ID}" + [[ "${provider_disabled,,}" != "true" ]] \ + || die "provider ${POOL_ID}/${PROVIDER_ID} is disabled, and a disabled provider exchanges no tokens. Either enable it: gcloud iam workload-identity-pools providers update-oidc ${PROVIDER_ID} --workload-identity-pool=${POOL_ID} --project=${PROJECT} --location=global --no-disabled, then run this again; or pass --provider-id ." current="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ --format='value(oidc.issuerUri)')" [[ "$current" = "$ISSUER" ]] \ || die "provider ${POOL_ID}/${PROVIDER_ID} already trusts ${current}, not ${ISSUER}; refusing to retarget it. Use another --pool-id." echo "provider ${PROVIDER_ID}: exists, issuer ${ISSUER}" + # A provider made by an earlier version of this script admits every token of this issuer: + # narrow it to the platform-only condition. + current_condition="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(attributeCondition)')" \ + || die "cannot read the attribute condition of provider ${POOL_ID}/${PROVIDER_ID}" + if [[ "$current_condition" != "$CONDITION" ]]; then + change iam workload-identity-pools providers update-oidc "$PROVIDER_ID" --project="$PROJECT" \ + --location=global --workload-identity-pool="$POOL_ID" --attribute-condition="$CONDITION" + fi else - # Only this install's issuer is admitted (attributeCondition), and only tokens addressed to - # this provider: SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). Mapping + # Only this install's platform tokens are admitted (attributeCondition), and only tokens + # addressed to this provider: SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). Mapping # matches the guided setup (gcp-setup.ts). change iam workload-identity-pools providers create-oidc "$PROVIDER_ID" --project="$PROJECT" \ --location=global --workload-identity-pool="$POOL_ID" --display-name="SAM API" \ @@ -211,14 +237,12 @@ for role in "${NODE_ROLES[@]}"; do --role="$role" --condition=None --quiet --format=none done -# Scope: the whole pool. Its only provider (checked above on every run) admits tokens whose -# issuer is this install's API origin and whose audience is that provider, so the binding admits -# ANY token this installation signs for the provider's audience, not only the ones it signs for -# node provisioning. SAM does not currently stop a user's own GCP credential from naming this -# pool, provider and service account, so a user of this install could obtain such a token and act -# as the node service account; closing that needs a Worker change (SAM task -# 01M7SB8FRZ08M5NEX9WGM74X61). Any provider added to this pool later would inherit the service -# account too, so do not add providers to it. +# Scope: the whole pool. Its only provider (checked above on every run) admits only tokens whose +# issuer is this install's API origin, whose audience is that provider, and whose user_id is a +# platform identity, so the binding admits the tokens SAM signs for the installation's own +# credential and no user's. SAM also refuses a user credential that names a pool the platform +# credential holds (gcp-wif-pool-ownership.ts). Any provider added to this pool later would +# inherit the service account too, so do not add providers to it. change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ --role=roles/iam.workloadIdentityUser \ --member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" \ diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index c5bf6a6f85..24915a56e8 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -16,6 +16,9 @@ vi.setConfig({ testTimeout: 60_000 }); const SCRIPT = resolve(import.meta.dirname, '../../deploy/selfhost/gcp-bootstrap.sh'); const ISSUER = 'https://api.vmtest.example.org'; +// Platform tokens only: SAM signs user_id = platform: for the installation's credential +// and the bare owner id for a user's (gcpIdentityTokenUserId, apps/api/src/services/gcp-sts.ts). +const CONDITION = `assertion.iss == '${ISSUER}' && assertion.user_id.startsWith('platform:')`; // The fake keeps Google Cloud state in $STATE/gcp.json and appends every call to $STATE/calls. const FAKE_GCLOUD = `#!/usr/bin/env bash @@ -52,8 +55,11 @@ function run(args: string[], advertisedIssuer = ISSUER, env: NodeJS.ProcessEnv = } interface FakeGcp { - pools: Record; - providers: Record; + pools: Record; + providers: Record< + string, + { issuer: string; pool?: string; state?: string; condition?: string; disabled?: boolean } + >; accounts: Record; bindings: string[]; } @@ -77,7 +83,7 @@ function calls(): string[] { } const MUTATING = - /^(services enable|iam workload-identity-pools( providers)? create|iam service-accounts create|projects add-iam-policy-binding|iam service-accounts add-iam-policy-binding)/; + /^(services enable|iam workload-identity-pools( providers)? (create|update)|iam service-accounts create|projects add-iam-policy-binding|iam service-accounts add-iam-policy-binding)/; describe('pnpm selfhost:gcp-bootstrap', () => { it('creates the pool, issuer-scoped provider, service account and bindings, and prints the five form values', () => { @@ -86,7 +92,8 @@ describe('pnpm selfhost:gcp-bootstrap', () => { const provider = result.calls.find((c) => c.includes('providers create-oidc'))!; expect(provider).toContain(`--issuer-uri=${ISSUER}`); - expect(provider).toContain(`--attribute-condition=assertion.iss == '${ISSUER}'`); + expect(provider).toContain(`--attribute-condition=${CONDITION}`); + expect(gcp().providers['sam-api'].condition).toBe(CONDITION); expect(provider).toContain( '--allowed-audiences=https://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/' ); @@ -135,7 +142,7 @@ describe('pnpm selfhost:gcp-bootstrap', () => { const second = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); expect(second.status, second.stderr).toBe(0); const secondCalls = second.calls.slice(before); - expect(secondCalls.filter((c) => / create/.test(c))).toEqual([]); + expect(secondCalls.filter((c) => / (create|update)/.test(c))).toEqual([]); expect(second.stdout.split('Add the installation')[1]).toBe( first.stdout.split('Add the installation')[1] ); @@ -149,6 +156,65 @@ describe('pnpm selfhost:gcp-bootstrap', () => { expect(result.stdout).toContain('Dry run: nothing was changed.'); }); + describe('a provider made by an earlier version (issuer-only condition)', () => { + const narrow = (extra: string[] = []) => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.providers['sam-api'].condition = `assertion.iss == '${ISSUER}'`; + }); + return run(['--project', 'sam-vm-test', '--api-url', ISSUER, ...extra]); + }; + + it('is narrowed to platform tokens on the next run', () => { + const result = narrow(); + expect(result.status, result.stderr).toBe(0); + expect(gcp().providers['sam-api'].condition).toBe(CONDITION); + expect(result.calls.filter((c) => c.includes('providers update-oidc'))).toHaveLength(1); + }); + + it('dry run only shows the update', () => { + const result = narrow(['--dry-run']); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain( + 'would run: gcloud iam workload-identity-pools providers update-oidc' + ); + expect(gcp().providers['sam-api'].condition).toBe(`assertion.iss == '${ISSUER}'`); + }); + }); + + it('a disabled pool (state still ACTIVE): stops with the enable command, binds nothing', () => { + expect( + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-off']).status + ).toBe(0); + setGcp((db) => { + db.pools['sam-off'].disabled = true; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-off']); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('workload identity pool sam-off is disabled'); + expect(result.stderr).toContain('--no-disabled'); + // API enablement runs first and is idempotent; nothing in IAM changes. + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services enable')) + ).toEqual([]); + }); + + it('a disabled provider: stops with the enable command, binds nothing', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.providers['sam-api'].disabled = true; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(/provider sam-[0-9a-f]{8}\/sam-api is disabled/); + // API enablement runs first and is idempotent; nothing in IAM changes. + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services enable')) + ).toEqual([]); + }); + it('refuses to retarget a provider that already trusts another install', () => { run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-shared']); const other = 'https://api.other.example.org'; diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index 81e020295f..1f1eabe386 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -51,8 +51,14 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { if (!db.providers[id]) fail('not found'); if (format.includes('issuerUri')) out(db.providers[id].issuer); if (format.includes('state')) out(db.providers[id].state ?? 'ACTIVE'); + if (format.includes('attributeCondition')) out(db.providers[id].condition ?? ''); + if (format.includes('disabled')) out(db.providers[id].disabled ? 'True' : 'False'); } else if (op === 'create-oidc') { - db.providers[id] = { issuer: flag('issuer-uri'), pool }; + db.providers[id] = { issuer: flag('issuer-uri'), pool, condition: flag('attribute-condition') }; + save(); + } else if (op === 'update-oidc') { + if (!db.providers[id]) fail('not found'); + db.providers[id].condition = flag('attribute-condition'); save(); } else fail(`unexpected ${cmd}`); } else if (cmd.startsWith('iam workload-identity-pools')) { @@ -61,6 +67,7 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { // A deleted pool still describes, with state DELETED, for 30 days (as Google keeps it). if (!db.pools[id]) fail('not found'); if (format.includes('state')) out(db.pools[id].state ?? 'ACTIVE'); + if (format.includes('disabled')) out(db.pools[id].disabled ? 'True' : 'False'); } else if (op === 'create') { db.pools[id] = { description: flag('description') }; save(); From eba71510c7a15734244248f425e739d936ebc79e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:04:04 +0000 Subject: [PATCH 32/65] fix(selfhost): Codex review round on L22c (overlays, state dir, profiles, GCP reuse) - Upgrade: merge build sections across every compose file COMPOSE_FILE selects (tracked overlays read at both refs, untracked ones from disk), so an overlay's build change triggers the explicit rebuild. - Upgrade: when --state-dir (or a .env outside deploy/selfhost) puts state where compose would not look, pass SAM_SELFHOST_STATE_DIR (absolute) to every compose command it runs and prints. - Box env: compose control variables (COMPOSE_FILE, COMPOSE_PATH_SEPARATOR, COMPOSE_PROFILES) take the shell value first, as compose does, so the mail-collector/inbound-mail settings match the profiles compose starts. - GCP bootstrap: refuse a disabled service account; set a reused provider's audience back with its condition. Each guard was removed once and its test went red. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 6 +- deploy/selfhost/gcp-bootstrap.sh | 24 +++- scripts/selfhost/box-settings.test.ts | 26 ++++ scripts/selfhost/box-settings.ts | 26 +++- scripts/selfhost/gcp-bootstrap.test.ts | 40 +++++- scripts/selfhost/image-rebuilds.ts | 72 +++++++--- scripts/selfhost/testdata/fake-gcloud-iam.mjs | 10 +- scripts/selfhost/upgrade-lib.ts | 71 ++++++++-- scripts/selfhost/upgrade.test.ts | 129 ++++++++++++++++-- 9 files changed, 354 insertions(+), 50 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 59acbeff0c..3702144c14 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -97,7 +97,11 @@ only the images whose build inputs changed (explicitly, with `docker compose bui restarts the stack (`up -d`, never `--build`) only when compose inputs changed, deploys, checks health and prints how to roll back. For a box other than the default, pass `--box-env`, `--state-dir` and `--secrets`; every deploy and compose command it runs or prints uses that box's -`.env` and every compose file its `COMPOSE_FILE` selects. +`.env` and every compose file its `COMPOSE_FILE` selects. Docker compose reads +`SAM_SELFHOST_STATE_DIR` relative to `deploy/selfhost/`, so when `--state-dir` (or a `.env` outside +`deploy/selfhost/`) puts the state elsewhere, the upgrade passes the absolute path to every compose +command it runs or prints. Set it in the box `.env` as an absolute path to run `docker compose` +by hand. If an upgrade fails, `.state/upgrade-pending.json` records the ref it started from and the printed output gives both ways out: run the same `selfhost:upgrade --to ` again to retry (it reruns diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index 3765f225bf..584eb0f5a0 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -187,6 +187,8 @@ else --description="Dedicated to the SAM install whose token issuer is ${ISSUER}" fi +# SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). +AUDIENCE="https://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" if provider_state="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ --format='value(state)' 2>/dev/null)"; then @@ -203,15 +205,22 @@ if provider_state="$(gcloud iam workload-identity-pools providers describe "$PRO [[ "$current" = "$ISSUER" ]] \ || die "provider ${POOL_ID}/${PROVIDER_ID} already trusts ${current}, not ${ISSUER}; refusing to retarget it. Use another --pool-id." echo "provider ${PROVIDER_ID}: exists, issuer ${ISSUER}" - # A provider made by an earlier version of this script admits every token of this issuer: - # narrow it to the platform-only condition. + # A provider made by an earlier version of this script admits every token of this issuer, and + # one edited by hand may name another audience (every exchange would then fail): set both to + # what this script creates. The attribute mapping is not checked: neither the condition nor the + # pool-wide binding reads a mapped attribute. current_condition="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ --format='value(attributeCondition)')" \ || die "cannot read the attribute condition of provider ${POOL_ID}/${PROVIDER_ID}" - if [[ "$current_condition" != "$CONDITION" ]]; then + current_audiences="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(oidc.allowedAudiences)')" \ + || die "cannot read the allowed audiences of provider ${POOL_ID}/${PROVIDER_ID}" + if [[ "$current_condition" != "$CONDITION" || "$current_audiences" != "$AUDIENCE" ]]; then change iam workload-identity-pools providers update-oidc "$PROVIDER_ID" --project="$PROJECT" \ - --location=global --workload-identity-pool="$POOL_ID" --attribute-condition="$CONDITION" + --location=global --workload-identity-pool="$POOL_ID" --attribute-condition="$CONDITION" \ + --allowed-audiences="$AUDIENCE" fi else # Only this install's platform tokens are admitted (attributeCondition), and only tokens @@ -220,12 +229,17 @@ else change iam workload-identity-pools providers create-oidc "$PROVIDER_ID" --project="$PROJECT" \ --location=global --workload-identity-pool="$POOL_ID" --display-name="SAM API" \ --issuer-uri="$ISSUER" \ - --allowed-audiences="https://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" \ + --allowed-audiences="$AUDIENCE" \ --attribute-mapping="google.subject=assertion.sub,attribute.sam_user=assertion.user_id,attribute.sam_project=assertion.project_id" \ --attribute-condition="$CONDITION" fi if exists iam service-accounts describe "$SA_EMAIL" --project="$PROJECT"; then + # A disabled account can be granted roles but mints no tokens, so every node exchange would fail. + sa_disabled="$(gcloud iam service-accounts describe "$SA_EMAIL" --project="$PROJECT" \ + --format='value(disabled)')" || die "cannot read service account ${SA_EMAIL}" + [[ "${sa_disabled,,}" != "true" ]] \ + || die "service account ${SA_EMAIL} is disabled, and a disabled account mints no tokens. Either enable it: gcloud iam service-accounts enable ${SA_EMAIL} --project=${PROJECT}, then run this again; or pass --service-account ." echo "service account ${SA_EMAIL}: exists" else change iam service-accounts create "$SA_ID" --project="$PROJECT" --display-name="SAM nodes" \ diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index 50dfd601e7..3221a4713a 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -31,6 +31,7 @@ import { } from './box-settings.js'; import { composeFileVariables, composeVariableNames } from './compose-env.js'; import { SELFHOST_DIR, syncGatewayEnv } from './deploy-steps.js'; +import { mailCollectorEnabled } from './mail-settings.js'; import { parseDotenv } from './secret-files.js'; const SECRET = 'ab'.repeat(32); @@ -314,6 +315,19 @@ describe('withComposeShellOverrides (F21 L5)', () => { expect(() => resolveTunnelPortRange(box)).toThrow(/contains FRPS_BIND_PORT \(25000\)/); }); + // Compose reads COMPOSE_PROFILES from the shell first; mailCollectorEnabled must see the same. + it('applies a shell COMPOSE_PROFILES, which no compose file interpolates', () => { + const fromEnv = { COMPOSE_PROFILES: 'tunnel,local-store,mail-collector' }; + const { box, overridden } = withComposeShellOverrides( + fromEnv, + { COMPOSE_PROFILES: 'tunnel,local-store' }, + composeNames + ); + expect(overridden).toEqual(['COMPOSE_PROFILES']); + expect(mailCollectorEnabled(fromEnv)).toBe(true); + expect(mailCollectorEnabled(box)).toBe(false); + }); + it('control: without a shell override the .env value is checked and passes', () => { const { box, overridden } = withComposeShellOverrides( { CELLD_INTERNAL_PORT: '7001' }, @@ -421,6 +435,18 @@ describe('loadBoxEnv (S4: checked before anything starts)', () => { expect(reported).toEqual(['CELLD_INTERNAL_PORT']); }); + it('reads the compose files a shell COMPOSE_FILE selects, and their variables', () => { + const dir = mkdtempSync(join(tmpdir(), 'sam-box-overlay-')); + const overlay = join(dir, 'ops.yml'); + writeFileSync(overlay, 'services:\n celld:\n environment:\n X: ${OPS_ONLY_VAR}\n'); + const loaded = loadBoxEnv(box(['SAM_DOMAIN=box.example']), SELFHOST_DIR, { + COMPOSE_FILE: `docker-compose.yml:${overlay}`, + OPS_ONLY_VAR: 'from-shell', + }); + expect(loaded.OPS_ONLY_VAR).toBe('from-shell'); + expect(loaded.COMPOSE_FILE).toBe(`docker-compose.yml:${overlay}`); + }); + it('control: returns the box with shell overrides applied', () => { expect( loadBoxEnv(box(['SAM_DOMAIN=box.example', 'CELLD_PORT=8080']), SELFHOST_DIR, { diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index 4a1229861b..c0a629730c 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -66,14 +66,26 @@ const UNPRIVILEGED_LISTENERS: ReadonlySet = new Set([ 'MAIL_COLLECTOR_UI_PORT', ]); +/** + * Compose's own control variables that the box .env may set and the scripts read: which files + * (COMPOSE_FILE, COMPOSE_PATH_SEPARATOR) and which profiles (COMPOSE_PROFILES: the mail collector, + * inbound mail) the stack runs with. Compose takes them from the shell before the .env, like an + * interpolated variable, but no compose file references them, so they are named here. + */ +export const COMPOSE_CONTROL_VARIABLES: readonly string[] = [ + 'COMPOSE_FILE', + 'COMPOSE_PATH_SEPARATOR', + 'COMPOSE_PROFILES', +]; + /** * The box settings with the values docker compose will actually run with. Compose takes every * variable it interpolates from the shell before the .env file, so `CELLD_BUCKET=... docker * compose up` runs celld on that bucket and `CELLD_INTERNAL_PORT=20001 docker compose up` runs * celld's operator API on 20001, whatever the .env says. The deploy and upgrade run in the * operator's shell, so they apply the same precedence to every name in `composeVariables` (what - * the box's compose files interpolate, composeFileVariables) and to every box port, and report - * each override by name. Other shell variables (PATH, ...) are not compose's and are ignored. + * the box's compose files interpolate, composeFileVariables), to compose's control variables + * (COMPOSE_CONTROL_VARIABLES) and to every box port, and report each override by name. Other shell variables (PATH, ...) are not compose's and are ignored. * (caddy/start.sh repeats the port check inside the running stack, for a compose command run * from another shell.) */ @@ -85,7 +97,11 @@ export function withComposeShellOverrides( const effective: Record = { ...box }; const overridden: string[] = []; // Box ports stay covered even if a compose file stops referencing one. - const names = new Set([...composeVariables, ...Object.keys(BOX_RESERVED_PORTS)]); + const names = new Set([ + ...composeVariables, + ...COMPOSE_CONTROL_VARIABLES, + ...Object.keys(BOX_RESERVED_PORTS), + ]); for (const name of [...names].sort((a, b) => a.localeCompare(b))) { const value = hostEnv[name]; if (value === undefined || value === box[name]) continue; @@ -109,10 +125,12 @@ export function loadBoxEnv( onOverride: (name: string) => void = () => {} ): Record { const fromFile = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // A shell COMPOSE_FILE selects the files, so resolve the control variables before reading them. + const selecting = withComposeShellOverrides(fromFile, hostEnv, []).box; const { box, overridden } = withComposeShellOverrides( fromFile, hostEnv, - composeFileVariables(fromFile, composeDir) + composeFileVariables(selecting, composeDir) ); overridden.forEach(onOverride); resolveTunnelPortRange(box); diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index 24915a56e8..5c8ae15e62 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -58,9 +58,16 @@ interface FakeGcp { pools: Record; providers: Record< string, - { issuer: string; pool?: string; state?: string; condition?: string; disabled?: boolean } + { + issuer: string; + pool?: string; + state?: string; + condition?: string; + audience?: string; + disabled?: boolean; + } >; - accounts: Record; + accounts: Record; bindings: string[]; } @@ -172,6 +179,18 @@ describe('pnpm selfhost:gcp-bootstrap', () => { expect(result.calls.filter((c) => c.includes('providers update-oidc'))).toHaveLength(1); }); + it('a hand-edited audience is set back, with the condition', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + const audience = gcp().providers['sam-api'].audience; + setGcp((db) => { + db.providers['sam-api'].audience = 'https://example.com/other'; + }); + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + expect(gcp().providers['sam-api'].audience).toBe(audience); + expect(gcp().providers['sam-api'].condition).toBe(CONDITION); + }); + it('dry run only shows the update', () => { const result = narrow(['--dry-run']); expect(result.status, result.stderr).toBe(0); @@ -215,6 +234,23 @@ describe('pnpm selfhost:gcp-bootstrap', () => { ).toEqual([]); }); + it('a disabled service account: stops with the enable command, grants nothing', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.accounts['sam-nodes@sam-vm-test.iam.gserviceaccount.com'].disabled = true; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'service account sam-nodes@sam-vm-test.iam.gserviceaccount.com is disabled' + ); + expect(result.stderr).toContain('gcloud iam service-accounts enable'); + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services enable')) + ).toEqual([]); + }); + it('refuses to retarget a provider that already trusts another install', () => { run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-shared']); const other = 'https://api.other.example.org'; diff --git a/scripts/selfhost/image-rebuilds.ts b/scripts/selfhost/image-rebuilds.ts index 799e242b9c..aad8a0986e 100644 --- a/scripts/selfhost/image-rebuilds.ts +++ b/scripts/selfhost/image-rebuilds.ts @@ -3,26 +3,52 @@ * run `docker compose up -d --build` whenever any compose input changed; a build fetches base * images and modules from the network, so it now runs only for a service whose image would differ. */ -import { join, posix, relative } from 'node:path'; +import { isAbsolute, join, posix, relative } from 'node:path'; import { parse as parseYaml } from 'yaml'; +import { isJsonRecord } from '../../packages/shared/src/runtime-validation.js'; import { REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; /** The compose file, relative to the repository root (what `git show :` reads). */ export const COMPOSE_PATH = relative(REPO_ROOT, join(SELFHOST_DIR, 'docker-compose.yml')); +type BuildSection = { context?: string; dockerfile?: string; args?: unknown }; + interface ComposeBuildService { - build?: string | { context?: string; dockerfile?: string; args?: unknown }; + build?: string | BuildSection; +} + +/** A compose file's text at the two refs an upgrade moves between (null: absent there). */ +export interface ComposeOverlay { + from: string | null; + to: string | null; +} + +function asSection(build: string | BuildSection): BuildSection { + return typeof build === 'string' ? { context: build } : { ...build }; } -/** Each locally built service's build section, from a docker-compose.yml text (null: none). */ -function buildSections(compose: string | null): Map { - const sections = new Map(); - if (compose === null) return sections; - const parsed = parseYaml(compose) as { services?: Record } | null; - for (const [name, service] of Object.entries(parsed?.services ?? {})) { - if (service?.build !== undefined) sections.set(name, service.build); +/** + * Each locally built service's build section across the selected compose files, in order: a later + * file's `build` keys replace the earlier file's, and its build args merge into theirs, as docker + * compose merges them. A service no file builds is absent. + */ +function buildSections(composes: readonly (string | null)[]): Map { + const sections = new Map(); + for (const compose of composes) { + if (compose === null) continue; + const parsed = parseYaml(compose) as { services?: Record } | null; + for (const [name, service] of Object.entries(parsed?.services ?? {})) { + if (service?.build === undefined) continue; + const earlier = sections.get(name) ?? {}; + const later = asSection(service.build); + const args = + isJsonRecord(earlier.args) && isJsonRecord(later.args) + ? { ...earlier.args, ...later.args } + : (later.args ?? earlier.args); + sections.set(name, { ...earlier, ...later, ...(args === undefined ? {} : { args }) }); + } } return sections; } @@ -38,10 +64,13 @@ function ignoresEverything(dockerignore: string | null): boolean { /** * The locally built services whose image this upgrade must rebuild, from the files that changed - * between the two refs and docker-compose.yml at each: a service is rebuilt when its build section - * changed (context, Dockerfile, build args such as the pinned Caddy module versions) or a file in - * its build context did. A context whose .dockerignore is exactly `*` sends nothing to the build - * (caddy/), so only its Dockerfile and .dockerignore count; README files never do. + * between the two refs and the box's compose files at each: docker-compose.yml, then every other + * file its COMPOSE_FILE selects (`overlays`, in order), which may add or change a build section. + * A service is rebuilt when its merged build section changed (context, Dockerfile, build args such + * as the pinned Caddy module versions) or a file in its build context did. A context whose + * .dockerignore is exactly `*` sends nothing to the build (caddy/), so only its Dockerfile and + * .dockerignore count; README files never do. Docker compose resolves every file's relative paths + * against the first file's directory, so a context is read relative to docker-compose.yml. * * Every other upgrade leaves the images alone (F11): a build fetches base images and modules from * the network, so it runs only when the image it would produce differs. @@ -50,20 +79,21 @@ export function imageRebuilds( changed: readonly string[], composeFrom: string | null, composeTo: string, - readFileAtTo: (path: string) => string | null = () => null + readFileAtTo: (path: string) => string | null = () => null, + overlays: readonly ComposeOverlay[] = [] ): string[] { - const before = buildSections(composeFrom); + const before = buildSections([composeFrom, ...overlays.map((o) => o.from)]); const rebuilds: string[] = []; - for (const [service, build] of buildSections(composeTo)) { + for (const [service, build] of buildSections([composeTo, ...overlays.map((o) => o.to)])) { if (JSON.stringify(before.get(service)) !== JSON.stringify(build)) { rebuilds.push(service); continue; } - const contextRel = typeof build === 'string' ? build : (build?.context ?? '.'); - const context = posix.join(posix.dirname(COMPOSE_PATH), contextRel); - const dockerfileName = - (typeof build === 'object' ? build?.dockerfile : undefined) ?? 'Dockerfile'; - const dockerfile = posix.join(context, dockerfileName); + const contextRel = build.context ?? '.'; + const context = isAbsolute(contextRel) + ? relative(REPO_ROOT, contextRel).split(/[\\/]/).join('/') + : posix.join(posix.dirname(COMPOSE_PATH), contextRel); + const dockerfile = posix.join(context, build.dockerfile ?? 'Dockerfile'); const ignore = posix.join(context, '.dockerignore'); const emptyContext = ignoresEverything(readFileAtTo(ignore)); const touched = changed.some( diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index 1f1eabe386..c5f94a0bb9 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -53,12 +53,19 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { if (format.includes('state')) out(db.providers[id].state ?? 'ACTIVE'); if (format.includes('attributeCondition')) out(db.providers[id].condition ?? ''); if (format.includes('disabled')) out(db.providers[id].disabled ? 'True' : 'False'); + if (format.includes('allowedAudiences')) out(db.providers[id].audience ?? ''); } else if (op === 'create-oidc') { - db.providers[id] = { issuer: flag('issuer-uri'), pool, condition: flag('attribute-condition') }; + db.providers[id] = { + issuer: flag('issuer-uri'), + pool, + condition: flag('attribute-condition'), + audience: flag('allowed-audiences'), + }; save(); } else if (op === 'update-oidc') { if (!db.providers[id]) fail('not found'); db.providers[id].condition = flag('attribute-condition'); + db.providers[id].audience = flag('allowed-audiences'); save(); } else fail(`unexpected ${cmd}`); } else if (cmd.startsWith('iam workload-identity-pools')) { @@ -78,6 +85,7 @@ else if (cmd.startsWith('iam service-accounts')) { const email = id.includes('@') ? id : `${id}@${flag('project')}.iam.gserviceaccount.com`; if (op === 'describe') { if (!db.accounts[email]) fail('not found'); + if (format.includes('disabled')) out(db.accounts[email].disabled ? 'True' : 'False'); } else if (op === 'create') { db.accounts[email] = { description: flag('description') }; save(); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 6ab0304a9d..6bc9a487b4 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -8,7 +8,8 @@ * `--env-file` and `--state-dir` (and `--secrets` when given): without them the deploy would * read the checkout's default .env and .state, a different box. * 4. Rebuild a locally built image (caddy, sam-mx) only when its build inputs changed - * (imageRebuilds: its build section in docker-compose.yml or a file in its build context), + * (imageRebuilds: its build section, merged across every selected compose file, or a file in + * its build context), * with an explicit `docker compose build `; then restart the stack * (`docker compose up -d`, never `--build`) only when compose inputs changed: a non-README file * under deploy/selfhost/, a compose file the box's COMPOSE_FILE selects, or a generated file @@ -33,12 +34,12 @@ import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; -import { dirname, join, relative, resolve } from 'node:path'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { loadBoxEnv } from './box-settings.js'; import { composeFilesFor } from './compose-env.js'; import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; -import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; +import { COMPOSE_PATH, type ComposeOverlay, imageRebuilds } from './image-rebuilds.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; /** Suffix of the files under .state/ that docker compose services read (`env_file`). */ @@ -96,6 +97,19 @@ function runCommand(command: string, args: string[], env?: NodeJS.ProcessEnv): R return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr }; } +/** + * The state directory docker compose must read for this box, when it differs from the one compose + * would read on its own: compose resolves `${SAM_SELFHOST_STATE_DIR:-./.state}` against the + * compose file's directory, while the deploy resolves the state dir against the .env's directory + * or takes `--state-dir`. A shell variable beats the .env in compose, so every compose command + * this upgrade runs or prints sets it; otherwise Caddy and frps would read another box's (or no) + * gateway.env. Null when compose already reads `ctx.stateDir`. + */ +function composeStateDirOverride(ctx: Pick): string | null { + const composeReads = resolve(SELFHOST_DIR, ctx.box.SAM_SELFHOST_STATE_DIR || '.state'); + return resolve(ctx.stateDir) === composeReads ? null : resolve(ctx.stateDir); +} + /** `docker compose` arguments for this box: every compose file, then its .env, then `args`. */ function composeArgs(ctx: Pick, args: string[]): string[] { return [ @@ -123,7 +137,7 @@ export function loadBox( return { box, envFile, - // Same default and base directory docker compose and deploy.ts use. + // Same default and base directory deploy.ts uses; compose is pointed at it (composeStateDirOverride). stateDir: resolve(dirname(envFile), stateDirOverride ?? box.SAM_SELFHOST_STATE_DIR ?? '.state'), ...(secretsFile ? { secretsFile: resolve(secretsFile) } : {}), composeFiles: composeFilesFor(box, SELFHOST_DIR), @@ -177,15 +191,19 @@ function shellWord(value: string): string { * is rolled back, not the default stack. */ function rollbackSteps( - ctx: Pick, + ctx: Pick, from: string, migrationsChanged: boolean, composeChanged: boolean, boxArgs: readonly string[] = [], imagesRebuilt: readonly string[] = [] ): string[] { + const stateDir = composeStateDirOverride(ctx); const compose = (args: string[]) => - ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '); + [ + ...(stateDir === null ? [] : [`SAM_SELFHOST_STATE_DIR=${shellWord(stateDir)}`]), + ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '), + ].join(' '); const deploy = ['pnpm selfhost:deploy', ...boxArgs.map(shellWord)].join(' '); // The images the upgrade rebuilt are rebuilt again from the old ref, never with `up --build`. const rebuild = imagesRebuilt.length > 0 ? [compose(['build', ...imagesRebuilt])] : []; @@ -224,6 +242,31 @@ export function composeInputsChanged(changed: readonly string[], composeFiles: r ); } +/** + * Every compose file the box selects other than docker-compose.yml, at both refs, for + * imageRebuilds: a tracked file is read from git at each ref; a file git does not have (an + * operator's untracked overlay, or one outside the repository) is the same at both, so it is read + * from disk once. + */ +export function composeOverlays( + composeFiles: readonly string[], + from: string, + to: string, + fileAt: (ref: string, path: string) => string | null +): ComposeOverlay[] { + return composeFiles + .map((file) => ({ file, rel: relative(REPO_ROOT, resolve(file)).split(/[\\/]/).join('/') })) + .filter(({ rel }) => rel !== COMPOSE_PATH) + .map(({ file, rel }) => { + const inRepo = !rel.startsWith('../') && !isAbsolute(rel); + const atFrom = inRepo ? fileAt(from, rel) : null; + const atTo = inRepo ? fileAt(to, rel) : null; + if (atFrom !== null || atTo !== null) return { from: atFrom, to: atTo }; + const onDisk = existsSync(file) ? readFileSync(file, 'utf8') : null; + return { from: onDisk, to: onDisk }; + }); +} + /** The ref an unfinished upgrade started from (`UPGRADE_PENDING_FILE`), or null. */ function readPendingFrom(stateDir: string): string | null { const path = join(stateDir, UPGRADE_PENDING_FILE); @@ -289,8 +332,14 @@ async function applyUpgrade( progress: UpgradeProgress ): Promise { const pnpm = (args: string[]) => check(ctx.run('pnpm', args), `pnpm ${args.join(' ')}`); + const stateDir = composeStateDirOverride(ctx); + const composeEnv = + stateDir === null ? undefined : { ...process.env, SAM_SELFHOST_STATE_DIR: stateDir }; const docker = (args: string[]) => - check(ctx.run('docker', composeArgs(ctx, args)), `docker compose ${args.join(' ')}`); + check( + ctx.run('docker', composeArgs(ctx, args), composeEnv), + `docker compose ${args.join(' ')}` + ); git(['checkout', '--detach', plan.to]); pnpm(['install', '--frozen-lockfile']); const before = stateFingerprint(ctx.stateDir); @@ -358,7 +407,13 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise }; const composeTo = fileAt(to); if (composeTo === null) throw new Error(`${to} has no ${COMPOSE_PATH}`); - const rebuilds = imageRebuilds(changed, fileAt(from), composeTo, (path) => fileAt(to, path)); + const rebuilds = imageRebuilds( + changed, + fileAt(from), + composeTo, + (path) => fileAt(to, path), + composeOverlays(ctx.composeFiles, from, to, fileAt) + ); if (pendingFrom !== null) { ctx.log(`resuming an unfinished upgrade that started from ${pendingFrom.slice(0, 12)}`); } diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 6c1d309464..f493e94ffd 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -36,6 +36,8 @@ let initRewritesState: boolean; let head: string; /** docker-compose.yml at each ref, and the services `docker compose config --services` lists. */ let composeAt: Record; +/** Other tracked files by repository path, then ref (a selected compose overlay). */ +let trackedAt: Record>; let activeServices: string[]; const COMPOSE = (dnsModule = 'github.com/caddy-dns/googleclouddns@v1.1.0') => ` @@ -58,7 +60,11 @@ const FILES_AT_TO: Record = { 'deploy/selfhost/caddy/.dockerignore': '# empty context\n*\n', }; -function run(command: string, args: string[]): RunResult { +/** SAM_SELFHOST_STATE_DIR in each docker command's environment (undefined: not set). */ +let dockerStateEnv: (string | undefined)[]; + +function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + if (command === 'docker') dockerStateEnv.push(env?.SAM_SELFHOST_STATE_DIR); const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); const line = `${command} ${args.join(' ')}`; if (command === 'git') { @@ -72,9 +78,7 @@ function run(command: string, args: string[]): RunResult { const text = path === 'deploy/selfhost/docker-compose.yml' ? composeAt[ref] - : ref === TO - ? FILES_AT_TO[path] - : undefined; + : (trackedAt[path]?.[ref] ?? (ref === TO ? FILES_AT_TO[path] : undefined)); return text === undefined || text === null ? { status: 128, stdout: '', stderr: 'does not exist' } : ok(text); @@ -96,7 +100,12 @@ function run(command: string, args: string[]): RunResult { function ctx(): BoxContext { return { - box: { CELLD_BUCKET: 'gs://fleet/celld', SAM_DOMAIN: 'box.example' }, + // The .env names the state dir, so docker compose reads the same one the upgrade does. + box: { + CELLD_BUCKET: 'gs://fleet/celld', + SAM_DOMAIN: 'box.example', + SAM_SELFHOST_STATE_DIR: join(root, 'state'), + }, envFile: join(root, 'box.env'), stateDir: join(root, 'state'), composeFiles: ['compose.yml'], @@ -121,6 +130,8 @@ beforeEach(() => { initRewritesState = false; head = FROM; composeAt = { [FROM]: COMPOSE(), [TO]: COMPOSE() }; + trackedAt = {}; + dockerStateEnv = []; activeServices = ['celld', 'caddy']; }); @@ -166,7 +177,11 @@ describe('runUpgrade', () => { it('passes a non-default env file, state dir and secrets file to every deploy it runs', async () => { const envFile = join(root, 'custom', 'box.env'); mkdirSync(join(root, 'custom')); - writeFileSync(envFile, 'CELLD_BUCKET=gs://fleet/celld\n', { mode: 0o600 }); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, + { mode: 0o600 } + ); const secrets = join(root, 'custom', 'secrets.env'); const loaded = loadBox(envFile, join(root, 'custom-state'), secrets); diff = ['deploy/selfhost/docker-compose.yml']; @@ -317,7 +332,8 @@ describe('loadBox refuses a box port inside the lease range', () => { describe('runUpgrade with the box .env COMPOSE_FILE', () => { const boxFromEnv = (lines: string[]): BoxContext => { const envFile = join(root, 'real.env'); - writeFileSync(envFile, [`CELLD_BUCKET=gs://fleet/celld`, ...lines, ''].join('\n'), { + const stateLine = `SAM_SELFHOST_STATE_DIR=${join(root, 'state')}`; + writeFileSync(envFile, [`CELLD_BUCKET=gs://fleet/celld`, stateLine, ...lines, ''].join('\n'), { mode: 0o600, }); // The real loader reads the .env; only the commands are answered by the fake runner. @@ -361,7 +377,11 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { it('selects the same box in the restore-based rollback, quoting a path with a space', async () => { diff = ['apps/api/src/db/migrations/0300_new.sql']; const envFile = join(root, 'my box.env'); - writeFileSync(envFile, 'CELLD_BUCKET=gs://fleet/celld\n', { mode: 0o600 }); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, + { mode: 0o600 } + ); const ctx = { ...loadBox(envFile, join(root, 'state')), run, log: (m: string) => logs.push(m) }; const { rollback } = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); const file = join(SELFHOST_DIR, 'docker-compose.yml'); @@ -403,6 +423,89 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { }); }); +// docker compose reads ${SAM_SELFHOST_STATE_DIR:-./.state} against deploy/selfhost/, not the .env's +// directory, so a --state-dir the .env does not name must reach every compose command. +describe('runUpgrade with a state dir docker compose would not read on its own', () => { + const box = (stateLine: string[]): BoxContext => { + const envFile = join(root, 'real.env'); + writeFileSync(envFile, ['CELLD_BUCKET=gs://fleet/celld', ...stateLine, ''].join('\n'), { + mode: 0o600, + }); + return { ...loadBox(envFile, join(root, 'state')), run, log: (m) => logs.push(m) }; + }; + + it('sets SAM_SELFHOST_STATE_DIR on every compose command it runs and prints', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile', 'apps/api/src/db/migrations/0300_new.sql']; + const result = await runUpgrade(box([]), { to: 'v1', checkHealth: async () => true }); + const state = join(root, 'state'); + expect(dockerStateEnv.length).toBeGreaterThan(1); + expect(dockerStateEnv.every((value) => value === state)).toBe(true); + const printed = result.rollback.filter((step) => step.includes('docker compose')); + expect(printed.length).toBeGreaterThan(0); + expect(printed.every((step) => step.startsWith(`SAM_SELFHOST_STATE_DIR=${state} docker`))).toBe( + true + ); + }); + + it('control: sets nothing when the .env already names that state dir', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile', 'apps/api/src/db/migrations/0300_new.sql']; + const result = await runUpgrade(box([`SAM_SELFHOST_STATE_DIR=${join(root, 'state')}`]), { + to: 'v1', + checkHealth: async () => true, + }); + expect(dockerStateEnv.length).toBeGreaterThan(1); + expect(dockerStateEnv.every((value) => value === undefined)).toBe(true); + expect(result.rollback.some((step) => step.startsWith('docker compose'))).toBe(true); + expect(result.rollback.some((step) => step.includes('SAM_SELFHOST_STATE_DIR='))).toBe(false); + }); +}); + +// A selected overlay can add or change a build section; up -d never builds, so the plan must see it. +describe('runUpgrade with a compose overlay that builds', () => { + const OVERLAY = 'deploy/selfhost/docker-compose.override.yml'; + const overlay = (dnsModule: string) => ` +services: + caddy: + build: + args: + CADDY_DNS_MODULE: ${dnsModule} +`; + const boxWithOverlay = (file = 'docker-compose.override.yml'): BoxContext => { + const envFile = join(root, 'real.env'); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n` + + `COMPOSE_FILE=docker-compose.yml:${file}\n`, + { mode: 0o600 } + ); + return { ...loadBox(envFile, join(root, 'state')), run, log: (m) => logs.push(m) }; + }; + const built = () => steps.filter((s) => s.startsWith('docker compose') && s.includes(' build ')); + + it('rebuilds caddy when a tracked overlay changes its build args', async () => { + diff = [OVERLAY]; + trackedAt[OVERLAY] = { [FROM]: overlay('mod@v1'), [TO]: overlay('mod@v2') }; + await runUpgrade(boxWithOverlay(), { to: 'v1', checkHealth: async () => true }); + expect(built().map((s) => s.split(' ').at(-1))).toEqual(['caddy']); + }); + + it('control: an overlay change that leaves every build section alone rebuilds nothing', async () => { + diff = [OVERLAY]; + trackedAt[OVERLAY] = { [FROM]: overlay('mod@v1'), [TO]: `${overlay('mod@v1')} celld: {}\n` }; + await runUpgrade(boxWithOverlay(), { to: 'v1', checkHealth: async () => true }); + expect(built()).toEqual([]); + }); + + it('rebuilds a service an untracked overlay builds when its context changed', async () => { + const file = join(root, 'ops.yml'); + writeFileSync(file, 'services:\n celld:\n build: ./celld-local\n'); + diff = ['deploy/selfhost/celld-local/main.go']; + activeServices = ['celld', 'caddy']; + await runUpgrade(boxWithOverlay(file), { to: 'v1', checkHealth: async () => true }); + expect(built().map((s) => s.split(' ').at(-1))).toEqual(['celld']); + }); +}); + // F11: an image build fetches base images and modules from the network, so it must be explicit // and happen only when the image it produces differs. describe('runUpgrade image builds', () => { @@ -500,6 +603,16 @@ describe('imageRebuilds', () => { it('rebuilds a service that had no build section at the old ref', () => { expect(imageRebuilds([], null, COMPOSE())).toEqual(['caddy', 'sam-mx']); }); + + it('merges an overlay build section over the base one (args merge, keys replace)', () => { + const tweak = 'services:\n caddy:\n build:\n args:\n EXTRA: x\n'; + expect( + imageRebuilds([], COMPOSE(), COMPOSE(), () => null, [{ from: null, to: tweak }]) + ).toEqual(['caddy']); + expect( + imageRebuilds([], COMPOSE(), COMPOSE(), () => null, [{ from: tweak, to: tweak }]) + ).toEqual([]); + }); }); describe('composeFilesFor', () => { From 662a092f9d3cbcff4b55174f7484d8ea682d9209 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:05:22 +0000 Subject: [PATCH 33/65] fix(selfhost): refuse SAM_MX_LISTEN with an unbracketed IPv6 host Go's net.Listen refuses `::2525` ("too many colons in address"), so the inbound-mail service would restart-loop. Deploy (box-settings) and Caddy's start.sh now require a host free of ':' or a bracketed IPv6 host. Codex review. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/caddy/start.sh | 7 +++++++ scripts/selfhost/box-settings.test.ts | 17 +++++++++++++++++ scripts/selfhost/box-settings.ts | 8 ++++++++ scripts/selfhost/caddy-start.test.ts | 13 ++++++++++++- 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh index 58f0cf2ded..bb455632d0 100644 --- a/deploy/selfhost/caddy/start.sh +++ b/deploy/selfhost/caddy/start.sh @@ -76,7 +76,14 @@ done # SAM_MX_LISTEN is a listen address ([host]:port): its port is the part after the last ':'. sam-mx # hands it to Go's net.Listen, which refuses a bare port, so the inbound-mail service would # restart-loop: refuse it here. +# Go also refuses a host with an unbracketed ':' (`::2525`: "too many colons in address"): an +# IPv6 host must be bracketed. case "${SAM_MX_LISTEN:-}" in +\[*\]:*) ;; +*\[* | *\]* | *:*:*) + echo "caddy: SAM_MX_LISTEN must be a listen address [host]:port with an IPv6 host in brackets (e.g. [::]:2525), got ${SAM_MX_LISTEN}" >&2 + exit 64 + ;; *:*) ;; *) echo "caddy: SAM_MX_LISTEN must be a listen address [host]:port (e.g. :25 or 0.0.0.0:2525), not a bare port" >&2 diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index 3221a4713a..98e61deb9b 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -389,6 +389,23 @@ describe('sam-mx listen address and unprivileged listeners (S4)', () => { ); }); + // Go's net.Listen refuses an unbracketed IPv6 host ("too many colons in address"). + it.each(['::2525', 'foo::2525', '[::1:2525', '[a]b]:2525'])( + 'refuses SAM_MX_LISTEN=%s, a host with an unbracketed colon or bracket', + (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( + /IPv6 host in brackets/ + ); + } + ); + + it('control: a bracketed IPv6 host is accepted', () => { + expect(resolveTunnelPortRange({ SAM_MX_LISTEN: '[::1]:2525' })).toEqual({ + start: 20000, + end: 29999, + }); + }); + it.each(['0.0.0.0:', ':x', 'smtp'])('refuses a malformed SAM_MX_LISTEN %s', (listen) => { expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow(/SAM_MX_LISTEN/); }); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index c0a629730c..92f6f4ba9c 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -179,6 +179,14 @@ function boxPort(box: Readonly>, name: string, fallback: `${name} must be a listen address [host]:port (e.g. :${raw}), not a bare port: got ${raw}` ); } + // Go's net.Listen takes host:port with a host free of ':' or a bracketed IPv6 host, and refuses + // `::2525` ("too many colons in address"): the inbound-mail service would restart-loop. + const host = raw.slice(0, separator); + if (/^\[.*\]$/.test(host) ? /[[\]]/.test(host.slice(1, -1)) : /[:[\]]/.test(host)) { + throw new Error( + `${name} must be a listen address [host]:port, with an IPv6 host in brackets (e.g. [::]:2525): got ${raw}` + ); + } const port = raw.slice(separator + 1); if (port === '') throw new Error(`${name} must end in :, got ${raw}`); return integer(port, fallback, name, bounds); diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts index 54f04783c7..c900cee5a0 100644 --- a/scripts/selfhost/caddy-start.test.ts +++ b/scripts/selfhost/caddy-start.test.ts @@ -94,7 +94,18 @@ describe('caddy/start.sh', () => { } ); - it.each([':2525', '0.0.0.0:2525', '[::]:2525'])( + // Go's net.Listen refuses an unbracketed IPv6 host ("too many colons in address"). + it.each(['::2525', 'foo::2525', '[::]2525', '[::1]:[25]'])( + 'refuses SAM_MX_LISTEN=%s, an IPv6 host without brackets or a malformed bracket', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status).toBe(64); + expect(run.out).toMatch(/SAM_MX_LISTEN (must be a listen address|must be set to a port)/); + expect(run.out).not.toContain('caddy run'); + } + ); + + it.each([':2525', '0.0.0.0:2525', '[::]:2525', '[::1]:2525'])( 'control: accepts the listen address SAM_MX_LISTEN=%s', (listen) => { const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); From 3e3ef8d301d7d0a67ad08031e52f72648c3ee942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:15:54 +0000 Subject: [PATCH 34/65] fix(selfhost): COMPOSE_PROFILES=* enables the mail profiles Docker compose reads `*` as every profile, so the collector and sam-mx start; mailCollectorEnabled and inboundMailEnabled now agree, so the deploy configures the Worker for the services that actually run. Codex review. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/inbound-mail-settings.test.ts | 4 ++++ scripts/selfhost/inbound-mail-settings.ts | 4 ++-- scripts/selfhost/mail-settings.test.ts | 6 ++++++ scripts/selfhost/mail-settings.ts | 8 +++++++- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/scripts/selfhost/inbound-mail-settings.test.ts b/scripts/selfhost/inbound-mail-settings.test.ts index 8e2b340344..2006d8f42b 100644 --- a/scripts/selfhost/inbound-mail-settings.test.ts +++ b/scripts/selfhost/inbound-mail-settings.test.ts @@ -10,6 +10,10 @@ describe('inbound agent email settings', () => { expect(inboundMailWorkerVars(box, {})).toEqual({}); }); + it('is on for COMPOSE_PROFILES=*, which compose reads as every profile', () => { + expect(inboundMailEnabled({ COMPOSE_PROFILES: '*' })).toBe(true); + }); + it('turns agent email on with the mail collector as the reply transport', () => { const box = { COMPOSE_PROFILES: 'tunnel, mail-in ,mail-collector' }; const smtp = smtpWorkerVars(box, {}, 'box.example'); diff --git a/scripts/selfhost/inbound-mail-settings.ts b/scripts/selfhost/inbound-mail-settings.ts index 1988a16262..adf3aac008 100644 --- a/scripts/selfhost/inbound-mail-settings.ts +++ b/scripts/selfhost/inbound-mail-settings.ts @@ -6,14 +6,14 @@ * self-host-inbound.ts), and replies need an SMTP transport, so the profile without one is refused * here rather than deploying addresses whose agents cannot answer. */ -import { composeProfiles } from './mail-settings.js'; +import { composeProfileEnabled } from './mail-settings.js'; const MAIL_IN_PROFILE = 'mail-in'; type Box = Readonly>; export function inboundMailEnabled(box: Box): boolean { - return composeProfiles(box).includes(MAIL_IN_PROFILE); + return composeProfileEnabled(box, MAIL_IN_PROFILE); } /** Worker vars for inbound agent email ({} when the profile is off). */ diff --git a/scripts/selfhost/mail-settings.test.ts b/scripts/selfhost/mail-settings.test.ts index 5d7a9cd83b..7e06837964 100644 --- a/scripts/selfhost/mail-settings.test.ts +++ b/scripts/selfhost/mail-settings.test.ts @@ -74,6 +74,12 @@ describe('mail collector profile', () => { expect(mailCollectorEnabled({})).toBe(false); }); + // docker compose reads `*` as every profile, so the collector runs and the deploy must know. + it('is on for COMPOSE_PROFILES=*', () => { + expect(mailCollectorEnabled({ COMPOSE_PROFILES: '*' })).toBe(true); + expect(mailCollectorEnabled({ COMPOSE_PROFILES: 'tunnel, *' })).toBe(true); + }); + it('keeps node lease ranges off the collector ports even with the collector off', () => { expect(() => resolveTunnelPortRange({ diff --git a/scripts/selfhost/mail-settings.ts b/scripts/selfhost/mail-settings.ts index 17c85e6519..bf90d7645c 100644 --- a/scripts/selfhost/mail-settings.ts +++ b/scripts/selfhost/mail-settings.ts @@ -63,8 +63,14 @@ export function composeProfiles(box: Box): string[] { .filter(Boolean); } +/** Whether compose starts `profile`'s services: `COMPOSE_PROFILES=*` enables every profile. */ +export function composeProfileEnabled(box: Box, profile: string): boolean { + const profiles = composeProfiles(box); + return profiles.includes(profile) || profiles.includes('*'); +} + export function mailCollectorEnabled(box: Box): boolean { - return composeProfiles(box).includes(MAIL_COLLECTOR_PROFILE); + return composeProfileEnabled(box, MAIL_COLLECTOR_PROFILE); } export function mailCollectorPorts(box: Box): { smtp: number; ui: number } { From 424c7ba57b4de3f9861f0300175223f4f2224f20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:21:12 +0000 Subject: [PATCH 35/65] feat: isolate hosted git runtime and bound git resource use --- apps/api/package.json | 5 +- apps/api/src/repo-hosting-ports/artifacts.ts | 2 +- apps/api/src/routes/artifacts-config.ts | 2 +- apps/api/src/routes/projects/crud.ts | 2 +- .../api/src/routes/projects/project-create.ts | 39 +- .../routes/workspaces/runtime-git-token.ts | 8 +- apps/api/src/schemas/projects.ts | 1 + apps/api/src/selfhost/hosted-git.ts | 52 + apps/api/src/selfhost/hosted-git/env.ts | 7 + .../src/selfhost/hosted-git/hosted-git-gc.ts | 82 + .../selfhost/hosted-git/hosted-git-ls-refs.ts | 54 + .../selfhost/hosted-git/hosted-git-repo.ts | 421 +++++ apps/api/src/selfhost/hosted-git/http.ts | 196 +++ apps/api/src/selfhost/hosted-git/limits.ts | 66 + .../src/selfhost/hosted-git/local-backend.ts | 149 ++ apps/api/src/selfhost/hosted-git/policy.ts | 24 + .../src/selfhost/hosted-git/token-route.ts | 56 + apps/api/src/selfhost/hosted-git/tokens.ts | 178 +++ .../src/services/admin-setting-definitions.ts | 2 + .../src/services/admin-settings-registry.ts | 2 + .../{hosted-git => artifacts}/backend.ts | 0 apps/api/src/services/artifacts/settings.ts | 27 + apps/api/src/vendor/dgit/LICENSE | 21 + apps/api/src/vendor/dgit/UPSTREAM.md | 34 + apps/api/src/vendor/dgit/git/budget.ts | 92 ++ apps/api/src/vendor/dgit/git/multipart.ts | 108 ++ apps/api/src/vendor/dgit/git/objects.ts | 182 +++ apps/api/src/vendor/dgit/git/oidset.ts | 167 ++ apps/api/src/vendor/dgit/git/pack.ts | 127 ++ apps/api/src/vendor/dgit/git/packstore.ts | 911 +++++++++++ apps/api/src/vendor/dgit/git/pktline.ts | 69 + apps/api/src/vendor/dgit/git/protocol.ts | 1361 +++++++++++++++++ apps/api/src/vendor/dgit/git/sha1.ts | 369 +++++ apps/api/src/vendor/dgit/git/sha1dc-tables.ts | 324 ++++ apps/api/src/vendor/dgit/git/store.ts | 491 ++++++ apps/api/src/vendor/dgit/git/util.ts | 41 + apps/api/src/vendor/dgit/git/zlib.ts | 35 + .../tests/helpers/selfhost-only-modules.ts | 22 +- .../hosted-git/celld-entry-bundle.test.ts | 69 + apps/api/tests/hosted-git/celld/README.md | 25 + .../api/tests/hosted-git/celld/conformance.sh | 20 + apps/api/tests/hosted-git/celld/entry.ts | 25 + apps/api/tests/hosted-git/celld/near-cap.sh | 15 + apps/api/tests/hosted-git/celld/wrangler.json | 7 + .../hosted-git/hosted-git-conformance.test.ts | 726 +++++++++ .../hosted-git/support/hosted-git-entry.ts | 88 ++ .../hosted-git/support/hosted-git-runtime.ts | 119 ++ .../hosted-git-ls-refs.test.ts | 83 + .../unit/selfhost/hosted-git-budget.test.ts | 64 + .../selfhost/selfhost-only-modules.test.ts | 22 +- .../unit/services/hosted-git-backend.test.ts | 2 +- .../hosted-git/tokens-and-limits.test.ts | 202 +++ apps/api/vitest.hosted-git.config.ts | 14 + packages/repo-hosting/src/env.ts | 22 +- packages/repo-hosting/src/index.ts | 3 + packages/repo-hosting/src/ports.ts | 2 +- .../repo-hosting/src/repo-browse/artifacts.ts | 16 +- .../src/repo-browse/fetch-http-client.ts | 61 + pnpm-lock.yaml | 16 + scripts/selfhost/hosted-git-smoke.sh | 104 ++ scripts/selfhost/selfhost-durable-objects.ts | 74 + .../2026-11-19-bounded-selfhost-git-import.md | 8 + 62 files changed, 7489 insertions(+), 27 deletions(-) create mode 100644 apps/api/src/selfhost/hosted-git.ts create mode 100644 apps/api/src/selfhost/hosted-git/env.ts create mode 100644 apps/api/src/selfhost/hosted-git/hosted-git-gc.ts create mode 100644 apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts create mode 100644 apps/api/src/selfhost/hosted-git/hosted-git-repo.ts create mode 100644 apps/api/src/selfhost/hosted-git/http.ts create mode 100644 apps/api/src/selfhost/hosted-git/limits.ts create mode 100644 apps/api/src/selfhost/hosted-git/local-backend.ts create mode 100644 apps/api/src/selfhost/hosted-git/policy.ts create mode 100644 apps/api/src/selfhost/hosted-git/token-route.ts create mode 100644 apps/api/src/selfhost/hosted-git/tokens.ts rename apps/api/src/services/{hosted-git => artifacts}/backend.ts (100%) create mode 100644 apps/api/src/services/artifacts/settings.ts create mode 100644 apps/api/src/vendor/dgit/LICENSE create mode 100644 apps/api/src/vendor/dgit/UPSTREAM.md create mode 100644 apps/api/src/vendor/dgit/git/budget.ts create mode 100644 apps/api/src/vendor/dgit/git/multipart.ts create mode 100644 apps/api/src/vendor/dgit/git/objects.ts create mode 100644 apps/api/src/vendor/dgit/git/oidset.ts create mode 100644 apps/api/src/vendor/dgit/git/pack.ts create mode 100644 apps/api/src/vendor/dgit/git/packstore.ts create mode 100644 apps/api/src/vendor/dgit/git/pktline.ts create mode 100644 apps/api/src/vendor/dgit/git/protocol.ts create mode 100644 apps/api/src/vendor/dgit/git/sha1.ts create mode 100644 apps/api/src/vendor/dgit/git/sha1dc-tables.ts create mode 100644 apps/api/src/vendor/dgit/git/store.ts create mode 100644 apps/api/src/vendor/dgit/git/util.ts create mode 100644 apps/api/src/vendor/dgit/git/zlib.ts create mode 100644 apps/api/tests/hosted-git/celld-entry-bundle.test.ts create mode 100644 apps/api/tests/hosted-git/celld/README.md create mode 100755 apps/api/tests/hosted-git/celld/conformance.sh create mode 100644 apps/api/tests/hosted-git/celld/entry.ts create mode 100755 apps/api/tests/hosted-git/celld/near-cap.sh create mode 100644 apps/api/tests/hosted-git/celld/wrangler.json create mode 100644 apps/api/tests/hosted-git/hosted-git-conformance.test.ts create mode 100644 apps/api/tests/hosted-git/support/hosted-git-entry.ts create mode 100644 apps/api/tests/hosted-git/support/hosted-git-runtime.ts create mode 100644 apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts create mode 100644 apps/api/tests/unit/selfhost/hosted-git-budget.test.ts create mode 100644 apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts create mode 100644 apps/api/vitest.hosted-git.config.ts create mode 100644 packages/repo-hosting/src/repo-browse/fetch-http-client.ts create mode 100755 scripts/selfhost/hosted-git-smoke.sh create mode 100644 scripts/selfhost/selfhost-durable-objects.ts create mode 100644 tasks/backlog/2026-11-19-bounded-selfhost-git-import.md diff --git a/apps/api/package.json b/apps/api/package.json index 062be113ae..fabf53589d 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -18,7 +18,8 @@ "openapi:generate": "tsx scripts/generate-openapi.ts", "openapi:check": "tsx scripts/generate-openapi.ts --check", "deploy": "wrangler deploy", - "deploy:staging": "wrangler deploy --env staging" + "deploy:staging": "wrangler deploy --env staging", + "test:hosted-git": "vitest run --config vitest.hosted-git.config.ts" }, "dependencies": { "@ai-sdk/openai-compatible": "2.0.87", @@ -51,6 +52,7 @@ "drizzle-orm": "catalog:", "hono": "4.13.4", "jose": "catalog:", + "pako": "^2.1.0", "tsx": "catalog:", "valibot": "catalog:", "workers-ai-provider": "4.0.1", @@ -62,6 +64,7 @@ "@modelcontextprotocol/client": "2.4.0", "@types/better-sqlite3": "^7.6.13", "@types/diff": "^8.0.0", + "@types/pako": "^2.0.3", "@typescript-eslint/eslint-plugin": "catalog:", "@typescript-eslint/parser": "catalog:", "@vitest/coverage-v8": "catalog:", diff --git a/apps/api/src/repo-hosting-ports/artifacts.ts b/apps/api/src/repo-hosting-ports/artifacts.ts index e4a6673306..d7d068a3d1 100644 --- a/apps/api/src/repo-hosting-ports/artifacts.ts +++ b/apps/api/src/repo-hosting-ports/artifacts.ts @@ -1,7 +1,7 @@ import type { ArtifactsBackendPort } from '@simple-agent-manager/repo-hosting/ports'; import type { Env } from '../env'; -import { resolveArtifactsBackend } from '../services/hosted-git/backend'; +import { resolveArtifactsBackend } from '../services/artifacts/backend'; /** * Repo hosting resolves the SAM-native repository backend through the worker's hosted-git seam: diff --git a/apps/api/src/routes/artifacts-config.ts b/apps/api/src/routes/artifacts-config.ts index 8674a45f8b..0bbf138712 100644 --- a/apps/api/src/routes/artifacts-config.ts +++ b/apps/api/src/routes/artifacts-config.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono'; import type { Env } from '../env'; import { applyCacheHeaders } from '../lib/cache-headers'; -import { isArtifactsAvailable } from '../services/hosted-git/backend'; +import { isArtifactsAvailable } from '../services/artifacts/backend'; /** * Public config: whether this install can create SAM-native (Artifacts) repositories. True only diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index 37ab252899..711bff2e1e 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -17,7 +17,7 @@ import { deleteProjectLibraryObjects, getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; -import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend'; +import { resolveArtifactsBackendForCleanup } from '../../services/artifacts/backend'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; import { registerProjectCreateRoute } from './project-create'; diff --git a/apps/api/src/routes/projects/project-create.ts b/apps/api/src/routes/projects/project-create.ts index 663f60ad13..162c4d69f5 100644 --- a/apps/api/src/routes/projects/project-create.ts +++ b/apps/api/src/routes/projects/project-create.ts @@ -10,9 +10,10 @@ import { log } from '../../lib/logger'; import { toProjectResponse } from '../../lib/mappers'; import { ulid } from '../../lib/ulid'; import { getUserId } from '../../middleware/auth'; -import { errors } from '../../middleware/error'; +import { AppError, errors } from '../../middleware/error'; import { createOwnerProjectMembership } from '../../middleware/project-auth'; import { CreateProjectSchema, jsonValidator } from '../../schemas'; +import { resolveArtifactsBackend } from '../../services/artifacts/backend'; import { seedArtifactsReadme } from '../../services/artifacts/seed-readme'; import { getExternalInstallationId } from '../../services/github-installation-ids'; import { @@ -20,7 +21,6 @@ import { requireGitLabUserAccessToken, verifyGitLabProjectAccess, } from '../../services/gitlab'; -import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { assertRepositoryAccess, @@ -103,7 +103,17 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): throw errors.badRequest(`Maximum ${maxRepos} Artifacts-backed projects allowed`); } + const importUrl = body.importUrl?.trim() || null; + const importer = artifacts.importSource; + if (importUrl && !importer) { + throw errors.badRequest('This repository backend does not support importUrl'); + } + const importBranch = importUrl && importer ? await importer.defaultBranch(importUrl) : null; + if (importUrl && !importBranch) { + throw errors.badRequest('Could not read the default branch of the repository at importUrl'); + } const defaultBranch = + importBranch || body.defaultBranch?.trim() || c.env.ARTIFACTS_DEFAULT_BRANCH || ARTIFACTS_DEFAULTS.DEFAULT_BRANCH; @@ -133,13 +143,23 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): // also orients agents (project name, description, SAM MCP tools). If seeding // fails the repo is unusable, so we abort creation and log the orphan. try { - await seedArtifactsReadme({ - remote: created.remote, - token: created.token, - branch: defaultBranch, - projectName: name, - description, - }); + if (importUrl && importer) { + await importer.populate({ + sourceUrl: importUrl, + branch: defaultBranch, + remote: created.remote, + token: created.token, + }); + } else { + await seedArtifactsReadme({ + remote: created.remote, + token: created.token, + branch: defaultBranch, + projectName: name, + description, + fetchImpl: artifacts.remoteFetch, + }); + } } catch (seedError) { log.error('project_create.artifacts_seed_failed', { projectId, @@ -159,6 +179,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): action: 'orphaned_artifacts_repo_cleanup_failed', }); } + if (importUrl && seedError instanceof AppError) throw seedError; throw errors.internal('Failed to initialize Artifacts repository'); } diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index f8ee409d8f..fa742fcdb6 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -6,6 +6,7 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { errors } from '../../middleware/error'; +import { resolveArtifactsBackend } from '../../services/artifacts/backend'; import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; import { GitHubCliPolicyError, @@ -19,7 +20,6 @@ import { requireGitLabUserAccessTokenResultForOwner, verifyGitLabProjectAccess, } from '../../services/gitlab'; -import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { boundArtifactsRepositoryHost } from '../../services/workspace-git-source'; import { assertRepositoryAccess } from '../projects/_helpers'; import { @@ -237,7 +237,11 @@ runtimeRoutes.post('/:id/git-token', async (c) => { const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); const repo = await artifacts.get(artifactsRepoId); await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const tokenResult = await repo.createToken(requestedScope, ttl); + const tokenResult = await repo.createToken(requestedScope, ttl, { + userId: workspace.userId, + workspaceId: workspace.workspaceId, + callbackGeneration: workspace.callbackGeneration ?? null, + }); // Strip ?expires= suffix from token for git credential use const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext; diff --git a/apps/api/src/schemas/projects.ts b/apps/api/src/schemas/projects.ts index fadc782d9d..3741a0009d 100644 --- a/apps/api/src/schemas/projects.ts +++ b/apps/api/src/schemas/projects.ts @@ -16,6 +16,7 @@ const AgentDefaultEntrySchema = v.object({ const AgentDefaultsSchema = v.record(v.string(), AgentDefaultEntrySchema); export const CreateProjectSchema = v.object({ + importUrl: v.optional(v.string()), name: v.string(), description: v.optional(v.string()), installationId: v.optional(v.string()), diff --git a/apps/api/src/selfhost/hosted-git.ts b/apps/api/src/selfhost/hosted-git.ts new file mode 100644 index 0000000000..7a6e3ac825 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git.ts @@ -0,0 +1,52 @@ +/** + * SAM-hosted git for the self-host build only: the `HostedGitRepo` Durable Object class (vendored + * dgit core and pako) and the git smart-HTTP route. + * + * Only the celld entry generated by scripts/selfhost/celld-project.ts imports this module. The + * Cloudflare build's entry is `src/index.ts`, which does not, so the Cloudflare bundle carries + * neither the class nor the vendored git code (tests/unit/selfhost/selfhost-only-modules.test.ts + * fails if the shared entry reaches them again). The celld config declares the `HOSTED_GIT` + * binding and the class's migration (`SELFHOST_DURABLE_OBJECTS` in + * scripts/selfhost/selfhost-durable-objects.ts); `apps/api/wrangler.toml` does not. + * + * Loading this module also registers SAM's own git server as the Artifacts fallback in the shared + * seam (`registerArtifactsBackendFallback` in `services/artifacts/backend.ts`), so project + * creation, browsing, git tokens and deletion use it when no Cloudflare Artifacts binding exists. + * The backend (`selfhost/hosted-git/local-backend.ts`) reaches the Durable Object only through the + * `HOSTED_GIT` namespace binding, which exists only on a self-host deployment. + */ +import type { Hono } from 'hono'; + +import { registerArtifactsBackendFallback } from '../services/artifacts/backend'; +import type { HostedGitEnv as Env } from './hosted-git/env'; +import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './hosted-git/http'; +import { isLocalHostedGitActive, localHostedGitBackendFallback } from './hosted-git/local-backend'; + +export { HostedGitRepo } from './hosted-git/hosted-git-repo'; + +// Once, at module load: the celld entry imports this module before any request is served. +registerArtifactsBackendFallback(localHostedGitBackendFallback); + +/** + * Mounts git smart HTTP for SAM-hosted repositories (`/git/.git/...`). Authenticated per + * request with a repository token, not a session cookie. Inactive (falls through to the 404 + * handler) unless this install uses the local hosted git backend. + * + * Call it once, after `src/index.ts` has registered the shared routes. Hono runs every matching + * handler in registration order, and nothing `index.ts` registers after its global middleware + * matches `/git/*`, so the route runs after exactly the middleware every request gets (preview, + * pages proxy, workspace proxy, request logging, analytics, CORS), inside the request-scoped D1 + * session of the default `fetch`. tests/unit/selfhost/hosted-git-route-order.test.ts pins that. + */ +export function mountHostedGitRoute(app: Hono<{ Bindings: Env }>): void { + // An empty app means this is not the instance index.ts registered on (for example a bundle that + // loaded app.ts twice); the route would then serve nothing and every clone would 404 silently. + if (app.routes.length === 0) { + throw new Error('mountHostedGitRoute: the app has no routes; mount after src/index.ts'); + } + app.all(`${HOSTED_GIT_PATH_PREFIX}*`, async (c, next) => { + if (!isLocalHostedGitActive(c.env)) return next(); + const response = await handleHostedGitRequest(c.req.raw, c.env); + return response ?? next(); + }); +} diff --git a/apps/api/src/selfhost/hosted-git/env.ts b/apps/api/src/selfhost/hosted-git/env.ts new file mode 100644 index 0000000000..cd23a56edc --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/env.ts @@ -0,0 +1,7 @@ +import type { Env } from '../../env'; + +/** celld-only bindings; Cloudflare never configures these. */ +export interface HostedGitEnv extends Env { + HOSTED_GIT?: DurableObjectNamespace; + HOSTED_GIT_BACKEND?: string; +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts new file mode 100644 index 0000000000..47f140285f --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts @@ -0,0 +1,82 @@ +/** + * Garbage collection for a SAM-hosted repository, adapted from dgit's `RepoCell.runGc` + * (https://github.com/littledivy/durable-git, MIT, commit d5eba04; see src/vendor/dgit/UPSTREAM.md). + * + * After a force push or a branch deletion, objects no longer reachable from any ref still occupy + * storage and count toward the repository's caps. This walks the graph from every ref and HEAD, + * keeps thin-pack delta bases, moves reachable pack objects to loose storage, drops the packs, and + * deletes unreachable loose objects. Huge repositories (beyond SAM's own object cap anyway) skip. + */ +import { isGitlinkMode, parseCommit, parseTag, parseTree } from '../../vendor/dgit/git/objects'; +import { OidSet } from '../../vendor/dgit/git/oidset'; +import type { GitStore } from '../../vendor/dgit/git/store'; + +const GC_MAX_OBJECTS = 300_000; +/** The Durable Object SQLite ceiling a migration must not cross while duplicating objects. */ +const DO_STORAGE_CAP = 10 * 1024 * 1024 * 1024; + +export interface HostedGitGcResult { + removed: number; + kept: number; + skipped?: boolean; +} + +export async function runHostedGitGc(store: GitStore): Promise { + if (store.objectCount() > GC_MAX_OBJECTS) { + return { removed: 0, kept: store.objectCount(), skipped: true }; + } + const reachable = new OidSet(Math.max(store.objectCount(), 4096)); + const stack: string[] = store.refs().map((r: { target: string }) => r.target); + const head = store.resolveHead(); + if (head) stack.push(head); + for (let oid = stack.pop(); oid !== undefined; oid = stack.pop()) { + if (!reachable.addHex(oid)) continue; + const meta = store.typeAndSize(oid); + if (!meta || meta.type === 'blob') continue; + const obj = await store.get(oid); + if (!obj) continue; + if (obj.type === 'commit') { + const c = parseCommit(obj.data); + stack.push(c.tree, ...c.parents); + } else if (obj.type === 'tag') { + const t = parseTag(obj.data); + if (t.object) stack.push(t.object); + } else if (obj.type === 'tree') { + for (const e of parseTree(obj.data)) { + if (!isGitlinkMode(e.mode)) stack.push(e.oid); + } + } + } + // Thin-pack delta bases are a second reference edge, often unreachable from any ref. + for (const b of store.packs.baseOids()) reachable.addHex(b); + + const packCount = store.packs.countObjects(); + const noHeadroom = + packCount > 0 && store.dbSize() + store.packs.totalPackBytes() > DO_STORAGE_CAP; + let removed = 0; + if (packCount > 0 && !noHeadroom) { + // Migrate reachable pack objects to loose storage first, then drop the packs. + let migrated = 0; + for (let i = 0; i < reachable.size; i++) { + const oid = reachable.atHex(i); + if (store.packs.lookup(oid)) { + const obj = await store.get(oid); + if (obj) { + store.put(oid, obj.type, obj.data); + migrated++; + } + } + } + removed += packCount - migrated; + store.packs.reset(); + } + for (const oid of store.allOids()) { + if (!reachable.hasHex(oid)) { + store.deleteObject(oid); + removed++; + } + } + return noHeadroom + ? { removed, kept: reachable.size, skipped: true } + : { removed, kept: reachable.size }; +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts b/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts new file mode 100644 index 0000000000..9828e10f95 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts @@ -0,0 +1,54 @@ +/** + * `ref-prefix` for protocol v2 `ls-refs` on SAM-hosted repositories. + * + * The vendored dgit server (`vendor/dgit/git/protocol.ts`, `lsRefs`) ignores `ref-prefix` and + * always answers HEAD plus every ref. Git's protocol v2 says a server given `ref-prefix` arguments + * shows only refs that start with one of them (gitprotocol-v2, "ls-refs"). Clients that rely on it, + * such as isomorphic-git's `listServerRefs({ prefix: 'refs/heads/' })` behind the project's branch + * list, then saw "HEAD" as a branch (box round R13 D11). The vendored files stay a byte copy of + * upstream (UPSTREAM.md), so the filter lives here, applied by the Durable Object to the answer. + */ +import { FLUSH, pkt, PktParser } from '../../vendor/dgit/git/pktline'; +import { concat } from '../../vendor/dgit/git/util'; + +/** Upper bound on one ls-refs answer the filter buffers (refs only, no objects). */ +const MAX_LS_REFS_RESPONSE_BYTES = 16 * 1024 * 1024; + +/** + * The `ref-prefix` arguments of a protocol v2 `ls-refs` request, or null when the request is not + * `ls-refs` or names no prefix (then every ref is shown, as the protocol says). + */ +export function lsRefsPrefixes(body: Uint8Array): string[] | null { + const parser = new PktParser(body); + let lsRefs = false; + const prefixes: string[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind !== 'line') continue; + if (p.text === 'command=ls-refs') lsRefs = true; + else if (p.text.startsWith('ref-prefix ')) prefixes.push(p.text.slice('ref-prefix '.length)); + } + return lsRefs && prefixes.length > 0 ? prefixes : null; +} + +/** + * Keeps the lines of an `ls-refs` answer (` [ ]`) whose ref name starts + * with one of the prefixes; the flush packet that ends the answer is kept. + */ +export async function filterLsRefsResponse( + response: Response, + prefixes: readonly string[] +): Promise { + const body = new Uint8Array(await response.arrayBuffer()); + if (body.length > MAX_LS_REFS_RESPONSE_BYTES) return response; + const parser = new PktParser(body); + const kept: Uint8Array[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind !== 'line') continue; + const name = p.text.split(' ')[1] ?? ''; + if (prefixes.some((prefix) => name.startsWith(prefix))) kept.push(pkt(p.raw)); + } + return new Response(concat([...kept, FLUSH]), { + status: response.status, + headers: response.headers, + }); +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts new file mode 100644 index 0000000000..3d46ec3051 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -0,0 +1,421 @@ +/** + * One SAM-hosted git repository: a Durable Object speaking git smart HTTP. + * + * Adapted from dgit's `RepoCell` (https://github.com/littledivy/durable-git, MIT, commit + * d5eba04, see `src/vendor/dgit/UPSTREAM.md`): the git protocol paths, delete and the GC alarm. + * Dropped: the web UI, R2 pack offload and the content API. GC lives in `hosted-git-gc.ts`. Added: SAM's push and repository caps + * (`selfhost/hosted-git/limits.ts`), checked before a pack is stored. + * + * Authentication is NOT done here. The only caller is `selfhost/hosted-git/http.ts`, which checks + * SAM's repository token on every request before forwarding to this object. The object is + * addressed by `idFromName()`, so one repository is one object. + */ +import { DurableObject } from 'cloudflare:workers'; + +import { log } from '../../lib/logger'; +import { maybeJsonRecord } from '../../lib/runtime-validation'; +import { bindGitResponse, readGitChunk, withGitWorkBudget } from '../../vendor/dgit/git/budget'; +import { ObjCache } from '../../vendor/dgit/git/packstore'; +import { + advertisement, + commitPush, + parsePushCommands, + renderStatus, + type Service, + sidebandFrames, + uploadPack, + validatePush, +} from '../../vendor/dgit/git/protocol'; +import { GitStore } from '../../vendor/dgit/git/store'; +import { concat, td, te } from '../../vendor/dgit/git/util'; +import { gunzipLimited } from '../../vendor/dgit/git/zlib'; +import type { HostedGitEnv } from './env'; +import { type HostedGitGcResult, runHostedGitGc } from './hosted-git-gc'; +import { filterLsRefsResponse, lsRefsPrefixes } from './hosted-git-ls-refs'; +import { + hostedGitPushByteBudget, + hostedGitPushRefusal, + hostedGitPushTooLargeMessage, +} from './limits'; +import { resolveHostedGitLimits } from './policy'; + +/** An upload-pack request is wants/haves/caps only. */ +const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; +/** Concurrent clone/fetch walks contend on one event loop. */ +const MAX_ACTIVE_UPLOADS = 4; +/** Decompressed objects held for delta-base resolution during one push. */ +const INGEST_CACHE_BYTES = 32 * 1024 * 1024; +const GC_DELAY_MS = 5 * 60 * 1000; +const PACK_HEADER_BYTES = 12; +/** The pkt-line command section of a push (ref updates + capabilities) before the pack. */ +const MAX_COMMAND_SECTION_BYTES = 1024 * 1024; +const PKT_LENGTH = /^[0-9a-f]{4}$/i; + +class RequestTooLargeError extends Error { + constructor() { + super('request body exceeds maximum size'); + } +} + +/** + * A pkt-line length: exactly four hex digits. 0 is a flush packet; 1-3 are invalid. `parseInt` + * alone would accept "-004" and walk the parser backwards forever (security review, HIGH). + */ +function pktLength(bytes: Uint8Array): number { + const text = td.decode(bytes); + if (!PKT_LENGTH.test(text)) throw new Error('bad pkt-line in push request'); + const len = parseInt(text, 16); + if (len !== 0 && len < 4) throw new Error('bad pkt-line in push request'); + return len; +} + +/** Read a whole request body, refusing (without buffering further) past `maxBytes`. */ +async function readBodyBounded(req: Request, maxBytes: number): Promise { + if (!req.body) return new Uint8Array(0); + const reader = req.body.getReader(); + const parts: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await readGitChunk(reader); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => undefined); + throw new RequestTooLargeError(); + } + parts.push(value); + } + return concat(parts); +} + +/** Discard up to `maxBytes` of a request body, then cancel whatever is left. */ +async function drainBounded( + reader: ReadableStreamDefaultReader | null, + maxBytes: number +): Promise { + if (!reader) return; + let drained = 0; + try { + while (drained <= maxBytes) { + const { done, value } = await readGitChunk(reader); + if (done) return; + drained += value?.byteLength ?? 0; + } + await reader.cancel(); + } catch { + // The client may already be gone. + } +} + +export class HostedGitRepo extends DurableObject { + private store: GitStore; + private readonly settingsEnv: HostedGitEnv; + /** Pushes are serialized: concurrent ingests would race pack-id allocation. */ + private receiveChain: Promise = Promise.resolve(); + private activeUploads = 0; + + constructor(ctx: DurableObjectState, env: unknown) { + super(ctx, env as never); + // celld supplies the same installation bindings to this class as its Worker. + this.settingsEnv = env as HostedGitEnv; + this.store = new GitStore(ctx.storage.sql); + } + + async fetch(req: Request): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + return withGitWorkBudget(limits, async () => bindGitResponse(await this.handleFetch(req))); + } + + private async handleFetch(req: Request): Promise { + const url = new URL(req.url); + const path = url.pathname; + try { + if (path === '/info/refs' && req.method === 'GET') { + const service = url.searchParams.get('service'); + if (service !== 'git-upload-pack' && service !== 'git-receive-pack') { + return new Response('smart HTTP only\n', { status: 400 }); + } + const v2 = req.headers + .get('git-protocol') + ?.split(':') + .some((value) => value.trim() === 'version=2'); + return new Response(advertisement(this.store, service as Service, v2), { + headers: { + 'content-type': `application/x-${service}-advertisement`, + 'cache-control': 'no-cache', + }, + }); + } + if (path === '/git-upload-pack' && req.method === 'POST') { + return await this.upload(req); + } + if (path === '/git-receive-pack' && req.method === 'POST') { + return await this.receive(req); + } + if (path === '/init' && req.method === 'PUT') { + const body = maybeJsonRecord(await req.json().catch(() => null)); + const branch = typeof body?.defaultBranch === 'string' ? body.defaultBranch : 'main'; + this.store.setHead(`refs/heads/${branch}`); + this.store.setMeta('created', '1'); + return Response.json({ ok: true }); + } + if (path === '/info' && req.method === 'GET') { + return Response.json({ + exists: this.store.getMeta('created') === '1', + head: this.store.head(), + objects: this.store.objectCount(), + bytes: this.store.dbSize(), + }); + } + if (path === '/' && req.method === 'DELETE') { + await this.ctx.blockConcurrencyWhile(async () => { + // wipe() drops dgit's tables. Not storage.deleteAll(): on celld that also sweeps the + // replication control tables and breaks WAL capture for the cell (upstream note). + this.store.wipe(); + await this.ctx.storage.deleteAlarm(); + this.store = new GitStore(this.ctx.storage.sql); + }); + return new Response('deleted\n'); + } + return new Response('not found\n', { status: 404 }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log.error('hosted_git.request_failed', { path, method: req.method, error: msg }); + return new Response('error: the repository could not process this request\n', { + status: 500, + }); + } + } + + async alarm(): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + return withGitWorkBudget(limits, () => this.runAlarm()); + } + + private async runAlarm(): Promise { + if (this.store.getMeta('gc-pending') !== '1') return; + // GC drops packs: never while a clone is streaming. Leave gc-pending set and retry. + if (this.activeUploads > 0) { + await this.ctx.storage.setAlarm(Date.now() + 30_000).catch(() => undefined); + return; + } + // Clear first (at most once), so a throwing sweep cannot cause a retry storm. + this.store.setMeta('gc-pending', '0'); + try { + const result = await this.gc(); + log.info('hosted_git.gc', { ...result }); + } catch (err) { + log.error('hosted_git.gc_failed', { + error: err instanceof Error ? err.message : String(err), + }); + } + } + + /** GC serialized behind pushes and with no other request interleaving (it resets packs). */ + private gc(): Promise { + let result: HostedGitGcResult = { removed: 0, kept: 0 }; + const run = this.receiveChain.then(() => + this.ctx.blockConcurrencyWhile(async () => { + result = await runHostedGitGc(this.store); + }) + ); + this.receiveChain = run.then( + () => undefined, + () => undefined + ); + return run.then(() => result); + } + + private async upload(req: Request): Promise { + const declared = parseInt(req.headers.get('content-length') ?? '', 10); + if (Number.isFinite(declared) && declared > MAX_UPLOAD_PACK_BYTES) { + return new Response('error: fetch request too large\n', { status: 413 }); + } + if (this.activeUploads >= MAX_ACTIVE_UPLOADS) { + return new Response('busy: too many concurrent fetches, retry shortly\n', { + status: 503, + headers: { 'retry-after': '15' }, + }); + } + // The slot spans the whole response stream; release() fires once from close/cancel. + this.activeUploads++; + let released = false; + const release = () => { + if (released) return; + released = true; + this.activeUploads--; + }; + try { + let body = await readBodyBounded(req, MAX_UPLOAD_PACK_BYTES); + if (req.headers.get('content-encoding')?.includes('gzip')) { + body = gunzipLimited(body, MAX_UPLOAD_PACK_BYTES); + } + // dgit answers ls-refs with every ref whatever `ref-prefix` asks; filter the answer here. + const prefixes = lsRefsPrefixes(body); + const response = await uploadPack(this.store, body, release); + return prefixes ? await filterLsRefsResponse(response, prefixes) : response; + } catch (err) { + release(); + if ( + err instanceof RequestTooLargeError || + (err instanceof Error && err.message.includes('exceeds maximum size')) + ) { + return new Response('error: fetch request too large\n', { status: 413 }); + } + throw err; + } + } + + /** + * The response is returned only after processing completes: returning a stream early lets + * celld treat the request as finished and evict the cell mid-ingest (upstream note). + */ + private async receive(req: Request): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + const declared = parseInt(req.headers.get('content-length') ?? '', 10); + if (Number.isFinite(declared) && declared > limits.maxPushBytes) { + return new Response(`error: ${hostedGitPushTooLargeMessage(limits.maxPushBytes)}\n`, { + status: 413, + headers: { 'content-type': 'text/plain; charset=utf-8' }, + }); + } + const chunks: Uint8Array[] = []; + const run = this.receiveChain.then(() => this.processReceive(req, (c) => chunks.push(c))); + this.receiveChain = run.then( + () => undefined, + () => undefined + ); + try { + await run; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log.error('hosted_git.receive_failed', { error: msg }); + if (err instanceof RequestTooLargeError || msg.includes('exceeds maximum size')) { + return new Response(`error: ${hostedGitPushTooLargeMessage(limits.maxPushBytes)}\n`, { + status: 413, + }); + } + // Malformed requests are the client's fault; keep the detail out of the response. + const status = /pkt-line|push request|command section|git work|inflated size/.test(msg) + ? 400 + : 500; + return new Response( + status === 400 + ? 'error: malformed push request\n' + : 'error: the push could not be processed\n', + { status } + ); + } + return new Response(concat(chunks), { + headers: { + 'content-type': 'application/x-git-receive-pack-result', + 'cache-control': 'no-cache', + }, + }); + } + + private async processReceive(req: Request, emit: (chunk: Uint8Array) => void): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + const currentBytes = this.store.dbSize(); + const maxBytes = hostedGitPushByteBudget(currentBytes, limits); + let reader: ReadableStreamDefaultReader | null = null; + let buf: Uint8Array; + if (req.headers.get('content-encoding')?.includes('gzip')) { + buf = gunzipLimited(await readBodyBounded(req, limits.maxPushBytes), limits.maxPushBytes); + } else { + reader = req.body?.getReader() ?? null; + buf = new Uint8Array(0); + } + + // The pkt-line command section is small; everything after it is the pack. + let pos = 0; + const need = async (n: number): Promise => { + while (buf.length - pos < n) { + if (!reader) return false; + const { done, value } = await readGitChunk(reader); + if (done) return false; + if (value?.length) buf = concat([buf, value]); + } + return true; + }; + for (;;) { + if (!(await need(4))) break; + const len = pktLength(buf.subarray(pos, pos + 4)); + if (len === 0) { + pos += 4; + break; + } + if (pos + len > MAX_COMMAND_SECTION_BYTES) throw new Error('push command section too large'); + if (!(await need(len))) throw new Error('truncated push request'); + pos += len; + } + const { commands, caps } = parsePushCommands(buf.subarray(0, pos)); + const sideband = caps.includes('side-band-64k'); + const progress = (msg: string) => { + if (!sideband) return; + for (const f of sidebandFrames(2, te.encode(msg))) emit(f); + }; + + // Read up to the pack header so the declared object count can be checked before storing. + const packStart = pos; + const hasPack = (await need(PACK_HEADER_BYTES)) || buf.length > packStart; + let unpackError: string | null = null; + let packId: number | null = null; + if (hasPack) { + const header = buf.subarray(packStart, packStart + PACK_HEADER_BYTES); + const incomingObjects = + header.length === PACK_HEADER_BYTES + ? new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8) + : 0; + const refusal = hostedGitPushRefusal( + { objects: this.store.objectCount(), bytes: currentBytes }, + incomingObjects, + limits + ); + if (refusal) { + unpackError = refusal; + } else { + try { + const ingested = await this.store.packs.ingest(buf.subarray(packStart), reader, { + maxBytes, + sizeHint: Number.isFinite(parseInt(req.headers.get('content-length') ?? '', 10)) + ? parseInt(req.headers.get('content-length') ?? '', 10) + : undefined, + cache: new ObjCache(INGEST_CACHE_BYTES), + onProgress: progress, + flush: () => this.ctx.storage.sync(), + collisionDetect: false, + }); + packId = ingested.packId; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + unpackError = msg.includes('exceeds maximum push size') + ? hostedGitPushTooLargeMessage(maxBytes) + : msg; + } + } + if (unpackError) { + log.warn('hosted_git.push_refused', { reason: unpackError }); + progress(`${unpackError}\n`); + // Read (and discard) the rest of the upload before answering: a response sent while the + // client is still uploading resets the connection, and git then shows "remote end hung up" + // instead of the reason. Bounded, so a refused client cannot keep the cell busy forever. + await drainBounded(reader, limits.maxPushBytes * 2); + } + } + + const plan = await validatePush(this.store, commands, unpackError, packId); + const { results, changed, needsGc } = this.ctx.storage.transactionSync(() => + commitPush(this.store, plan) + ); + if (changed) { + this.store.setMeta('created', '1'); + this.store.setMeta('last-push', String(Date.now())); + } + if (needsGc) { + this.store.setMeta('gc-pending', '1'); + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS).catch(() => undefined); + } + if (caps.includes('report-status')) emit(renderStatus(results, unpackError, sideband)); + } +} diff --git a/apps/api/src/selfhost/hosted-git/http.ts b/apps/api/src/selfhost/hosted-git/http.ts new file mode 100644 index 0000000000..7d952c9df5 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/http.ts @@ -0,0 +1,196 @@ +/** + * Git smart HTTP for SAM-hosted repositories: `https://api./git/.git/...`. + * + * Every request is authenticated here before it reaches the repository's Durable Object: + * 1. HTTP Basic, password = a SAM hosted-git token (`tokens.ts`); the username is ignored. + * 2. The token names exactly this repository, and a push (receive-pack, including its + * `info/refs?service=git-receive-pack` discovery) needs the `write` scope. + * 3. D1: the repository still belongs to an `artifacts` project and the token's user is still an + * active member of it. A token minted for a workspace additionally needs that workspace to be + * active, owned by that user, in that project, on its current runtime (callback generation) + * and on a live node. + * Any failure answers 401 with a Basic challenge (git then reports "Authentication failed"), + * without saying which check failed. + */ +import { log } from '../../lib/logger'; +import { projectRoleHasCapability } from '../../middleware/project-auth'; +import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; +import { WORKSPACE_CALLBACK_ACTIVE_STATUSES } from '../../services/workspace-callback-identity'; +import type { HostedGitEnv as Env } from './env'; +import { type HostedGitTokenClaims, isHostedGitRepoName, verifyHostedGitToken } from './tokens'; + +export const HOSTED_GIT_PATH_PREFIX = '/git/'; + +/** Durable Object sub-paths a client may reach, with the scope each needs. */ +type GitOperation = { doPath: string; write: boolean }; + +function classify(subPath: string, method: string, url: URL): GitOperation | null { + if (subPath === '/info/refs' && method === 'GET') { + const service = url.searchParams.get('service'); + if (service === 'git-upload-pack') return { doPath: '/info/refs', write: false }; + if (service === 'git-receive-pack') return { doPath: '/info/refs', write: true }; + return null; + } + if (subPath === '/git-upload-pack' && method === 'POST') { + return { doPath: '/git-upload-pack', write: false }; + } + if (subPath === '/git-receive-pack' && method === 'POST') { + return { doPath: '/git-receive-pack', write: true }; + } + return null; +} + +/** Parse `/git/.git/`; the `.git` suffix is optional. */ +export function parseHostedGitPath(pathname: string): { repo: string; subPath: string } | null { + if (!pathname.startsWith(HOSTED_GIT_PATH_PREFIX)) return null; + const rest = pathname.slice(HOSTED_GIT_PATH_PREFIX.length); + const slash = rest.indexOf('/'); + if (slash <= 0) return null; + const repo = rest.slice(0, slash).replace(/\.git$/, ''); + if (!isHostedGitRepoName(repo)) return null; + return { repo, subPath: rest.slice(slash) }; +} + +function unauthorized(): Response { + return new Response('Authentication required for this SAM-hosted repository\n', { + status: 401, + headers: { 'www-authenticate': 'Basic realm="SAM"', 'content-type': 'text/plain' }, + }); +} + +function basicPassword(request: Request): string | null { + const header = request.headers.get('authorization') ?? ''; + if (!header.startsWith('Basic ')) return null; + try { + const decoded = atob(header.slice(6).trim()); + const colon = decoded.indexOf(':'); + return colon === -1 ? null : decoded.slice(colon + 1); + } catch { + return null; + } +} + +interface BindingRow { + project_id: string; + /** The token user's role when they are an active member, else null. */ + member_role: string | null; + workspace_status: string | null; + workspace_project_id: string | null; + workspace_user_id: string | null; + workspace_generation: string | null; + node_id: string | null; + node_status: string | null; +} + +/** + * One D1 round trip: the repository's project, whether the token's user is an active member of + * it, and, for a workspace-bound token, that workspace and its node. + */ +async function loadBinding( + env: Pick, + repo: string, + claims: HostedGitTokenClaims +): Promise { + return env.DATABASE.prepare( + `SELECT p.id AS project_id, + (SELECT pm.role FROM project_members pm + WHERE pm.project_id = p.id AND pm.user_id = ?3 AND pm.status = 'active' + LIMIT 1) AS member_role, + w.status AS workspace_status, w.project_id AS workspace_project_id, + w.user_id AS workspace_user_id, w.callback_generation AS workspace_generation, + w.node_id AS node_id, n.status AS node_status + FROM projects p + LEFT JOIN workspaces w ON w.id = ?2 + LEFT JOIN nodes n ON n.id = w.node_id + WHERE p.artifacts_repo_id = ?1 AND p.repo_provider = 'artifacts' + LIMIT 1` + ) + .bind(repo, claims.workspaceId ?? null, claims.userId ?? null) + .first(); +} + +/** Why a token's binding is no longer valid, or null when it is. */ +function bindingRefusal( + row: BindingRow, + claims: HostedGitTokenClaims, + write: boolean +): string | null { + if (!claims.userId) return 'no_principal'; + if (!row.member_role) return 'not_a_member'; + // Scope is fixed at mint time; the role is current, so a downgrade takes effect at once. + if (write && !projectRoleHasCapability(row.member_role, 'workspace:write')) { + return 'role_cannot_write'; + } + if (!claims.workspaceId) return null; + if (!row.workspace_status || !WORKSPACE_CALLBACK_ACTIVE_STATUSES.has(row.workspace_status)) { + return 'workspace_inactive'; + } + if (row.workspace_project_id !== row.project_id) return 'workspace_project_mismatch'; + if (row.workspace_user_id !== claims.userId) return 'workspace_user_mismatch'; + if ((row.workspace_generation ?? null) !== (claims.callbackGeneration ?? null)) { + return 'workspace_generation_retired'; + } + if (!row.node_id || !row.node_status || nodeStatusTerminatesCallbacks(row.node_status)) { + return 'workspace_node_gone'; + } + return null; +} + +export interface HostedGitHttpEnv { + DATABASE: D1Database; + ENCRYPTION_KEY: string; + HOSTED_GIT?: DurableObjectNamespace; +} + +/** Handle one git request. Returns null when the path is not a hosted git path. */ +export async function handleHostedGitRequest( + request: Request, + env: HostedGitHttpEnv, + options: { + /** + * Set only by SAM's own in-process calls (`artifactsRemoteFetch`): README seeding runs + * before the project row exists, and browsing callers have already checked project access. + * The token's signature, repository, scope and expiry are still checked. + */ + trustedInternalCaller?: boolean; + } = {} +): Promise { + const url = new URL(request.url); + const parsed = parseHostedGitPath(url.pathname); + if (!parsed) return null; + if (!env.HOSTED_GIT) return new Response('not found\n', { status: 404 }); + const operation = classify(parsed.subPath, request.method, url); + if (!operation) return new Response('not found\n', { status: 404 }); + + const password = basicPassword(request); + if (!password) return unauthorized(); + const claims = await verifyHostedGitToken(env, password); + const reject = (reason: string) => { + log.info('hosted_git.auth_rejected', { repo: parsed.repo, reason, write: operation.write }); + return unauthorized(); + }; + if (!claims) return reject('invalid_token'); + if (claims.repo !== parsed.repo) return reject('repo_mismatch'); + if (operation.write && claims.scope !== 'write') return reject('scope'); + + // External requests always need a person behind the token (a member, or a workspace owner). + // Tokens with neither are minted only for SAM's own in-process seeding and browsing. + if (!options.trustedInternalCaller || claims.userId || claims.workspaceId) { + const binding = await loadBinding(env, parsed.repo, claims); + if (!binding) return reject('repo_not_bound'); + const refusal = bindingRefusal(binding, claims, operation.write); + if (refusal) return reject(refusal); + } + + const doUrl = new URL(request.url); + doUrl.pathname = operation.doPath; + const headers = new Headers(request.headers); + headers.delete('authorization'); + const forwarded = new Request(doUrl.toString(), { + method: request.method, + headers, + body: request.method === 'GET' ? null : request.body, + }); + const stub = env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(parsed.repo)); + return stub.fetch(forwarded); +} diff --git a/apps/api/src/selfhost/hosted-git/limits.ts b/apps/api/src/selfhost/hosted-git/limits.ts new file mode 100644 index 0000000000..388e7bb9f2 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/limits.ts @@ -0,0 +1,66 @@ +/** + * Caps for SAM-hosted repositories (the self-host Durable Object git server). + * + * Why these numbers (measured on celld 0.6.3 with the self-host box's settings, idea + * 01M75V57RG8GR4NA0KC91TM1J7, "HOSTED REPOS ON DURABLE OBJECTS" part 6): every request to a + * repository runs inside celld's node-wide 300 s handler budget, and one repository is one + * single-threaded cell. A 24.8k-object repository (32 MiB pack) pushed in 29.5 s and cold-cloned + * in 67 s; a 97k-object repository (448 MiB) could not cold-clone within 300 s at all, and the + * cost grows faster than the object count. Ingest ran at about 5.5 MB/s. + * + * - Push: 64 MiB at ~5.5 MB/s is ~12 s of receive plus indexing and the connectivity check, well + * inside 300 s even for a fresh repository. + * - Objects: 30,000 keeps a cold full clone near the measured 25k-object point (~70-90 s). + * - Storage: 256 MiB of SQLite per repository (packs are stored about 1-2.5x their wire size). + * + * Administrators can lower these bounds through repositories.* settings. Maximums remain at + * the measured safe envelope; increasing that envelope requires a new measurement. + */ +import { + REPOSITORY_POLICY_DEFAULTS, + type RepositoryPolicyKey, +} from '../../services/artifacts/settings'; + +export const DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES = REPOSITORY_POLICY_DEFAULTS.maxPushBytes; +export const DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS = REPOSITORY_POLICY_DEFAULTS.maxRepoObjects; +export const DEFAULT_HOSTED_GIT_MAX_REPO_BYTES = REPOSITORY_POLICY_DEFAULTS.maxRepoBytes; +export type HostedGitLimits = { [K in RepositoryPolicyKey]: number }; +export const DEFAULT_HOSTED_GIT_LIMITS: HostedGitLimits = REPOSITORY_POLICY_DEFAULTS; + +function mib(bytes: number): string { + return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`; +} + +/** + * Decide whether a push may start, from the repository's current size and the object count the + * pushed pack declares in its header. Returns the refusal message shown to the git client, or + * null when the push may proceed. + */ +export function hostedGitPushRefusal( + current: { objects: number; bytes: number }, + incomingObjects: number, + limits: HostedGitLimits +): string | null { + if (current.bytes >= limits.maxRepoBytes) { + return ( + `SAM: push refused: this repository already uses ${mib(current.bytes)} of its ` + + `${mib(limits.maxRepoBytes)} storage limit` + ); + } + if (current.objects + incomingObjects > limits.maxRepoObjects) { + return ( + `SAM: push refused: it would bring this repository to ${current.objects + incomingObjects} ` + + `objects, over the ${limits.maxRepoObjects}-object limit for SAM-hosted repositories` + ); + } + return null; +} + +/** The most bytes this push may stream: the push cap, or less when the repository is nearly full. */ +export function hostedGitPushByteBudget(currentBytes: number, limits: HostedGitLimits): number { + return Math.max(0, Math.min(limits.maxPushBytes, limits.maxRepoBytes - currentBytes)); +} + +export function hostedGitPushTooLargeMessage(maxBytes: number): string { + return `SAM: push refused: the pack is larger than the ${mib(maxBytes)} limit for one push to a SAM-hosted repository; push in smaller pieces`; +} diff --git a/apps/api/src/selfhost/hosted-git/local-backend.ts b/apps/api/src/selfhost/hosted-git/local-backend.ts new file mode 100644 index 0000000000..d6fd41f161 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/local-backend.ts @@ -0,0 +1,149 @@ +/** + * SAM's own git server as an Artifacts backend (self-host only). + * + * `backend.ts` is the seam: it selects the Cloudflare Artifacts binding, else the fallback a + * self-host build registered. This module is that fallback: the four `Env.ARTIFACTS` methods SAM + * calls, implemented against the `HostedGitRepo` Durable Object (`selfhost/hosted-git/hosted-git-repo.ts`) + * through the `HOSTED_GIT` namespace binding only. It never imports the class. The self-host build + * registers it (`selfhost/hosted-git.ts`); only that build sets `HOSTED_GIT_BACKEND` and binds the + * class (`scripts/selfhost/celld-config.ts`, `selfhost-durable-objects.ts`), so on Cloudflare + * `isLocalHostedGitActive` is always false. + */ +import type { ArtifactsBackend } from '../../services/artifacts/backend'; +import type { HostedGitEnv as Env } from './env'; +import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './http'; +import { clampHostedGitTokenTtl, mintHostedGitToken } from './tokens'; + +type BackendEnv = Pick< + Env, + 'ARTIFACTS' | 'ARTIFACTS_ENABLED' | 'HOSTED_GIT' | 'HOSTED_GIT_BACKEND' | 'BASE_DOMAIN' +> & + Partial>; + +export function isHostedGitBackendConfigured( + env: Pick +): boolean { + return env.HOSTED_GIT_BACKEND?.trim() === 'durable-object' && !!env.HOSTED_GIT; +} + +/** Base URL of hosted repositories; a repository's remote is `.git`. */ +export function hostedGitBaseUrl(env: Pick): string { + return `https://api.${env.BASE_DOMAIN}${HOSTED_GIT_PATH_PREFIX}`; +} + +export function hostedGitRemote(env: Pick, repo: string): string { + return `${hostedGitBaseUrl(env)}${repo}.git`; +} + +/** Host git clients use for hosted repositories (`api.`). */ +export function hostedGitHost(env: Pick): string { + return `api.${env.BASE_DOMAIN}`; +} + +function repoStub(env: BackendEnv, name: string): DurableObjectStub { + if (!env.HOSTED_GIT) throw new Error('HOSTED_GIT binding is missing'); + return env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(name)); +} + +function requireEncryptionKey(env: BackendEnv): Pick { + if (!env.ENCRYPTION_KEY) + throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); + return { ENCRYPTION_KEY: env.ENCRYPTION_KEY }; +} + +/** The local implementation of the four `Env.ARTIFACTS` methods SAM calls. */ +export function createDurableObjectArtifactsBackend(env: BackendEnv): ArtifactsBackend { + const keyEnv = () => requireEncryptionKey(env); + return { + remoteFetch: artifactsRemoteFetch(env), + // Import stays unregistered until tasks/backlog/2026-11-19-bounded-selfhost-git-import.md + // bounds decompression before the importer materializes untrusted objects. + async create(name, opts) { + const defaultBranch = opts?.setDefaultBranch || 'main'; + const res = await repoStub(env, name).fetch('https://hosted-git/init', { + method: 'PUT', + body: JSON.stringify({ defaultBranch }), + }); + if (!res.ok) throw new Error(`Hosted repository init failed: HTTP ${res.status}`); + const { token } = await mintHostedGitToken(keyEnv(), { repo: name, scope: 'write' }); + return { + id: name, + name, + remote: hostedGitRemote(env, name), + token, + default_branch: defaultBranch, + }; + }, + async delete(name) { + const res = await repoStub(env, name).fetch('https://hosted-git/', { method: 'DELETE' }); + return res.ok; + }, + async get(name) { + const res = await repoStub(env, name).fetch('https://hosted-git/info'); + const info = res.ok ? ((await res.json()) as { head?: string }) : {}; + const defaultBranch = (info.head ?? 'refs/heads/main').replace(/^refs\/heads\//, ''); + return { + id: name, + name, + remote: hostedGitRemote(env, name), + defaultBranch, + async createToken(scope, ttl, context) { + const minted = await mintHostedGitToken(keyEnv(), { + repo: name, + scope: scope ?? 'read', + ...context, + ttlSeconds: clampHostedGitTokenTtl(ttl), + }); + return { + id: name, + plaintext: minted.token, + scope: scope ?? 'read', + expiresAt: minted.expiresAt, + }; + }, + }; + }, + }; +} + +/** + * The fallback the self-host build registers with `registerArtifactsBackendFallback`: SAM's own git + * server when this install configured it, else none. + */ +export function localHostedGitBackendFallback(env: Env): ArtifactsBackend | null { + return isHostedGitBackendConfigured(env) ? createDurableObjectArtifactsBackend(env) : null; +} + +/** Whether this install serves SAM-native repositories from its own Durable Object git server. */ +export function isLocalHostedGitActive(env: BackendEnv): boolean { + return env.ARTIFACTS_ENABLED === 'true' && !env.ARTIFACTS && isHostedGitBackendConfigured(env); +} + +/** Whether `remote` is a repository on this install's own git server. */ +export function isHostedGitRemote(env: Pick, remote: string): boolean { + return !!env.BASE_DOMAIN && remote.startsWith(hostedGitBaseUrl(env)); +} + +/** + * A fetch for SAM's own calls to a repository remote (README seeding, browsing). Requests to the + * hosted git server are served in-process through the same authenticated handler external git + * clients reach, instead of leaving the Worker and coming back through the ingress (no hairpin + * through Caddy, no egress-fence exception). Anything else uses the global fetch. + */ +export function artifactsRemoteFetch(env: BackendEnv): typeof fetch { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend + if (!isLocalHostedGitActive(env)) return fetch; + return async (input, init) => { + const request = new Request(input, init); + if (!isHostedGitRemote(env, request.url) || !env.DATABASE || !env.ENCRYPTION_KEY) { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend + return fetch(request); + } + const response = await handleHostedGitRequest( + request, + { DATABASE: env.DATABASE, ENCRYPTION_KEY: env.ENCRYPTION_KEY, HOSTED_GIT: env.HOSTED_GIT }, + { trustedInternalCaller: true } + ); + return response ?? new Response('not found\n', { status: 404 }); + }; +} diff --git a/apps/api/src/selfhost/hosted-git/policy.ts b/apps/api/src/selfhost/hosted-git/policy.ts new file mode 100644 index 0000000000..98cc644833 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/policy.ts @@ -0,0 +1,24 @@ +import { resolveAdminSettingDetailsMany } from '../../services/admin-settings-resolution'; +import { + REPOSITORY_POLICY_DEFAULTS, + type RepositoryPolicyKey, + type RepositorySettingName, +} from '../../services/artifacts/settings'; +import type { HostedGitEnv } from './env'; +import { DEFAULT_HOSTED_GIT_LIMITS, type HostedGitLimits } from './limits'; + +export async function resolveHostedGitLimits(env: HostedGitEnv): Promise { + const keys = Object.keys(REPOSITORY_POLICY_DEFAULTS) as RepositoryPolicyKey[]; + const settings = await resolveAdminSettingDetailsMany( + env, + keys.map((key) => `repositories.${key}` as RepositorySettingName) + ); + const result = { ...DEFAULT_HOSTED_GIT_LIMITS }; + for (const [index, key] of keys.entries()) { + const setting = settings[index]; + if (!setting || typeof setting.value !== 'number') + throw new Error('Repository policy is unavailable'); + result[key] = setting.value; + } + return result; +} diff --git a/apps/api/src/selfhost/hosted-git/token-route.ts b/apps/api/src/selfhost/hosted-git/token-route.ts new file mode 100644 index 0000000000..dc279af990 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/token-route.ts @@ -0,0 +1,56 @@ +/** + * POST /api/projects/:id/hosted-git/token — a short-lived clone/push credential for a person + * using a SAM-hosted repository from their own machine (self-host only). + * + * Session-authenticated (mounted inside projectsRoutes). Read needs `project:read`; write needs + * `workspace:write`, the capability that lets a member change the project's work. Returns 404 + * for any project that is not on this install's own git server, so Cloudflare installs and + * GitHub/GitLab projects are unaffected. + */ +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; + +import * as schema from '../../db/schema'; +import { getUserId } from '../../middleware/auth'; +import { errors } from '../../middleware/error'; +import { requireProjectCapability } from '../../middleware/project-auth'; +import type { HostedGitEnv as Env } from './env'; +import { hostedGitHost, isLocalHostedGitActive } from './local-backend'; +import { mintHostedGitToken } from './tokens'; + +const hostedGitTokenRoutes = new Hono<{ Bindings: Env }>(); + +hostedGitTokenRoutes.post('/:id/hosted-git/token', async (c) => { + const userId = getUserId(c); + const projectId = c.req.param('id'); + const scope = c.req.query('scope') === 'write' ? 'write' : 'read'; + const db = drizzle(c.env.DATABASE, { schema }); + const project = await requireProjectCapability( + db, + projectId, + userId, + scope === 'write' ? 'workspace:write' : 'project:read' + ); + if ( + !isLocalHostedGitActive(c.env) || + project.repoProvider !== 'artifacts' || + !project.artifactsRepoId + ) { + throw errors.notFound('SAM-hosted repository'); + } + const minted = await mintHostedGitToken(c.env, { + repo: project.artifactsRepoId, + scope, + userId, + }); + return c.json({ + cloneUrl: project.repository, + host: hostedGitHost(c.env), + username: 'x', + token: minted.token, + scope, + expiresAt: minted.expiresAt, + }); +}); + +export { hostedGitTokenRoutes }; diff --git a/apps/api/src/selfhost/hosted-git/tokens.ts b/apps/api/src/selfhost/hosted-git/tokens.ts new file mode 100644 index 0000000000..cfd36fae7c --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/tokens.ts @@ -0,0 +1,178 @@ +/** + * Access tokens for SAM-hosted repositories. + * + * A token is `samgit1..`: a base64url JSON payload naming one repository, + * one scope, an expiry and who it acts for (a user, and for workspaces the workspace and its + * callback generation), signed with HMAC-SHA256. git sends it as the HTTP Basic password (any + * username). The key is derived from the Worker's ENCRYPTION_KEY with HKDF under a fixed label, so + * it is separate from every other use of that secret and needs no new secret or table. + * + * Tokens cannot be revoked individually; they are short-lived (TTL clamped to 1 s..24 h) and + * the git route re-checks in D1, on every request, that the repository still belongs to a + * project, that the user is still an active member, and that a workspace-bound token's workspace + * is still active on its current runtime (callback generation). + */ +import type { HostedGitEnv as Env } from './env'; + +export type HostedGitScope = 'read' | 'write'; + +export interface HostedGitTokenClaims { + /** Repository name (projects.artifacts_repo_id). */ + repo: string; + scope: HostedGitScope; + /** Expiry, unix seconds. */ + exp: number; + /** Workspace the token was minted for, when a workspace asked for it. */ + workspaceId?: string; + /** + * The workspace's callback credential generation at mint time (`workspaces.callback_generation`, + * null when unset). A restart or wake rotates it, retiring tokens of the previous runtime. + */ + callbackGeneration?: string | null; + /** The person the token acts for: a member, or the owner of the workspace. */ + userId?: string; +} + +const TOKEN_PREFIX = 'samgit1'; +const KEY_LABEL = 'sam-hosted-git-token/v1'; +export const DEFAULT_HOSTED_GIT_TOKEN_TTL_SECONDS = 3600; +export const MAX_HOSTED_GIT_TOKEN_TTL_SECONDS = 86_400; +/** Repository names SAM generates (toArtifactsRepoName): lowercase, digits, dashes. */ +const REPO_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,127}$/; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +export function isHostedGitRepoName(name: string): boolean { + return REPO_NAME_PATTERN.test(name); +} + +function base64UrlEncode(bytes: Uint8Array): string { + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} + +function base64UrlDecode(value: string): Uint8Array | null { + if (!/^[A-Za-z0-9_-]+$/.test(value)) return null; + try { + const padded = + value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (value.length % 4)) % 4); + return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0)); + } catch { + return null; + } +} + +/** + * The derived key, cached once derived. Only a finished key is shared: a request never waits on a + * derivation another request started, which on the self-hosted celld runtime could be dropped + * with that request (lib/shared-flight.ts). Concurrent cold callers each derive once (one HKDF). + */ +let cachedKey: { secret: string; key: CryptoKey } | null = null; + +/** HKDF-SHA256 from ENCRYPTION_KEY with a purpose label; no other use shares this key. */ +async function signingKey(env: Pick): Promise { + const secret = env.ENCRYPTION_KEY; + if (!secret) throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); + if (cachedKey?.secret === secret) return cachedKey.key; + const root = await crypto.subtle.importKey('raw', encoder.encode(secret), 'HKDF', false, [ + 'deriveKey', + ]); + const key = await crypto.subtle.deriveKey( + { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: encoder.encode(KEY_LABEL) }, + root, + { name: 'HMAC', hash: 'SHA-256', length: 256 }, + false, + ['sign', 'verify'] + ); + cachedKey = { secret, key }; + return key; +} + +export function clampHostedGitTokenTtl(ttlSeconds: number | undefined): number { + if (ttlSeconds === undefined || !Number.isFinite(ttlSeconds) || ttlSeconds <= 0) { + return DEFAULT_HOSTED_GIT_TOKEN_TTL_SECONDS; + } + return Math.min(Math.floor(ttlSeconds), MAX_HOSTED_GIT_TOKEN_TTL_SECONDS) || 1; +} + +export async function mintHostedGitToken( + env: Pick, + input: { + repo: string; + scope: HostedGitScope; + ttlSeconds?: number; + workspaceId?: string; + callbackGeneration?: string | null; + userId?: string; + }, + now: number = Date.now() +): Promise<{ token: string; expiresAt: string }> { + if (!isHostedGitRepoName(input.repo)) throw new Error('Invalid hosted repository name'); + const exp = Math.floor(now / 1000) + clampHostedGitTokenTtl(input.ttlSeconds); + const claims: HostedGitTokenClaims = { repo: input.repo, scope: input.scope, exp }; + if (input.workspaceId) { + claims.workspaceId = input.workspaceId; + claims.callbackGeneration = input.callbackGeneration ?? null; + } + if (input.userId) claims.userId = input.userId; + const payload = base64UrlEncode(encoder.encode(JSON.stringify(claims))); + const unsigned = `${TOKEN_PREFIX}.${payload}`; + const signature = await crypto.subtle.sign( + 'HMAC', + await signingKey(env), + encoder.encode(unsigned) + ); + return { + token: `${unsigned}.${base64UrlEncode(new Uint8Array(signature))}`, + expiresAt: new Date(exp * 1000).toISOString(), + }; +} + +/** Verify signature, shape and expiry. Returns null for any token that is not valid now. */ +export async function verifyHostedGitToken( + env: Pick, + token: string, + now: number = Date.now() +): Promise { + if (token.length > 2048) return null; + const parts = token.split('.'); + if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null; + const [prefix, payload, signaturePart] = parts as [string, string, string]; + const signature = base64UrlDecode(signaturePart); + const payloadBytes = base64UrlDecode(payload); + if (!signature || !payloadBytes) return null; + const valid = await crypto.subtle.verify( + 'HMAC', + await signingKey(env), + signature, + encoder.encode(`${prefix}.${payload}`) + ); + if (!valid) return null; + let parsed: unknown; + try { + parsed = JSON.parse(decoder.decode(payloadBytes)); + } catch { + return null; + } + if (!parsed || typeof parsed !== 'object') return null; + const claims = parsed as Record; + if (typeof claims.repo !== 'string' || !isHostedGitRepoName(claims.repo)) return null; + if (claims.scope !== 'read' && claims.scope !== 'write') return null; + if (typeof claims.exp !== 'number' || claims.exp * 1000 <= now) return null; + if (claims.workspaceId !== undefined && typeof claims.workspaceId !== 'string') return null; + if (claims.userId !== undefined && typeof claims.userId !== 'string') return null; + const generation = claims.callbackGeneration; + if (generation !== undefined && generation !== null && typeof generation !== 'string') + return null; + return { + repo: claims.repo, + scope: claims.scope, + exp: claims.exp, + ...(typeof claims.workspaceId === 'string' + ? { workspaceId: claims.workspaceId, callbackGeneration: generation ?? null } + : {}), + ...(typeof claims.userId === 'string' ? { userId: claims.userId } : {}), + }; +} diff --git a/apps/api/src/services/admin-setting-definitions.ts b/apps/api/src/services/admin-setting-definitions.ts index 122490496f..42cdb32abf 100644 --- a/apps/api/src/services/admin-setting-definitions.ts +++ b/apps/api/src/services/admin-setting-definitions.ts @@ -19,6 +19,7 @@ import { type OutboundSettingName } from './admin-settings-outbound-definitions' import { type AgentEmailSettingName } from './agent-email/setting-definitions'; import { type AgentModelSettingKey } from './agent-models/settings-definition'; import type { AiProxySettingName } from './ai-proxy-settings'; +import type { RepositorySettingName } from './artifacts/settings'; import { type ConnectorReadSettingName } from './connector-read-settings-definition'; import { CONNECTOR_DEFAULTS, @@ -73,6 +74,7 @@ export type AdminSettingName = | InfomaniakSettingName | InstructionBudgetSettingName | OperationsTelemetrySettingName + | RepositorySettingName | OutboundSettingName | 'operations.projectDataRowUsageIntervalMs' | 'chat.profileUsageWindowDays' diff --git a/apps/api/src/services/admin-settings-registry.ts b/apps/api/src/services/admin-settings-registry.ts index 7eab89d3ce..438633da6f 100644 --- a/apps/api/src/services/admin-settings-registry.ts +++ b/apps/api/src/services/admin-settings-registry.ts @@ -18,6 +18,7 @@ import { OUTBOUND_SETTINGS } from './admin-settings-outbound-definitions'; import { OVERVIEW_BRIEF_SETTINGS } from './admin-settings-overview-brief-definitions'; import { PROJECT_EVENT_SETTINGS } from './admin-settings-project-event-definitions'; import { AI_PROXY_SETTINGS } from './ai-proxy-settings'; +import { REPOSITORY_SETTINGS } from './artifacts/settings'; import { llmEndpointSettingDefinitions } from './llm-endpoint-settings'; export { type AdminSettingDefinition, @@ -35,6 +36,7 @@ export { OPERATOR_DEFAULTS, } from './admin-setting-definitions'; const definitions = [ + ...REPOSITORY_SETTINGS, ...LIBRARY_MULTIPART_SETTINGS, ...ACCOUNT_LINKING_SETTINGS, ...llmEndpointSettingDefinitions(), diff --git a/apps/api/src/services/hosted-git/backend.ts b/apps/api/src/services/artifacts/backend.ts similarity index 100% rename from apps/api/src/services/hosted-git/backend.ts rename to apps/api/src/services/artifacts/backend.ts diff --git a/apps/api/src/services/artifacts/settings.ts b/apps/api/src/services/artifacts/settings.ts new file mode 100644 index 0000000000..a882703e89 --- /dev/null +++ b/apps/api/src/services/artifacts/settings.ts @@ -0,0 +1,27 @@ +/** Resource policy metadata for an optional repository backend; contains no git implementation. */ +import { type AdminSettingDefinition, integerDefinition } from '../admin-setting-definitions'; + +export const REPOSITORY_POLICY_DEFAULTS = { + maxPushBytes: 64 * 1024 * 1024, + maxRepoObjects: 30_000, + maxRepoBytes: 256 * 1024 * 1024, + maxObjectBytes: 16 * 1024 * 1024, + maxInflatedBytes: 128 * 1024 * 1024, + maxDeltaDepth: 100, + workTimeoutMs: 120_000, +} as const; + +export type RepositoryPolicyKey = keyof typeof REPOSITORY_POLICY_DEFAULTS; +export type RepositorySettingName = `repositories.${RepositoryPolicyKey}`; + +export const REPOSITORY_SETTINGS: readonly AdminSettingDefinition[] = ( + Object.entries(REPOSITORY_POLICY_DEFAULTS) as [RepositoryPolicyKey, number][] +).map(([key, value]) => + integerDefinition( + `repositories.${key}`, + value, + 'Operations', + `Resource bound ${key} for the installation's optional local repository backend.`, + { min: 1, max: value } + ) +); diff --git a/apps/api/src/vendor/dgit/LICENSE b/apps/api/src/vendor/dgit/LICENSE new file mode 100644 index 0000000000..57474920ff --- /dev/null +++ b/apps/api/src/vendor/dgit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Divy Srivastava + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md new file mode 100644 index 0000000000..2ec490e417 --- /dev/null +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -0,0 +1,34 @@ +# Vendored dgit git core + +- Upstream: https://github.com/littledivy/durable-git (npm `durable-git` 0.0.8) +- Commit: `d5eba04eda584b855a1bde1f86a836b751c378c0` (tag v0.0.8, 2026-08-21) +- Licence: MIT, see `LICENSE` in this directory (copyright Divy Srivastava). + +## What is here + +Local change to every vendored file: two header lines, `// @ts-nocheck` and +`/* eslint-disable */`. Upstream typechecks under `strict` but not SAM's +`noUncheckedIndexedAccess`, and follows its own lint style. `protocol.ts` and `packstore.ts` also +carry a `// FILE SIZE EXCEPTION` line. Nothing else differs from upstream. + +`git/` is upstream `src/git/` copied byte for byte, minus the three modules only the web UI +used (`blame.ts`, `diff.ts`, `snapshot.ts`). Upstream's Worker router (`mod.ts`), registry +Durable Object (`registry.ts`), cgit-style UI (`ui/`) and its `RepoCell` class are not vendored. + +Only the self-host build contains this code; the Cloudflare Worker's entry never imports it (see +`apps/api/src/selfhost/hosted-git.ts`). + +SAM's Durable Object, `apps/api/src/durable-objects/hosted-git-repo.ts`, is adapted from +upstream `src/repo.ts` (`RepoCell`): it keeps the smart-HTTP protocol paths (`info/refs`, +`git-upload-pack`, `git-receive-pack`), delete and the GC alarm, and adds SAM's push and +repository caps. Authentication is SAM's (`apps/api/src/services/hosted-git/`), not upstream's. + +## Updating + +Copy the same files from a newer upstream commit, update the commit above, and run the hosted git +conformance suite (`pnpm --filter @simple-agent-manager/api test:hosted-git`). Do not edit files +under `git/` beyond those two header lines: keep local behaviour in the Durable Object so the next update is a copy. + +## H2 resource policy + +SAM adds `git/budget.ts` around pack ingest, reads and delta application. Every request and GC invocation carries a separate cumulative decompression and deadline budget, including streamed responses. Object size is checked before allocation and while inflating, delta targets before allocation, and delta depth before traversal. Policy values come from the optional repository backend's typed admin settings. These are deliberate security changes to the vendored code; this directory is not byte-for-byte upstream. diff --git a/apps/api/src/vendor/dgit/git/budget.ts b/apps/api/src/vendor/dgit/git/budget.ts new file mode 100644 index 0000000000..93227d2718 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/budget.ts @@ -0,0 +1,92 @@ +/** SAM resource policy around the vendored git engine; never imported by Cloudflare. */ +import { AsyncLocalStorage } from 'node:async_hooks'; + +export interface GitWorkLimits { + maxObjectBytes: number; + maxInflatedBytes: number; + maxDeltaDepth: number; + workTimeoutMs: number; +} + +const budgets = new AsyncLocalStorage<{ + limits: GitWorkLimits; + remaining: number; + deadline: number; +}>(); + +export function withGitWorkBudget(limits: GitWorkLimits, action: () => T): T { + return budgets.run( + { limits, remaining: limits.maxInflatedBytes, deadline: Date.now() + limits.workTimeoutMs }, + action + ); +} + +export function gitWorkLimits(): GitWorkLimits { + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + if (Date.now() >= budget.deadline) throw new Error('git work exceeds time budget'); + return budget.limits; +} + +/** Charge output before storing/allocating it, including repeated reads and delta outputs. */ +export function chargeGitWork(bytes: number): void { + const limits = gitWorkLimits(); + if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > limits.maxObjectBytes) { + throw new Error('git object exceeds inflated size limit'); + } + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + if (bytes > budget.remaining) throw new Error('git work exceeds decompression budget'); + budget.remaining -= bytes; +} + +/** A stalled client cannot hold a repository's receive lock past its request budget. */ +export async function readGitChunk( + reader: ReadableStreamDefaultReader +): Promise> { + gitWorkLimits(); + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + const remaining = budget.deadline - Date.now(); + let timer: ReturnType | undefined; + try { + return await Promise.race([ + reader.read(), + new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error('git work exceeds time budget')); + void reader.cancel().catch(() => undefined); + }, remaining); + }), + ]); + } finally { + if (timer) clearTimeout(timer); + } +} + +/** Keep resource accounting attached when the runtime pulls a response after fetch returns. */ +export function bindGitResponse(response: Response): Response { + if (!response.body) return response; + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + const reader = response.body.getReader(); + const body = new ReadableStream({ + pull: (controller) => + budgets.run(budget, async () => { + try { + const { done, value } = await readGitChunk(reader); + if (done) controller.close(); + else controller.enqueue(value); + } catch (error) { + void reader.cancel().catch(() => undefined); + controller.error(error); + } + }), + cancel: (reason) => reader.cancel(reason), + }); + return new Response(body, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); +} diff --git a/apps/api/src/vendor/dgit/git/multipart.ts b/apps/api/src/vendor/dgit/git/multipart.ts new file mode 100644 index 0000000000..8f353d5c84 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/multipart.ts @@ -0,0 +1,108 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { concat } from "./util"; + +/** In-progress R2 multipart upload for one pack object (clone cache or raw store). */ +export interface MultipartPackUpload { + uploadPart(data: Uint8Array): Promise; + complete(): Promise; + abort(): Promise; +} + +/** Uniform multipart part size. R2 requires every part but the last to be the + * same size and >= 5 MiB; 16 MiB parts cap a pack at 16 MiB * 10,000 = 160 GiB + * while holding at most one part in isolate memory at a time. */ +export const R2_PART_SIZE = 16 * 1024 * 1024; + +/** + * Buffers a streamed pack into fixed-size R2 multipart parts. Chunks are copied + * on push (callers hand out views into buffers that later reads evict). `drain` + * uploads every whole 16 MiB part and keeps the sub-part remainder, so isolate + * memory never holds more than ~one part; `finish` flushes the final (short) + * part and completes; any failure aborts so R2 is left with no partial object. + * Uniform part size (exactly R2_PART_SIZE, last excepted) is what satisfies R2's + * equal-size-parts rule. + */ +export class MultipartCapture { + private chunks: Uint8Array[] = []; + private len = 0; + private failed = false; + private completed = false; + constructor(private mp: MultipartPackUpload) {} + + /** True once a part upload or complete/abort has failed (no R2 object exists). */ + get aborted(): boolean { + return this.failed; + } + + push(chunk: Uint8Array): void { + if (this.failed) return; + this.chunks.push(chunk.slice()); + this.len += chunk.length; + } + + async drain(): Promise { + while (!this.failed && this.len >= R2_PART_SIZE) { + const merged = concat(this.chunks); + try { + await this.mp.uploadPart(merged.subarray(0, R2_PART_SIZE)); + } catch { + await this.abort(); + return; + } + const rest = merged.slice(R2_PART_SIZE); + this.chunks = rest.length ? [rest] : []; + this.len = rest.length; + } + } + + async finish(): Promise { + if (this.failed) return; + try { + if (this.len) await this.mp.uploadPart(concat(this.chunks)); + await this.mp.complete(); + this.completed = true; + } catch { + await this.abort(); + } + this.chunks = []; + this.len = 0; + } + + async abort(): Promise { + if (this.failed || this.completed) return; + this.failed = true; + this.chunks = []; + this.len = 0; + try { + await this.mp.abort(); + } catch { + // best effort: an un-aborted multipart auto-expires + } + } +} + +/** Begin a raw R2 multipart upload under `key`. Returns null (caller falls back) + * if R2 refuses — celld deliberately makes createMultipartUpload throw. */ +export async function beginRawMultipart( + bucket: R2Bucket, + key: string +): Promise { + try { + const mp = await bucket.createMultipartUpload(key); + const parts: R2UploadedPart[] = []; + return { + uploadPart: async (data) => { + parts.push(await mp.uploadPart(parts.length + 1, data)); + }, + complete: async () => { + await mp.complete(parts); + }, + abort: async () => { + await mp.abort(); + }, + }; + } catch { + return null; + } +} diff --git a/apps/api/src/vendor/dgit/git/objects.ts b/apps/api/src/vendor/dgit/git/objects.ts new file mode 100644 index 0000000000..33ad8dc955 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/objects.ts @@ -0,0 +1,182 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { te, td, toHex, concat, sha1hex, isOid } from "./util"; + +export type ObjType = "commit" | "tree" | "blob" | "tag"; + +/** Thrown for any malformed/attacker-crafted object body. */ +export class GitParseError extends Error { + constructor(msg: string) { + super(msg); + this.name = "GitParseError"; + } +} + +export const TYPE_NUM: Record = { commit: 1, tree: 2, blob: 3, tag: 4 }; +export const NUM_TYPE: Record = { 1: "commit", 2: "tree", 3: "blob", 4: "tag" }; + +export function objectHeader(type: ObjType, size: number): Uint8Array { + return te.encode(`${type} ${size}\0`); +} + +export function hashObject(type: ObjType, data: Uint8Array): string { + return sha1hex(concat([objectHeader(type, data.length), data])); +} + +export interface Person { + name: string; + email: string; + /** unix seconds */ + time: number; + tz: string; +} + +export interface Commit { + tree: string; + parents: string[]; + author: Person; + committer: Person; + message: string; + /** first line of the message */ + subject: string; +} + +export interface Tag { + object: string; + type: string; + tag: string; + tagger: Person | null; + message: string; +} + +export interface TreeEntry { + mode: string; // e.g. "100644", "40000", "120000", "160000" + name: string; + oid: string; +} + +function parsePerson(line: string): Person { + // "Name 1234567890 +0100". Parsed with linear scans, not a + // backtracking regex: an attacker controls this line and can make it + // megabytes long, so `/(.*?) <(.*?)>/` would be a quadratic-scan DoS. + const lt = line.indexOf(" <"); + const gt = lt < 0 ? -1 : line.indexOf(">", lt + 2); + if (lt < 0 || gt < 0) return { name: line, email: "", time: 0, tz: "+0000" }; + const name = line.slice(0, lt); + const email = line.slice(lt + 2, gt); + const rest = line.slice(gt + 1).trim().split(" "); + const time = rest.length ? parseInt(rest[0], 10) : 0; + const tz = rest.length > 1 && /^[+-]\d{4}$/.test(rest[1]) ? rest[1] : "+0000"; + return { name, email, time: Number.isFinite(time) ? time : 0, tz }; +} + +function splitHeaders(text: string): { headers: [string, string][]; message: string } { + const nn = text.indexOf("\n\n"); + const head = nn === -1 ? text : text.slice(0, nn); + const message = nn === -1 ? "" : text.slice(nn + 2); + const headers: [string, string][] = []; + // continuation pieces are collected per-header and joined once at the end: + // appending with `+=` in the loop is O(n^2) on a crafted object with a huge + // multi-line header value (e.g. a giant gpgsig). + const cont: string[][] = []; + for (const line of head.split("\n")) { + // continuation lines (gpgsig etc.) start with a space; append to previous + if (line.startsWith(" ") && headers.length) { + cont[cont.length - 1].push(line.slice(1)); + continue; + } + const sp = line.indexOf(" "); + if (sp > 0) { + headers.push([line.slice(0, sp), line.slice(sp + 1)]); + cont.push([]); + } + } + for (let i = 0; i < headers.length; i++) { + if (cont[i].length) headers[i][1] += "\n" + cont[i].join("\n"); + } + return { headers, message }; +} + +export function parseCommit(data: Uint8Array): Commit { + const { headers, message } = splitHeaders(td.decode(data)); + const c: Commit = { + tree: "", + parents: [], + author: { name: "", email: "", time: 0, tz: "+0000" }, + committer: { name: "", email: "", time: 0, tz: "+0000" }, + message, + subject: message.split("\n", 1)[0] ?? "", + }; + let sawTree = false; + for (const [k, v] of headers) { + if (k === "tree") { + // tree/parent oids feed the connectivity walk verbatim: reject anything + // not a real oid so a crafted value can never be treated as an object id. + if (sawTree) throw new GitParseError("commit has duplicate tree header"); + if (!isOid(v)) throw new GitParseError("commit has malformed tree oid"); + c.tree = v; + sawTree = true; + } else if (k === "parent") { + if (!isOid(v)) throw new GitParseError("commit has malformed parent oid"); + c.parents.push(v); + } else if (k === "author") c.author = parsePerson(v); + else if (k === "committer") c.committer = parsePerson(v); + } + if (!sawTree) throw new GitParseError("commit missing tree header"); + return c; +} + +export function parseTag(data: Uint8Array): Tag { + const { headers, message } = splitHeaders(td.decode(data)); + const t: Tag = { object: "", type: "", tag: "", tagger: null, message }; + let sawObject = false; + for (const [k, v] of headers) { + if (k === "object") { + if (sawObject) throw new GitParseError("tag has duplicate object header"); + if (!isOid(v)) throw new GitParseError("tag has malformed object oid"); + t.object = v; + sawObject = true; + } else if (k === "type") t.type = v; + else if (k === "tag") t.tag = v; + else if (k === "tagger") t.tagger = parsePerson(v); + } + if (!sawObject) throw new GitParseError("tag missing object header"); + return t; +} + +export function parseTree(data: Uint8Array): TreeEntry[] { + const entries: TreeEntry[] = []; + let pos = 0; + while (pos < data.length) { + let sp = pos; + while (sp < data.length && data[sp] !== 0x20) sp++; + if (sp >= data.length) throw new GitParseError("malformed tree"); + const mode = td.decode(data.subarray(pos, sp)); + let nul = sp + 1; + while (nul < data.length && data[nul] !== 0) nul++; + if (nul >= data.length || nul + 21 > data.length) throw new GitParseError("malformed tree"); + const name = td.decode(data.subarray(sp + 1, nul)); + const oid = toHex(data.subarray(nul + 1, nul + 21)); + entries.push({ mode, name, oid }); + pos = nul + 21; + } + return entries; +} + +export function isTreeMode(mode: string): boolean { + return mode === "40000" || mode === "040000"; +} + +export function isGitlinkMode(mode: string): boolean { + return mode === "160000"; +} + +/** Render a tree-entry mode the way cgit/ls-tree does: d rwx r-x r-x etc. */ +export function modeString(mode: string): string { + const m = parseInt(mode, 8); + if (isTreeMode(mode)) return "d---------"; + if (isGitlinkMode(mode)) return "m---------"; + if ((m & 0o170000) === 0o120000) return "lrwxrwxrwx"; + const bits = (n: number) => `${n & 4 ? "r" : "-"}${n & 2 ? "w" : "-"}${n & 1 ? "x" : "-"}`; + return `-${bits((m >> 6) & 7)}${bits((m >> 3) & 7)}${bits(m & 7)}`; +} diff --git a/apps/api/src/vendor/dgit/git/oidset.ts b/apps/api/src/vendor/dgit/git/oidset.ts new file mode 100644 index 0000000000..22e84d8fe4 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/oidset.ts @@ -0,0 +1,167 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { fromHex, toHex } from "./util"; + +/** + * Memory-compact set + insertion-ordered list of object ids. A JS + * Set of 40-char hex strings costs ~100 bytes per entry — at + * Linux scale (10M objects) that is gigabytes. This stores raw 20-byte + * digests in typed arrays: ~20B per entry plus a u32 open-addressing table. + * + * A set can also carry a *tagged sub-set* (mark/isMarked/markedAt): one bit + * per entry plus a u32 index list. Two nested roles — e.g. the object walk's + * "visited" and its strict subset "send" — then cost ~28B/object in one set + * instead of ~56B in two. + */ +export class OidSet { + private table: Uint32Array; // 1-based indices into the entry list; 0 = empty + private mask: number; + private data: Uint8Array; // 20 bytes per entry, insertion order + private count = 0; + // tagged sub-set, allocated lazily on first mark() + private marks: Uint8Array | null = null; // one bit per entry index + private markedIdx: Uint32Array | null = null; // tagged entry indices, insertion order + private markedCount = 0; + + constructor(expected = 1024) { + let cap = 2048; + while (cap < expected * 2) cap *= 2; + this.table = new Uint32Array(cap); + this.mask = cap - 1; + this.data = new Uint8Array(Math.max(expected, 1024) * 20); + } + + get size(): number { + return this.count; + } + + /** Number of entries in the tagged sub-set. */ + get markedSize(): number { + return this.markedCount; + } + + private hashAt(bytes: Uint8Array, off: number): number { + // oids are uniformly random; the first 4 bytes are a fine hash + return ((bytes[off] << 24) | (bytes[off + 1] << 16) | (bytes[off + 2] << 8) | bytes[off + 3]) >>> 0; + } + + private equalsEntry(idx: number, bytes: Uint8Array, off: number): boolean { + const base = idx * 20; + for (let i = 0; i < 20; i++) { + if (this.data[base + i] !== bytes[off + i]) return false; + } + return true; + } + + private grow(): void { + const newTable = new Uint32Array(this.table.length * 2); + const newMask = newTable.length - 1; + for (let i = 0; i < this.count; i++) { + let slot = this.hashAt(this.data, i * 20) & newMask; + while (newTable[slot] !== 0) slot = (slot + 1) & newMask; + newTable[slot] = i + 1; + } + this.table = newTable; + this.mask = newMask; + } + + /** Make room for the entry about to be written at index `this.count`. */ + private growData(): void { + if ((this.count + 1) * 20 > this.data.length) { + const bigger = new Uint8Array(this.data.length * 2); + bigger.set(this.data); + this.data = bigger; + } + if (this.marks && (this.count >> 3) >= this.marks.length) { + const bigger = new Uint8Array(this.marks.length * 2); + bigger.set(this.marks); + this.marks = bigger; + } + } + + /** Entry index of `bytes`, inserting it when absent. */ + private indexOrInsert(bytes: Uint8Array, off: number): number { + if ((this.count + 1) * 2 > this.table.length) this.grow(); + let slot = this.hashAt(bytes, off) & this.mask; + while (this.table[slot] !== 0) { + if (this.equalsEntry(this.table[slot] - 1, bytes, off)) return this.table[slot] - 1; + slot = (slot + 1) & this.mask; + } + this.growData(); + this.data.set(bytes.subarray(off, off + 20), this.count * 20); + this.table[slot] = ++this.count; + return this.count - 1; + } + + /** Adds a hex oid; returns false if it was already present. */ + addHex(hex: string): boolean { + return this.addBytes(fromHex(hex), 0); + } + + addBytes(bytes: Uint8Array, off: number): boolean { + const before = this.count; + // a freshly inserted entry always lands at index `before` + return this.indexOrInsert(bytes, off) === before; + } + + hasHex(hex: string): boolean { + return this.hasBytes(fromHex(hex), 0); + } + + /** Insertion-order entry index of `hex`, or -1 if absent. */ + indexOfHex(hex: string): number { + return this.indexOf(fromHex(hex), 0); + } + + hasBytes(bytes: Uint8Array, off: number): boolean { + return this.indexOf(bytes, off) >= 0; + } + + /** Entry index of `bytes`, or -1. */ + private indexOf(bytes: Uint8Array, off: number): number { + let slot = this.hashAt(bytes, off) & this.mask; + while (this.table[slot] !== 0) { + if (this.equalsEntry(this.table[slot] - 1, bytes, off)) return this.table[slot] - 1; + slot = (slot + 1) & this.mask; + } + return -1; + } + + /** Hex oid of the i-th inserted entry. */ + atHex(i: number): string { + return toHex(this.data.subarray(i * 20, i * 20 + 20)); + } + + /** + * Adds `hex` if needed and puts it in the tagged sub-set. + * Returns false if it was already tagged. + */ + markHex(hex: string): boolean { + const idx = this.indexOrInsert(fromHex(hex), 0); + if (!this.marks) this.marks = new Uint8Array(((this.data.length / 20) >> 3) + 1); + const byte = idx >> 3; + const bit = 1 << (idx & 7); + if (this.marks[byte] & bit) return false; + this.marks[byte] |= bit; + if (!this.markedIdx) this.markedIdx = new Uint32Array(1024); + if (this.markedCount === this.markedIdx.length) { + const bigger = new Uint32Array(this.markedIdx.length * 2); + bigger.set(this.markedIdx); + this.markedIdx = bigger; + } + this.markedIdx[this.markedCount++] = idx; + return true; + } + + isMarkedHex(hex: string): boolean { + if (!this.marks) return false; + const idx = this.indexOf(fromHex(hex), 0); + return idx >= 0 && (this.marks[idx >> 3] & (1 << (idx & 7))) !== 0; + } + + /** Hex oid of the i-th entry of the tagged sub-set. */ + markedAtHex(i: number): string { + const idx = this.markedIdx![i]; + return toHex(this.data.subarray(idx * 20, idx * 20 + 20)); + } +} diff --git a/apps/api/src/vendor/dgit/git/pack.ts b/apps/api/src/vendor/dgit/git/pack.ts new file mode 100644 index 0000000000..ad55b59d81 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/pack.ts @@ -0,0 +1,127 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { chargeGitWork } from "./budget"; +import { te, fromHex, Sha1 } from "./util"; +import { deflate } from "./zlib"; +import { ObjType, TYPE_NUM } from "./objects"; + +export function applyDelta(base: Uint8Array, delta: Uint8Array): Uint8Array { + let pos = 0; + // bounded read: a truncated/crafted delta must throw, never read past the end + // (which would fold `undefined` into offsets/sizes and corrupt the result). + const next = (): number => { + if (pos >= delta.length) throw new Error("delta truncated"); + return delta[pos++]; + }; + const varint = () => { + let r = 0, shift = 0, b: number; + do { + b = next(); + r += (b & 0x7f) * 2 ** shift; + shift += 7; + } while (b & 0x80); + return r; + }; + const srcSize = varint(); + const tgtSize = varint(); + if (srcSize !== base.length) throw new Error("delta base size mismatch"); + chargeGitWork(tgtSize); + const out = new Uint8Array(tgtSize); + let op = 0; + while (pos < delta.length) { + const cmd = next(); + if (cmd & 0x80) { + // copy from base + let off = 0, size = 0; + if (cmd & 0x01) off = next(); + if (cmd & 0x02) off |= next() << 8; + if (cmd & 0x04) off |= next() << 16; + if (cmd & 0x08) off += next() * 0x1000000; + if (cmd & 0x10) size = next(); + if (cmd & 0x20) size |= next() << 8; + if (cmd & 0x40) size |= next() << 16; + if (size === 0) size = 0x10000; + if (off + size > base.length) throw new Error("delta copy out of range"); + if (op + size > tgtSize) throw new Error("delta copy overflows target"); + out.set(base.subarray(off, off + size), op); + op += size; + } else if (cmd) { + // insert literal + if (pos + cmd > delta.length) throw new Error("delta literal truncated"); + if (op + cmd > tgtSize) throw new Error("delta literal overflows target"); + out.set(delta.subarray(pos, pos + cmd), op); + op += cmd; + pos += cmd; + } else { + throw new Error("invalid delta opcode 0"); + } + } + if (op !== tgtSize) throw new Error("delta target size mismatch"); + return out; +} + +const REF_DELTA_NUM = 7; + +function encodeTypeSizeNum(typeNum: number, size: number): Uint8Array { + const bytes: number[] = []; + let first = (typeNum << 4) | (size & 0x0f); + size = Math.floor(size / 16); + while (size > 0) { + bytes.push(first | 0x80); + first = size & 0x7f; + size = Math.floor(size / 128); + } + bytes.push(first); + return new Uint8Array(bytes); +} + +function encodeTypeSize(type: ObjType, size: number): Uint8Array { + return encodeTypeSizeNum(TYPE_NUM[type], size); +} + +/** + * Incremental packfile writer: emits raw pack bytes through `emit` while + * keeping the running SHA-1 for the trailer, so packs can be streamed + * without ever materializing the whole file. + */ +export class PackWriter { + private sha = new Sha1(); + + constructor(private emit: (chunk: Uint8Array) => void) {} + + private out(chunk: Uint8Array): void { + this.sha.update(chunk); + this.emit(chunk); + } + + header(count: number): void { + const h = new Uint8Array(12); + h.set(te.encode("PACK"), 0); + const dv = new DataView(h.buffer); + dv.setUint32(4, 2); + dv.setUint32(8, count); + this.out(h); + } + + object(type: ObjType, data: Uint8Array): void { + this.out(encodeTypeSize(type, data.length)); + this.out(deflate(data)); + } + + /** Copy a stored full entry verbatim (already zlib-compressed). */ + rawFull(type: ObjType, entrySize: number, compressed: Uint8Array): void { + this.out(encodeTypeSize(type, entrySize)); + this.out(compressed); + } + + /** Copy a stored delta entry verbatim, addressed as a ref-delta. */ + rawDelta(entrySize: number, baseOid: string, compressed: Uint8Array): void { + this.out(encodeTypeSizeNum(REF_DELTA_NUM, entrySize)); + this.out(fromHex(baseOid)); + this.out(compressed); + } + + finish(): void { + this.emit(this.sha.digest()); // trailer is not part of the hashed content + } +} diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts new file mode 100644 index 0000000000..cca78d63cd --- /dev/null +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -0,0 +1,911 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +// FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) +import pako from "pako"; +import { chargeGitWork, gitWorkLimits, readGitChunk } from "./budget"; +import { td, concat, toHex, Sha1 } from "./util"; +import { Sha1Dc, Sha1CollisionError } from "./sha1"; +import { ObjType, NUM_TYPE, objectHeader } from "./objects"; +import { applyDelta } from "./pack"; +import { MultipartCapture, beginRawMultipart } from "./multipart"; + +export const PACK_CHUNK = 1024 * 1024; +/** a pushed pack goes to R2 only when the binding is present AND the pack is at + * least this large; smaller packs stay in SQLite (local ~ms writes/reads). R2's + * purpose is escaping the 10 GB per-DO SQLite cap, which only large repos hit. */ +export const R2_PACK_MIN_BYTES = 16 * 1024 * 1024; +/** real Workers isolates have a hard 128MB total; self-hosted celld nodes run multi-GB heaps */ +const TIGHT_MEMORY = typeof caches !== "undefined"; +const MAX_BUFFERED_ENTRY = (TIGHT_MEMORY ? 8 : 32) * 1024 * 1024; +/** full entries up to this size are kept in cache — they are likely delta bases */ +const CACHE_ENTRY_LIMIT = (TIGHT_MEMORY ? 2 : 4) * 1024 * 1024; +/** recent entry offsets kept in memory for ofs-delta base resolution */ +const OFFSET_WINDOW = 150_000; +/** + * Decoded pack chunks kept hot for readRaw. The clone loop reads one object + * per call in walk order, so without this every object re-SELECTs and + * re-decodes a whole 1MB row. A handful of 1MB chunks covers any delta chain + * and the locality of the walk. + */ +const RAW_CHUNK_CACHE = TIGHT_MEMORY ? 4 : 8; +/** + * Hard cap on delta base-chain length when resolving an object. git's default + * pack depth is 50; 50000 leaves enormous headroom for legitimately deep packs + * while a crafted unbounded chain is rejected instead of looping forever. The + * base walk is iterative (not recursive) and separately cycle-checked via a + * seen-set, so this bounds chain length rather than guarding stack depth. + */ + +/** + * pako output-chunk size. The default (64 KiB) is large enough that V8 keeps + * every inflate's backing store in its array-buffer arena, so streaming a pack + * one Inflate per object commits arena proportional to the object count — a + * 53MB pack peaked near 250MB of buffers this way. 16 KiB chunks are collected + * promptly, holding inflate memory to a bounded working set regardless of pack + * size. + */ +const INFLATE_CHUNK = 16 * 1024; +const inflateAll = (data: Uint8Array): Uint8Array => { + const inf = new pako.Inflate({ chunkSize: INFLATE_CHUNK }); + const chunks: Uint8Array[] = []; + let size = 0; + inf.onData = (chunk: Uint8Array) => { + size += chunk.length; + if (size > gitWorkLimits().maxObjectBytes) throw new Error("git object exceeds inflated size limit"); + chargeGitWork(chunk.length); + chunks.push(chunk); + }; + inf.push(data, true); + if (inf.err) throw new Error(`inflate failed: ${inf.msg}`); + return concat(chunks); +}; + +export interface ObjRec { + type: ObjType; + data: Uint8Array; +} + +export interface PackedEntry { + oid: string; + packId: number; + offset: number; + dataOff: number; + dataLen: number; + type: ObjType; + size: number; + entrySize: number; + baseOid: string | null; +} + +export type ExternalResolver = (oid: string) => ObjRec | null; + +/** Byte-budgeted LRU cache of inflated objects (delta-chain bases, hot commits/trees). */ +export class ObjCache { + private map = new Map(); + private bytes = 0; + + constructor(private budget: number) {} + + get(oid: string): ObjRec | undefined { + const hit = this.map.get(oid); + if (hit) { + this.map.delete(oid); + this.map.set(oid, hit); + } + return hit; + } + + put(oid: string, obj: ObjRec): void { + if (obj.data.length > this.budget / 4) return; + if (this.map.has(oid)) return; + this.map.set(oid, obj); + this.bytes += obj.data.length; + while (this.bytes > this.budget) { + const oldest = this.map.keys().next().value as string; + this.bytes -= this.map.get(oldest)!.data.length; + this.map.delete(oldest); + } + } +} + +// ingest is strictly sequential, so scratch hashers serve every object. The +// SHA-1DC pair is used only when collision detection is enabled; the plain +// streaming hasher covers the flag-off huge-object path. +const scratchSha = new Sha1Dc(); +const streamSha = new Sha1Dc(); +const streamShaPlain = new Sha1(); + +/** + * Finish a SHA-1DC hash, refusing anything carrying a SHA-1 collision-attack + * block. This is git's post-SHAttered rule: the id is still plain SHA-1, but + * an object built to collide never enters the database. + */ +function finishOid(h: Sha1Dc): string { + const oid = toHex(h.digest()); + if (h.collision) throw new Sha1CollisionError(oid); + return oid; +} + +/** + * Hash a fully-materialized object. With collision detection off (default) the + * id comes from native crypto.subtle — byte-identical to plain SHA-1 but ~24x + * faster than the JS hasher; with it on, SHA-1DC screens every block. The + * object is already in memory here, so the one-shot header+data buffer adds no + * unbounded allocation. + */ +async function hashObjectAsync(type: ObjType, data: Uint8Array, cd: boolean): Promise { + if (cd) return finishOid(scratchSha.reset().update(objectHeader(type, data.length)).update(data)); + const header = objectHeader(type, data.length); + const buf = new Uint8Array(header.length + data.length); + buf.set(header); + buf.set(data, header.length); + return toHex(new Uint8Array(await crypto.subtle.digest("SHA-1", buf))); +} + +/** + * Buffered sequential reader over a pack stored as SQLite chunk rows or an R2 + * object. Chunks are loaded through the owning PackStore's chunk cache (async + * because an R2-backed chunk is a range GET), so byte()/window() await; the SQL + * backend resolves without I/O. + */ +class PackReader { + pos = 0; + private seq = -1; + private chunk: Uint8Array = new Uint8Array(0); + + constructor(private load: (seq: number) => Promise, readonly size: number) {} + + private async ensure(): Promise { + gitWorkLimits(); + if (this.pos >= this.size) throw new Error("truncated pack entry"); + const want = Math.floor(this.pos / PACK_CHUNK); + if (want !== this.seq) { + this.chunk = await this.load(want); + this.seq = want; + } + } + + async byte(): Promise { + await this.ensure(); + return this.chunk[this.pos++ - this.seq * PACK_CHUNK]; + } + + /** Remaining bytes of the chunk containing pos (never empty while pos < size). */ + async window(): Promise { + await this.ensure(); + return this.chunk.subarray(this.pos - this.seq * PACK_CHUNK); + } +} + +/** + * Pack-native object database: received packfiles are stored verbatim — in R2 + * under `raw//` when a bucket is bound (PACK_CACHE), else in + * SQLite chunk rows (the fallback / celld path) — and indexed (oid -> + * pack/offset/base), preserving the client's delta compression. Only the index + * ever lives in SQLite for an R2-backed pack, so pack data escapes the per-DO + * storage ceiling. This is what lets large repos fit and stream. + */ +export class PackStore { + /** LRU of decoded pack chunks, keyed "packId:seq" (SQLite row or R2 range). */ + private chunks = new Map(); + /** + * R2 raw-pack backend for this repo, or null when no bucket is bound (celld / + * Workers without the binding). When set, newly ingested packs store their + * bytes in R2 under `raw//` and keep only the index in SQLite; + * pre-existing SQLite packs keep working (backend is recorded per pack). + */ + private r2: { bucket: R2Bucket; repo: string } | null = null; + /** Cached backend ('sql' | 'r2') per pack id, from pack_meta.store. */ + private backend = new Map(); + + constructor(private sql: SqlStorage, private extern: ExternalResolver) { + this.init(); + } + + /** Bind (or clear) the R2 backend. Idempotent; the DO is per-repo so this is + * set on each request from the repo name. */ + setR2(bucket: R2Bucket | undefined, repo: string): void { + this.r2 = bucket ? { bucket, repo } : null; + } + + private rawKey(packId: number): string { + return `raw/${this.r2!.repo}/${packId}`; + } + + /** Storage backend of a pack. Cached; falls back to a pack_meta lookup. The + * cache is primed at ingest start (before pack_meta exists) so phase B/C read + * the right source. */ + private backendOf(packId: number): "sql" | "r2" { + const hit = this.backend.get(packId); + if (hit) return hit; + const rows = this.sql + .exec<{ store: string }>("SELECT store FROM pack_meta WHERE pack_id = ?", packId) + .toArray(); + const b = rows[0]?.store === "r2" ? "r2" : "sql"; + this.backend.set(packId, b); + return b; + } + + private init(): void { + this.sql.exec(` + CREATE TABLE IF NOT EXISTS pack_meta ( + pack_id INTEGER PRIMARY KEY, + size INTEGER NOT NULL, + count INTEGER NOT NULL, + created INTEGER NOT NULL, + store TEXT NOT NULL DEFAULT 'sql' + ); + CREATE TABLE IF NOT EXISTS pack_data ( + pack_id INTEGER NOT NULL, + seq INTEGER NOT NULL, + data BLOB NOT NULL, + PRIMARY KEY (pack_id, seq) + ); + CREATE TABLE IF NOT EXISTS pack_objects ( + oid TEXT PRIMARY KEY, + pack_id INTEGER NOT NULL, + offset INTEGER NOT NULL, + data_off INTEGER NOT NULL, + data_len INTEGER NOT NULL, + type TEXT NOT NULL, + size INTEGER NOT NULL, + entry_size INTEGER NOT NULL, + base_oid TEXT + ); + CREATE INDEX IF NOT EXISTS idx_pack_objects_loc ON pack_objects(pack_id, offset); + CREATE TABLE IF NOT EXISTS pack_pending ( + pack_id INTEGER NOT NULL, + offset INTEGER NOT NULL, + data_off INTEGER NOT NULL, + data_len INTEGER NOT NULL, + entry_size INTEGER NOT NULL, + base_oid TEXT, + base_offset INTEGER, + PRIMARY KEY (pack_id, offset) + ); + `); + // back-fill the store column on repos whose pack_meta predates the R2 backend: + // every such pack is SQLite-backed, which the 'sql' default records + const cols = this.sql.exec<{ name: string }>("PRAGMA table_info(pack_meta)").toArray(); + if (!cols.some((c) => c.name === "store")) { + this.sql.exec("ALTER TABLE pack_meta ADD COLUMN store TEXT NOT NULL DEFAULT 'sql'"); + } + } + + wipe(): void { + for (const t of ["pack_meta", "pack_data", "pack_objects", "pack_pending"]) { + this.sql.exec(`DROP TABLE IF EXISTS ${t}`); + } + this.chunks.clear(); // pack ids restart from 1: cached rows would be stale + this.backend.clear(); + } + + /** Drop all packs and start empty (small-repo gc migrates objects out first). */ + reset(): void { + this.wipe(); + this.init(); + } + + /** Pack ids of the currently R2-backed packs (for GC to delete their R2 bytes). */ + r2PackIds(): number[] { + return this.sql + .exec<{ pack_id: number }>("SELECT pack_id FROM pack_meta WHERE store = 'r2'") + .toArray() + .map((r) => r.pack_id); + } + + /** Delete the R2 raw objects for the given pack ids (no-op without a binding). */ + async deleteR2Packs(packIds: number[]): Promise { + if (!this.r2 || !packIds.length) return; + const keys = packIds.map((id) => this.rawKey(id)); + for (let i = 0; i < keys.length; i += 100) { + try { + await this.r2.bucket.delete(keys.slice(i, i + 100)); + } catch { + // best effort: an undeleted raw object is unreferenced garbage + } + } + } + + countObjects(): number { + return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM pack_objects").one().n; + } + + /** Total stored bytes across all indexed packs (0 when pack-empty). */ + totalPackBytes(): number { + return this.sql.exec<{ n: number }>("SELECT COALESCE(SUM(size), 0) AS n FROM pack_meta").one().n; + } + + /** + * Bytes of pack storage the raw-chunk LRU keeps hot. A pack no larger than + * this fits entirely in cache, so readRaw never re-decodes a chunk no matter + * what order objects are emitted in — sorting for read locality is pure + * overhead below this threshold. + */ + rawCacheWindow(): number { + return RAW_CHUNK_CACHE * PACK_CHUNK; + } + + lookup(oid: string): PackedEntry | null { + gitWorkLimits(); + const rows = this.sql + .exec<{ + pack_id: number; offset: number; data_off: number; data_len: number; + type: ObjType; size: number; entry_size: number; base_oid: string | null; + }>( + "SELECT pack_id, offset, data_off, data_len, type, size, entry_size, base_oid FROM pack_objects WHERE oid = ?", + oid + ) + .toArray(); + const r = rows[0]; + if (!r) return null; + return { + oid, packId: r.pack_id, offset: r.offset, dataOff: r.data_off, dataLen: r.data_len, + type: r.type, size: r.size, entrySize: r.entry_size, baseOid: r.base_oid, + }; + } + + typeAndSize(oid: string): { type: ObjType; size: number } | null { + const rows = this.sql + .exec<{ type: ObjType; size: number }>("SELECT type, size FROM pack_objects WHERE oid = ?", oid) + .toArray(); + return rows[0] ?? null; + } + + /** Distinct delta-base oids: a second reference edge gc must not sever. */ + baseOids(): string[] { + return this.sql + .exec<{ base_oid: string }>("SELECT DISTINCT base_oid FROM pack_objects WHERE base_oid IS NOT NULL") + .toArray() + .map((r) => r.base_oid); + } + + findOidPrefix(prefix: string): string[] { + return this.sql + .exec<{ oid: string }>("SELECT oid FROM pack_objects WHERE oid LIKE ? LIMIT 2", prefix + "%") + .toArray() + .map((r) => r.oid); + } + + /** + * Raw stored (still-compressed) bytes of a pack region. Chunk rows are + * fetched one at a time: a wide range in a single SELECT can exceed the + * runtime's result-set size cap (celld materializes blob rows as JSON). + */ + async readRaw(packId: number, off: number, len: number): Promise { + gitWorkLimits(); + const first = Math.floor(off / PACK_CHUNK); + const last = Math.floor((off + len - 1) / PACK_CHUNK); + const out = new Uint8Array(len); + for (let seq = first; seq <= last; seq++) { + const chunk = await this.chunk(packId, seq); + const chunkStart = seq * PACK_CHUNK; + const from = Math.max(off, chunkStart); + const to = Math.min(off + len, chunkStart + chunk.length); + if (to > from) out.set(chunk.subarray(from - chunkStart, to - chunkStart), from - off); + } + return out; + } + + /** + * One decoded pack chunk, through the LRU. For a SQLite-backed pack this is a + * `pack_data` row; for an R2-backed pack it is an aligned ~1 MiB range GET + * against `raw//`, so sorted sequential reads (a clone) issue + * ~one GET per chunk instead of one per object. Chunks are immutable once + * written — a pack is inserted once and only ever removed wholesale (wipe/ + * reset, or the orphan sweep at the top of ingest, both of which clear the + * cache), so a hit can never be stale. + */ + private async chunk(packId: number, seq: number): Promise { + const key = `${packId}:${seq}`; + const hit = this.chunks.get(key); + if (hit) { + this.chunks.delete(key); // reinsert: most-recently-used goes last + this.chunks.set(key, hit); + return hit; + } + let chunk: Uint8Array; + if (this.backendOf(packId) === "r2") { + if (!this.r2) throw new Error(`pack ${packId}: R2 backend not bound`); + const obj = await this.r2.bucket.get(this.rawKey(packId), { + range: { offset: seq * PACK_CHUNK, length: PACK_CHUNK }, + }); + if (!obj) throw new Error(`pack ${packId}: missing R2 object ${this.rawKey(packId)}`); + chunk = new Uint8Array(await obj.arrayBuffer()); + } else { + const rows = this.sql + .exec<{ data: ArrayBuffer }>( + "SELECT data FROM pack_data WHERE pack_id = ? AND seq = ?", + packId, + seq + ) + .toArray(); + if (!rows.length) throw new Error(`pack ${packId}: missing chunk ${seq}`); + chunk = new Uint8Array(rows[0].data); + } + this.chunks.set(key, chunk); + while (this.chunks.size > RAW_CHUNK_CACHE) { + this.chunks.delete(this.chunks.keys().next().value as string); + } + return chunk; + } + + /** + * Inflate + delta-resolve an object out of pack storage. A crafted pack can + * chain deltas arbitrarily deep or in a cycle, so the base chain is walked + * ITERATIVELY (not recursively) through cheap index lookups first — bounding + * the chain length and detecting cycles before a single delta is inflated — + * then applied from the base upward, holding at most two inflated buffers at + * a time. This caps both stack depth and peak memory regardless of input. + */ + async getObject(oid: string, cache: ObjCache): Promise { + gitWorkLimits(); + const cached = cache.get(oid); + if (cached) return cached; + const first = this.lookup(oid); + if (!first) return null; + + // walk to the base via lookups only: collect the delta entries, resolve + // where the chain bottoms out (a full entry, a cached object, or a thin + // base from another pack / loose storage). + const chain: PackedEntry[] = []; + const seen = new Set(); + let base: ObjRec | null = null; + let cur: PackedEntry = first; + for (;;) { + if (seen.has(cur.oid)) throw new Error(`cyclic delta chain at ${cur.oid}`); + seen.add(cur.oid); + if (!cur.baseOid) { + base = { type: cur.type, data: inflateAll(await this.readRaw(cur.packId, cur.dataOff, cur.dataLen)) }; + break; + } + if (chain.length >= gitWorkLimits().maxDeltaDepth) throw new Error(`delta chain exceeds depth ${gitWorkLimits().maxDeltaDepth} at ${oid}`); + chain.push(cur); + const cachedBase = cache.get(cur.baseOid); + if (cachedBase) { base = cachedBase; break; } + const next = this.lookup(cur.baseOid); + if (!next) { + const ext = this.extern(cur.baseOid); + if (!ext) throw new Error(`missing delta base ${cur.baseOid} for ${cur.oid}`); + base = ext; + break; + } + cur = next; + } + + // apply deltas from the base upward (chain is target..base order) + let obj = base; + for (let i = chain.length - 1; i >= 0; i--) { + const d = chain[i]; + const delta = inflateAll(await this.readRaw(d.packId, d.dataOff, d.dataLen)); + obj = { type: base.type, data: applyDelta(obj.data, delta) }; + cache.put(d.oid, obj); + } + if (!chain.length) cache.put(oid, obj); + return obj; + } + + /** + * Ingest a packfile arriving as a byte stream: store the bytes verbatim + * (to R2 when a bucket is bound, else SQLite chunk rows) while verifying the + * SHA-1 trailer on the fly, then index sequentially. + * Deltas resolve eagerly against the LRU cache — pack ordering keeps + * bases hot — so the straggler pass afterwards is nearly empty. Memory + * stays bounded regardless of pack size. + */ + async ingest( + firstBytes: Uint8Array, + reader: ReadableStreamDefaultReader | null, + opts: { + maxBytes: number; + /** push body size (content-length ~= pack size); packs this size are + * stored in R2 when a bucket is bound, else in SQLite. Absent means the + * client went chunked, which git only does above ~1MB (http.postBuffer) + * — so unknown size picks R2, the safe side for the 10GB SQLite cap. */ + sizeHint?: number; + cache: ObjCache; + onProgress?: (msg: string) => void; + /** called periodically so the runtime can flush its write buffer — + * workerd holds a request's dirty pages in the 128MB isolate heap */ + flush?: () => Promise; + /** screen every block with SHA-1DC (git-parity collision detection); + * default hashes with native crypto.subtle, which yields the identical + * oid without the collision check */ + collisionDetect?: boolean; + } + ): Promise<{ packId: number; count: number }> { + const cd = opts.collisionDetect ?? false; + // a failed or interrupted ingest leaves rows (or an R2 raw object) without a + // pack_meta entry; reclaim that space before starting (pack_meta is only + // written on success). Union across every per-pack table so an R2 ingest that + // died mid-index — whose bytes are in R2, not pack_data — is caught too. + const orphans = this.sql + .exec<{ pack_id: number }>( + `SELECT pack_id FROM ( + SELECT DISTINCT pack_id FROM pack_data + UNION SELECT DISTINCT pack_id FROM pack_objects + UNION SELECT DISTINCT pack_id FROM pack_pending + ) WHERE pack_id NOT IN (SELECT pack_id FROM pack_meta)` + ) + .toArray(); + for (const o of orphans) { + for (const t of ["pack_data", "pack_objects", "pack_pending"]) { + this.sql.exec(`DELETE FROM ${t} WHERE pack_id = ?`, o.pack_id); + } + // an interrupted R2 ingest may have left a completed raw object; delete it + if (this.r2) { + try { + await this.r2.bucket.delete(this.rawKey(o.pack_id)); + } catch { + // best effort: the packId is reused next and its raw key overwritten + } + } + } + // the reclaimed pack id is about to be handed out again: drop anything the + // chunk LRU still holds for it (and for anything else — it is only a cache) + if (orphans.length) this.chunks.clear(); + const packId = + (this.sql.exec<{ m: number | null }>("SELECT MAX(pack_id) AS m FROM pack_meta").one().m ?? 0) + 1; + const started = Date.now(); + const say = (msg: string) => { + opts.onProgress?.(msg); + console.log(`[ingest pack ${packId} +${Math.round((Date.now() - started) / 1000)}s] ${msg.trim()}`); + }; + + // storage backend: with an R2 binding, a large (sizeHint >= R2_PACK_MIN_BYTES) + // or unknown-length (chunked, so >1MB) pack streams its bytes to + // raw// via multipart and only the index stays in SQLite; small + // declared-length packs go to pack_data. Prime the backend cache now — before + // pack_meta exists — so phase B/C readRaw hits the right source. A refused + // multipart begin (celld makes createMultipartUpload throw) degrades to SQLite. + let capture: MultipartCapture | null = null; + const wantR2 = this.r2 !== null && (opts.sizeHint === undefined || opts.sizeHint >= R2_PACK_MIN_BYTES); + if (this.r2 && wantR2) { + const mp = await beginRawMultipart(this.r2.bucket, this.rawKey(packId)); + if (mp) capture = new MultipartCapture(mp); + } + const r2Backed = capture !== null; + this.backend.set(packId, r2Backed ? "r2" : "sql"); + + // phase A: stream bytes into R2 (or chunk rows), hashing all but the trailing 20. + // Strictly linear: a cursor fills a fixed 1MB buffer — the source may + // arrive as one multi-GB chunk (celld buffers request bodies), so any + // re-concatenation of the remainder would go quadratic. + const sha = new Sha1(); + let tail = new Uint8Array(0); // rolling 20-byte lookbehind (the trailer) + let total = 0; + let seq = 0; + const chunkBuf = new Uint8Array(PACK_CHUNK); + let chunkLen = 0; + let lastLogged = 0; + const feed = (data: Uint8Array) => { + total += data.length; + if (total > opts.maxBytes) throw new Error("pack exceeds maximum push size"); + if (total - lastLogged >= 64 * 1024 * 1024) { + lastLogged = total; + say(`Receiving pack: ${Math.round(total / 1048576)}MB\n`); + } + const joined = tail.length ? concat([tail, data]) : data; + if (joined.length > 20) { + sha.update(joined.subarray(0, joined.length - 20)); + tail = joined.slice(joined.length - 20); + } else { + tail = joined.slice(); + } + if (capture) { + capture.push(data); // copied into a 16 MiB multipart part buffer + return; + } + let off = 0; + while (off < data.length) { + const take = Math.min(PACK_CHUNK - chunkLen, data.length - off); + chunkBuf.set(data.subarray(off, off + take), chunkLen); + chunkLen += take; + off += take; + if (chunkLen === PACK_CHUNK) { + this.sql.exec( + "INSERT INTO pack_data (pack_id, seq, data) VALUES (?, ?, ?)", + packId, + seq++, + chunkBuf.slice().buffer + ); + chunkLen = 0; + } + } + }; + // feed in bounded slices with yields, so one giant buffered body doesn't + // monopolize the event loop for a minutes-long synchronous stretch + const FEED_SLICE = 8 * 1024 * 1024; + const feedSliced = async (data: Uint8Array) => { + for (let off = 0; off < data.length; off += FEED_SLICE) { + feed(data.subarray(off, off + FEED_SLICE)); + if (capture) { + await capture.drain(); // upload whole 16 MiB parts, keep only the remainder + if (capture.aborted) throw new Error("pack upload to R2 failed"); + } + if (data.length > FEED_SLICE) await new Promise((res) => setTimeout(res, 0)); + await opts.flush?.(); + } + }; + if (firstBytes.length) await feedSliced(firstBytes); + if (reader) { + for (;;) { + const { done, value } = await readGitChunk(reader); + if (done) break; + if (value?.length) await feedSliced(value); + } + } + if (!capture && chunkLen > 0) { + this.sql.exec( + "INSERT INTO pack_data (pack_id, seq, data) VALUES (?, ?, ?)", + packId, + seq++, + chunkBuf.slice(0, chunkLen).buffer + ); + } + // validate the trailer before completing the R2 upload, so a corrupt push + // never leaves a finished raw object (abort leaves R2 with nothing). + if (total < 32) { + if (capture) await capture.abort(); + throw new Error("pack too small"); + } + if (toHex(tail) !== toHex(sha.digest())) { + if (capture) await capture.abort(); + throw new Error("pack checksum mismatch"); + } + if (capture) { + // complete the multipart BEFORE phase B/C: both readRaw the finished raw + // object (phase B for eager delta bases, phase C for deferred deltas). + await capture.finish(); + if (capture.aborted) throw new Error("pack upload to R2 failed"); + } + say(`Received pack: ${Math.round(total / 1048576)}MB\n`); + + // phase B: sequential scan with eager delta resolution + const r = new PackReader((s) => this.chunk(packId, s), total); + const magic = new Uint8Array(4); + for (let i = 0; i < 4; i++) magic[i] = await r.byte(); + if (td.decode(magic) !== "PACK") throw new Error("bad pack signature"); + let version = 0, count = 0; + for (let i = 0; i < 4; i++) version = (version << 8) | (await r.byte()); + for (let i = 0; i < 4; i++) count = (count << 8) | (await r.byte()); + if (version !== 2 && version !== 3) throw new Error(`unsupported pack version ${version}`); + + // batched index inserts: one exec per object made pack_objects a top SQL + // cost, and deferring rows is safe because delta bases resolve from the + // in-memory offset window and object cache — the flush points below cover + // the rare pack_objects SELECT fallbacks (oidByOffset miss, getObject). + // OR IGNORE keeps a duplicate oid's FIRST location — including within one + // batch — so a failed ingest's orphan sweep can't strand a stored object. + // workerd caps a DO SQL statement at ~100 bound variables (celld's stock + // SQLite allows more); 10 rows x 9 cols = 90 stays under that on both. + const OBJ_BATCH = 10; + let objBatch: (string | number | null)[] = []; + let objBatchRows = 0; + const flushObjects = () => { + if (!objBatchRows) return; + const values = Array(objBatchRows).fill("(?,?,?,?,?,?,?,?,?)").join(","); + this.sql.exec( + `INSERT OR IGNORE INTO pack_objects (oid, pack_id, offset, data_off, data_len, type, size, entry_size, base_oid) VALUES ${values}`, + ...objBatch + ); + objBatch = []; + objBatchRows = 0; + }; + const insertObject = (row: (string | number | null)[]) => { + for (const v of row) objBatch.push(v); + if (++objBatchRows >= OBJ_BATCH) flushObjects(); + }; + const insertPending = (row: (string | number | null)[]) => { + this.sql.exec( + "INSERT INTO pack_pending (pack_id, offset, data_off, data_len, entry_size, base_oid, base_offset) VALUES (?,?,?,?,?,?,?)", + ...row + ); + }; + + // rotating offset -> oid window: ofs-delta bases are nearly always recent + let winCur = new Map(); + let winPrev = new Map(); + const winPut = (off: number, oid: string) => { + winCur.set(off, oid); + if (winCur.size >= OFFSET_WINDOW) { + winPrev = winCur; + winCur = new Map(); + } + }; + const oidByOffset = (off: number): string | null => { + const hit = winCur.get(off) ?? winPrev.get(off); + if (hit) return hit; + flushObjects(); // a windowed miss falls back to SELECT: deferred rows must be visible + const rows = this.sql + .exec<{ oid: string }>("SELECT oid FROM pack_objects WHERE pack_id = ? AND offset = ?", packId, off) + .toArray(); + return rows[0]?.oid ?? null; + }; + + let pendingCount = 0; + for (let i = 0; i < count; i++) { + gitWorkLimits(); + const offset = r.pos; + let byte = await r.byte(); + const type = (byte >> 4) & 7; + let entrySize = byte & 15; + let shift = 4; + while (byte & 0x80) { + byte = await r.byte(); + entrySize += (byte & 0x7f) * 2 ** shift; + shift += 7; + } + if (!Number.isSafeInteger(entrySize) || entrySize < 0 || entrySize > gitWorkLimits().maxObjectBytes) { + throw new Error("git object exceeds inflated size limit"); + } + let baseOid: string | null = null; + let baseOffset: number | null = null; + if (type === 6) { + byte = await r.byte(); + let off = byte & 0x7f; + while (byte & 0x80) { + byte = await r.byte(); + off = (off + 1) * 128 + (byte & 0x7f); + } + baseOffset = offset - off; + } else if (type === 7) { + const b = new Uint8Array(20); + for (let j = 0; j < 20; j++) b[j] = await r.byte(); + baseOid = toHex(b); + } else if (!NUM_TYPE[type]) { + throw new Error(`bad object type ${type} at ${offset}`); + } + + const dataOff = r.pos; + const isFull = type >= 1 && type <= 4; + const objType = isFull ? NUM_TYPE[type] : null; + const buffered = entrySize <= MAX_BUFFERED_ENTRY; + // buffered entries inflate straight into one exact-size buffer (no piece + // array + concat, which would hold the object twice at once) + const content = buffered ? new Uint8Array(entrySize) : null; + if (isFull && !buffered) { + if (cd) streamSha.reset().update(objectHeader(objType!, entrySize)); + else streamShaPlain.reset().update(objectHeader(objType!, entrySize)); + } + let inflated = 0; + const inf = new pako.Inflate({ chunkSize: INFLATE_CHUNK }); + (inf as unknown as { onData: (c: Uint8Array) => void }).onData = (c: Uint8Array) => { + if (inflated + c.length > entrySize) throw new Error("entry size mismatch"); + chargeGitWork(c.length); + if (content) content.set(c, inflated); + else if (isFull) (cd ? streamSha : streamShaPlain).update(c); + inflated += c.length; + }; + const anyInf = inf as unknown as { err: number; msg: string; ended: boolean; strm: { avail_in: number } }; + while (!anyInf.ended) { + if (r.pos >= total) throw new Error(`truncated pack entry at ${offset}`); + const win = await r.window(); + inf.push(win, false); + if (anyInf.err) throw new Error(`inflate failed at ${dataOff}: ${anyInf.msg}`); + r.pos += anyInf.ended ? win.length - anyInf.strm.avail_in : win.length; + } + if (inflated !== entrySize) throw new Error(`entry size mismatch at ${offset}`); + const dataLen = r.pos - dataOff; + + if (isFull) { + const oid = buffered + ? await hashObjectAsync(objType!, content!, cd) + : cd + ? finishOid(streamSha) + : toHex(streamShaPlain.digest()); + insertObject([oid, packId, offset, dataOff, dataLen, objType!, entrySize, entrySize, null]); + winPut(offset, oid); + if (content && content.length <= CACHE_ENTRY_LIMIT) { + opts.cache.put(oid, { type: objType!, data: content }); + } + } else { + const resolvedBase = baseOid ?? (baseOffset !== null ? oidByOffset(baseOffset) : null); + let resolved = false; + if (buffered && resolvedBase) { + let base: ObjRec | null = opts.cache.get(resolvedBase) ?? null; + if (!base) { + flushObjects(); // getObject SELECTs pack_objects: deferred rows must be visible + try { + base = await this.getObject(resolvedBase, opts.cache); + } catch { + base = null; + } + } + if (!base) base = this.extern(resolvedBase); + if (base) { + const data = applyDelta(base.data, content!); + const oid = await hashObjectAsync(base.type, data, cd); + insertObject([oid, packId, offset, dataOff, dataLen, base.type, data.length, entrySize, resolvedBase]); + winPut(offset, oid); + if (data.length <= CACHE_ENTRY_LIMIT) { + opts.cache.put(oid, { type: base.type, data }); + } + resolved = true; + } + } + if (!resolved) { + insertPending([packId, offset, dataOff, dataLen, entrySize, baseOid, baseOffset]); + pendingCount++; + } + } + + if (i % 2000 === 1999) { + await new Promise((res) => setTimeout(res, 0)); + await opts.flush?.(); + if (i % 100000 === 99999) say(`Indexing objects: ${i + 1}/${count}\n`); + } + } + // the header count must account for every byte up to the 20-byte trailer; + // otherwise objects were silently dropped (or junk trails the pack) + if (r.pos !== total - 20) throw new Error("pack has trailing data or bad object count"); + await opts.flush?.(); + say(`Indexed ${count} objects (${pendingCount} deferred)\n`); + + // phase C: stragglers — deltas whose base appeared later in the pack, + // or thin-pack bases that live in another pack / loose storage + let pendingTotal = this.sql + .exec<{ n: number }>("SELECT COUNT(*) AS n FROM pack_pending WHERE pack_id = ?", packId) + .one().n; + let resolvedTotal = 0; + while (pendingTotal > 0) { + let resolvedThisPass = 0; + let lastOffset = -1; + for (;;) { + const page = this.sql + .exec<{ + offset: number; data_off: number; data_len: number; entry_size: number; + base_oid: string | null; base_offset: number | null; + }>( + "SELECT offset, data_off, data_len, entry_size, base_oid, base_offset FROM pack_pending WHERE pack_id = ? AND offset > ? ORDER BY offset LIMIT 500", + packId, + lastOffset + ) + .toArray(); + if (!page.length) break; + for (const row of page) { + lastOffset = row.offset; + let baseOid = row.base_oid; + if (!baseOid && row.base_offset !== null) { + baseOid = oidByOffset(row.base_offset); + if (!baseOid) continue; // base itself still pending + } + if (!baseOid) continue; + let base: ObjRec | null = null; + flushObjects(); // getObject SELECTs pack_objects: deferred rows must be visible + try { + base = (await this.getObject(baseOid, opts.cache)) ?? this.extern(baseOid); + } catch { + base = null; + } + if (!base) continue; // thin base not available (yet) + const delta = inflateAll(await this.readRaw(packId, row.data_off, row.data_len)); + const data = applyDelta(base.data, delta); + const oid = await hashObjectAsync(base.type, data, cd); + insertObject([oid, packId, row.offset, row.data_off, row.data_len, base.type, data.length, row.entry_size, baseOid]); + this.sql.exec("DELETE FROM pack_pending WHERE pack_id = ? AND offset = ?", packId, row.offset); + winPut(row.offset, oid); + if (data.length <= CACHE_ENTRY_LIMIT) opts.cache.put(oid, { type: base.type, data }); + resolvedTotal++; + resolvedThisPass++; + if (resolvedTotal % 2000 === 0) { + await new Promise((res) => setTimeout(res, 0)); + if (resolvedTotal % 100000 === 0) say(`Resolving deltas: ${resolvedTotal}\n`); + } + } + } + pendingTotal -= resolvedThisPass; + if (resolvedThisPass === 0 && pendingTotal > 0) { + throw new Error(`cannot resolve ${pendingTotal} delta object(s): missing base`); + } + } + if (resolvedTotal) say(`Resolved ${resolvedTotal} deferred delta(s)\n`); + flushObjects(); // commit the final partial batch before pack_meta marks the pack complete + + this.sql.exec( + "INSERT INTO pack_meta (pack_id, size, count, created, store) VALUES (?, ?, ?, ?, ?)", + packId, total, count, Date.now(), r2Backed ? "r2" : "sql" + ); + return { packId, count }; + } +} diff --git a/apps/api/src/vendor/dgit/git/pktline.ts b/apps/api/src/vendor/dgit/git/pktline.ts new file mode 100644 index 0000000000..9ba8d573cf --- /dev/null +++ b/apps/api/src/vendor/dgit/git/pktline.ts @@ -0,0 +1,69 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { te, td, concat } from "./util"; + +export const FLUSH = te.encode("0000"); + +/** Encode one pkt-line (length prefix includes the 4 prefix bytes). */ +export function pkt(payload: string | Uint8Array): Uint8Array { + const body = typeof payload === "string" ? te.encode(payload) : payload; + if (body.length > 65516) throw new Error("pkt-line too long"); + return concat([te.encode((body.length + 4).toString(16).padStart(4, "0")), body]); +} + +export function pktLines(...payloads: (string | Uint8Array)[]): Uint8Array { + return concat(payloads.map(pkt)); +} + +export type Pkt = { kind: "flush" | "delim" | "line"; raw: Uint8Array; text: string }; + +/** Iterates pkt-lines from a buffer; `rest()` returns unparsed bytes (e.g. a packfile). */ +export class PktParser { + pos = 0; + constructor(private buf: Uint8Array) {} + + /** + * Strict 4-byte hex length. `parseInt` is too lenient for attacker-framed + * input — it accepts leading whitespace and stops at the first non-digit, so + * " 12" or "001g" would parse to a bogus length and desync the stream. Every + * one of the four bytes must be a hex digit or the packet is rejected. + */ + private len4(): number { + let n = 0; + for (let i = 0; i < 4; i++) { + const c = this.buf[this.pos + i]; + let d: number; + if (c >= 0x30 && c <= 0x39) d = c - 0x30; + else if (c >= 0x61 && c <= 0x66) d = c - 0x57; + else if (c >= 0x41 && c <= 0x46) d = c - 0x37; + else throw new Error("bad pkt-line length"); + n = (n << 4) | d; + } + return n; + } + + read(): Pkt | null { + if (this.pos + 4 > this.buf.length) return null; + const len = this.len4(); + // 0000 flush and 0001 delim are the only special lengths; 0002/0003 are + // undefined and rejected, as is any declared length that overruns the buffer. + if (len === 0) { + this.pos += 4; + return { kind: "flush", raw: new Uint8Array(0), text: "" }; + } + if (len === 1) { + this.pos += 4; + return { kind: "delim", raw: new Uint8Array(0), text: "" }; + } + if (len < 4 || this.pos + len > this.buf.length) throw new Error("bad pkt-line"); + const raw = this.buf.subarray(this.pos + 4, this.pos + len); + this.pos += len; + let text = td.decode(raw); + if (text.endsWith("\n")) text = text.slice(0, -1); + return { kind: "line", raw, text }; + } + + rest(): Uint8Array { + return this.buf.subarray(this.pos); + } +} diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts new file mode 100644 index 0000000000..5ee4e9f6b3 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -0,0 +1,1361 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +// FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) +import { concat, isOid, ZERO_OID, te } from "./util"; +import { pkt, FLUSH, PktParser } from "./pktline"; +import { GitStore } from "./store"; +import { PackWriter } from "./pack"; +import { OidSet } from "./oidset"; +import { MultipartCapture, MultipartPackUpload } from "./multipart"; +import { parseCommit, parseTag, parseTree, isGitlinkMode, isTreeMode, TYPE_NUM, NUM_TYPE, ObjType } from "./objects"; + +const AGENT = "agent=dgit/0.3"; +const INFINITE_DEPTH = 0x7fffffff; +const SIDEBAND_CHUNK = 32 * 1024; +const WALK_YIELD = 5000; +/** + * Committer-date skew tolerated before the uninteresting (have) commit walk + * stops descending. Cutting the walk short can only ever shrink the "client + * already has it" set, i.e. send a few redundant objects — never omit one — + * so a day of slack is a safe way to keep an incremental fetch off the full + * commit graph. + */ +const WALK_DATE_SLOP = 24 * 60 * 60; + +export type Service = "git-upload-pack" | "git-receive-pack"; + +/** + * Optional R2-backed full-clone offload, write side only: on a full-clone MISS + * the DO tees the generated pack into a multipart upload so it never buffers the + * whole pack in isolate memory (no size cap). Absent on celld and on Workers + * without the binding, in which case every clone is served from the DO exactly + * as before. HITs are served by the Worker streaming R2 directly, not the DO. + */ +export interface PackCache { + repo: string; + /** Begin a multipart pack build under `key`, stamping the object count as + * customMetadata; null when R2 is unavailable (the clone still streams). */ + beginMultipart(key: string, objects: number): Promise; +} + +/** GET /info/refs?service=... — smart ref advertisement. */ +export function advertisement(store: GitStore, service: Service, v2 = false): Uint8Array { + if (v2 && service === "git-upload-pack") { + return concat([pkt("version 2\n"), pkt(`${AGENT}\n`), pkt("ls-refs\n"), pkt("fetch=shallow\n"), FLUSH]); + } + const caps = + service === "git-upload-pack" + ? [ + "multi_ack_detailed", + "no-done", + "shallow", + "side-band-64k", + `symref=HEAD:${store.head()}`, + AGENT, + ].join(" ") + : ["report-status", "delete-refs", "ofs-delta", "side-band-64k", AGENT].join(" "); + + const lines: Uint8Array[] = [pkt(`# service=${service}\n`), FLUSH]; + const refs: { name: string; target: string }[] = []; + if (service === "git-upload-pack") { + const head = store.resolveHead(); + if (head) refs.push({ name: "HEAD", target: head }); + } + refs.push(...store.refs()); + + if (refs.length === 0) { + lines.push(pkt(`${ZERO_OID} capabilities^{}\0${caps}\n`)); + } else { + refs.forEach((r, i) => { + lines.push(pkt(i === 0 ? `${r.target} ${r.name}\0${caps}\n` : `${r.target} ${r.name}\n`)); + }); + } + lines.push(FLUSH); + return concat(lines); +} + +/** + * The oids a fetch is allowed to `want`: exactly what the advertisement above + * exposes — HEAD, every current ref tip, and the peeled commit target of each + * annotated tag (git advertises those as `^{}`). + * + * This is git's default (`uploadpack.allowAnySHA1InWant=false`): serving any + * oid the database merely *has* leaks objects that are no longer reachable + * from any ref — a commit orphaned by a force-push stays readable to anyone + * who learned its sha. Membership in a set of ref tips, so a normal fetch + * (which only ever wants advertised tips) pays a few hash lookups, not a walk. + */ +export async function advertisedOids(store: GitStore): Promise> { + const oids = new Set(); + const head = store.resolveHead(); + if (head) oids.add(head); + for (const r of store.refs()) { + oids.add(r.target); + // peel annotated tags; lightweight tags already point at the commit + if (!r.name.startsWith("refs/tags/")) continue; + if (store.typeAndSize(r.target)?.type !== "tag") continue; + const peeled = await peelToCommitOid(store, r.target); + if (peeled) oids.add(peeled); + } + return oids; +} + +/** + * True when `wants` is exactly the set of current ref tips — a true full clone, + * not a single-branch or partial fetch. Only then does the whole-repo reachable + * cache describe precisely what the client asked for; a subset of the tips would + * pull unrelated branches' objects in and leave the client with danglers. + */ +export function wantsAreAllTips(store: GitStore, wants: string[]): boolean { + const tips = new Set(); + for (const r of store.refs()) tips.add(r.target); + if (tips.size === 0) return false; + const wantSet = new Set(wants); + if (wantSet.size !== tips.size) return false; + for (const t of tips) if (!wantSet.has(t)) return false; + return true; +} + +export function sidebandFrames(band: number, payload: Uint8Array): Uint8Array[] { + const frames: Uint8Array[] = []; + for (let off = 0; off < payload.length; off += SIDEBAND_CHUNK) { + const chunk = payload.subarray(off, off + SIDEBAND_CHUNK); + const framed = new Uint8Array(chunk.length + 1); + framed[0] = band; + framed.set(chunk, 1); + frames.push(pkt(framed)); + } + return frames; +} + +/** + * Serve a full clone by streaming the R2-cached raw pack straight from the + * Worker: the protocol's pack preamble, the + * optional band-2 progress line, then the pack re-chunked into band-1 side-band + * frames as R2 hands it over, then flush. Framing is identical to the DO path + * and the pack bytes are the stored bytes, so the client receives a + * byte-for-byte-equal pack. Memory is one R2 read chunk at a time — never + * proportional to pack size — and the DO is never contacted for bytes. + */ +export function streamingCloneResponse( + body: ReadableStream, + objects: number, + noProgress: boolean, v2 = false +): Response { + const headers = { + "content-type": "application/x-git-upload-pack-result", + "cache-control": "no-cache", + "x-pack-cache": "hit", + }; + const reader = body.getReader(); + let started = false; + let done = false; + const stream = new ReadableStream({ + pull: async (ctrl) => { + try { + if (!started) { + started = true; + ctrl.enqueue(pkt(v2 ? "packfile\n" : "NAK\n")); + if (!noProgress) { + for (const f of sidebandFrames(2, te.encode(`Enumerating objects: ${objects}, done.\n`))) ctrl.enqueue(f); + } + } + const { done: rdone, value } = await reader.read(); + if (rdone) { + if (!done) { + done = true; + ctrl.enqueue(FLUSH); + ctrl.close(); + } + return; + } + for (const f of sidebandFrames(1, value)) ctrl.enqueue(f); + } catch (err) { + ctrl.error(err); + } + }, + cancel: () => reader.cancel(), + }); + return new Response(stream, { headers }); +} + +interface UploadRequest { + command: "fetch" | "ls-refs" | null; + wants: string[]; + haves: string[]; + done: boolean; + clientShallows: string[]; + deepen: number; // 0 = no depth limit requested + caps: Set; +} + +export function parseUploadRequest(body: Uint8Array): UploadRequest { + const parser = new PktParser(body); + const req: UploadRequest = { + command: null, + wants: [], + haves: [], + done: false, + clientShallows: [], + deepen: 0, + caps: new Set(), + }; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind !== "line") continue; + const line = p.text; + if (line === "command=fetch" || line === "command=ls-refs") { + req.command = line === "command=fetch" ? "fetch" : "ls-refs"; + } else if (line === "no-progress" || line === "symrefs" || line === "peel") { + req.caps.add(line); + } else if (line.startsWith("want ")) { + req.wants.push(line.slice(5, 45)); + // capabilities ride on the first want line + for (const cap of line.slice(45).trim().split(" ")) if (cap) req.caps.add(cap); + } else if (line.startsWith("have ")) { + req.haves.push(line.slice(5, 45)); + } else if (line.startsWith("shallow ")) { + req.clientShallows.push(line.slice(8, 48)); + } else if (line.startsWith("deepen ")) { + req.deepen = parseInt(line.slice(7), 10) || 0; + } else if (line === "done") { + req.done = true; + } + } + return req; +} + +async function lsRefs(store: GitStore, req: UploadRequest): Promise { + const lines: Uint8Array[] = []; + const head = store.resolveHead(); + if (head) lines.push(pkt(`${head} HEAD${req.caps.has("symrefs") ? ` symref-target:${store.head()}` : ""}\n`)); + for (const ref of store.refs()) { + let peeled = ""; + if (req.caps.has("peel") && ref.name.startsWith("refs/tags/") && store.typeAndSize(ref.target)?.type === "tag") { + const oid = await peelToCommitOid(store, ref.target); + if (oid) peeled = ` peeled:${oid}`; + } + lines.push(pkt(`${ref.target} ${ref.name}${peeled}\n`)); + } + return concat([...lines, FLUSH]); +} + +/** Follow tag objects down to the underlying commit oid (or null). */ +async function peelToCommitOid(store: GitStore, oid: string): Promise { + for (let i = 0; i < 10; i++) { + const obj = await store.get(oid); + if (!obj) return null; + if (obj.type === "commit") return oid; + if (obj.type === "tag") { + oid = parseTag(obj.data).object; + continue; + } + return null; + } + return null; +} + +/** + * Newest committer time (ms) across every current ref tip and HEAD: each tip is + * peeled through annotated tags to its commit and its committer time taken; + * non-commit tips are ignored, parse errors skipped. Falls back to Date.now() + * when the repo holds no commits. Committer time is unix seconds, so ×1000. + */ +export async function latestCommitTime(store: GitStore): Promise { + const tips = new Set(); + const head = store.resolveHead(); + if (head) tips.add(head); + for (const r of store.refs()) tips.add(r.target); + let max = 0; + for (const tip of tips) { + try { + const oid = await peelToCommitOid(store, tip); + if (!oid) continue; + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + const t = parseCommit(obj.data).committer.time; + if (t > max) max = t; + } catch { + // broken/unparseable tip: skip it, never fail the push/config + } + } + return max > 0 ? max * 1000 : Date.now(); +} + +/** + * Depth-limited commit set from the wants (BFS, min depth wins; the tip is + * depth 1, like git). Boundary commits are included but their parents cut. + */ +async function computeDepthSet( + store: GitStore, + wants: string[], + depth: number +): Promise<{ commits: Set; boundary: Set }> { + const commits = new Set(); + const boundary = new Set(); + const queue: { oid: string; depth: number }[] = []; + for (const w of wants) { + const c = await peelToCommitOid(store, w); + if (c && !commits.has(c)) { + commits.add(c); + queue.push({ oid: c, depth: 1 }); + } + } + while (queue.length) { + const { oid, depth: d } = queue.shift()!; + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + const parents = parseCommit(obj.data).parents; + if (d >= depth) { + // every commit reached at the depth limit is a graft point, root commits + // included — git's get_shallow_commits() marks them unconditionally, and + // the client compares the advertised list against its own .git/shallow + boundary.add(oid); + continue; + } + boundary.delete(oid); // reachable within depth via this (shorter) path + for (const p of parents) { + if (!commits.has(p) && store.has(p)) { + commits.add(p); + queue.push({ oid: p, depth: d + 1 }); + } + } + } + return { commits, boundary }; +} + +/** + * Commits reachable from the wants without passing through one of the + * client's haves — the "interesting" side of the walk — plus the oldest + * committer date among them. Commit objects only; no trees are touched. + * + * The date is what bounds the uninteresting side: nothing older than the + * oldest thing the client is asking for can be needed as a boundary, so the + * have walk may stop there instead of marching down the whole commit graph. + */ +async function interestingCommits( + store: GitStore, + wants: string[], + haveCommits: Set, + yieldMaybe: () => Promise +): Promise<{ set: OidSet; minTime: number }> { + const set = new OidSet(4096); + const stack: string[] = []; + for (const w of wants) { + const c = await peelToCommitOid(store, w); + if (c && !haveCommits.has(c) && set.addHex(c)) stack.push(c); + } + let minTime = Infinity; + while (stack.length) { + const oid = stack.pop()!; + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + await yieldMaybe(); + const c = parseCommit(obj.data); + if (c.committer.time < minTime) minTime = c.committer.time; + for (const p of c.parents) { + if (haveCommits.has(p)) continue; // the client's side of the boundary + if (store.has(p) && set.addHex(p)) stack.push(p); + } + } + return { set, minTime }; +} + +/** + * Objects the client demonstrably already has, marked the way git marks + * UNINTERESTING: commits reachable from the haves (cut at the client's + * shallow boundaries), plus the *tree closure of the boundary commits only* + * — the client's own tips and the uninteresting parents of the commits it is + * asking for. Boundary tree descent halts the moment it reaches an object + * already known present, so shared subtrees are walked once, and history the + * fetch never touches is never inflated at all. + * + * The set is deliberately allowed to be an under-approximation: leaving an + * object out only means re-sending something the client had (a bigger pack), + * while putting one in wrongly would produce a broken pack. Every bound here + * therefore errs towards sending. + */ +async function excludedObjects( + store: GitStore, + haves: string[], + clientShallows: string[], + wants: string[] +): Promise { + const excluded = new OidSet(Math.max(haves.length * 64, 4096)); + if (!haves.length) return excluded; // full clone: nothing is excluded + + let ops = 0; + const yieldMaybe = async () => { + if (++ops % WALK_YIELD === 0) await new Promise((r) => setTimeout(r, 0)); + }; + + // the client's tips, peeled through any annotated tags + const haveCommits = new Set(); + for (const h of haves) { + if (!store.has(h)) continue; + const c = await peelToCommitOid(store, h); + if (c) haveCommits.add(c); + } + + const { set: interesting, minTime } = await interestingCommits(store, wants, haveCommits, yieldMaybe); + // minTime stays Infinity when the client wants nothing new: then no ancestor + // of a have can be a boundary and the walk stops at the haves themselves. + const cutoff = minTime === Infinity ? Infinity : minTime - WALK_DATE_SLOP; + + // uninteresting commit walk — commits and tags only, no trees + const shallowStops = new Set(clientShallows); + const commitStack: string[] = []; + for (const h of haves) { + if (store.has(h) && excluded.addHex(h)) commitStack.push(h); + } + while (commitStack.length) { + const oid = commitStack.pop()!; + const obj = await store.get(oid); + if (!obj) continue; + await yieldMaybe(); + if (obj.type === "tag") { + const t = parseTag(obj.data).object; + if (t && store.has(t) && excluded.addHex(t)) commitStack.push(t); + continue; + } + if (obj.type !== "commit") continue; + const c = parseCommit(obj.data); + if (shallowStops.has(oid)) continue; // client's history stops here + if (c.committer.time < cutoff) continue; // older than anything wanted + for (const p of c.parents) { + if (store.has(p) && excluded.addHex(p)) commitStack.push(p); + } + } + + // boundary commits whose trees are worth marking: the client's own tips + // (it has those trees in full) and the uninteresting parents of interesting + // commits (git's mark_edges_uninteresting). + const boundary: string[] = []; + for (const c of haveCommits) boundary.push(c); + for (let i = 0; i < interesting.size; i++) { + const oid = interesting.atHex(i); + if (excluded.hasHex(oid)) continue; // contested: reachable from a have too + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + await yieldMaybe(); + for (const p of parseCommit(obj.data).parents) { + if (excluded.hasHex(p)) boundary.push(p); + } + } + + const trees: string[] = []; + for (const oid of boundary) { + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + const tree = parseCommit(obj.data).tree; + if (tree && excluded.addHex(tree)) trees.push(tree); + } + while (trees.length) { + const oid = trees.pop()!; + const obj = await store.get(oid); + if (obj?.type !== "tree") continue; + await yieldMaybe(); + for (const e of parseTree(obj.data)) { + if (isGitlinkMode(e.mode)) continue; + // already present => the whole subtree below it is too; stop descending + if (excluded.addHex(e.oid) && isTreeMode(e.mode)) trees.push(e.oid); + } + } + return excluded; +} + +/** + * Objects to pack: closure of wants, minus excluded, cut at commitLimit. + * Returned as one OidSet whose tagged sub-set is the pack contents — the + * untagged remainder is the walk's visited bookkeeping, which is a strict + * superset, so one set carries both roles at half the per-object cost. + * + * `descendThroughExcluded` is set only when the client is deepening: with a + * shallow client, commits BELOW its boundary are not excluded and must be + * reachable even when the walk enters via commits it already has (deepen and + * unshallow fetches). On an ordinary fetch the walk must stop dead at an + * excluded commit — descending anyway re-sends the history the client + * deliberately does not have, and strands it below its own shallow graft. + * Blobs are added by type lookup alone — never inflated during the walk. + */ +async function collectPackOids( + store: GitStore, + wants: string[], + excluded: OidSet, + commitLimit: Set | null, + descendThroughExcluded: boolean, + expected: number +): Promise { + // The frontier is the visited set itself, walked in insertion order by a + // cursor: a child is appended with addHex (deduped in place) and reached + // when the cursor gets to it, so there is no separate stack of hex oids to + // hold alongside the OidSet. The result set is decided by membership, so + // this BFS and the old DFS produce the identical walk and marked sub-set. + const walk = new OidSet(expected); + for (const w of wants) walk.addHex(w); + let ops = 0; + for (let i = 0; i < walk.size; i++) { + const oid = walk.atHex(i); + if (++ops % WALK_YIELD === 0) await new Promise((r) => setTimeout(r, 0)); + const meta = store.typeAndSize(oid); + if (!meta) throw new Error(`missing object ${oid}`); + if (meta.type === "commit" && commitLimit && !commitLimit.has(oid)) continue; + if (excluded.hasHex(oid)) { + if (descendThroughExcluded && meta.type === "commit") { + const full = (await store.get(oid))!; + for (const p of parseCommit(full.data).parents) walk.addHex(p); + } + continue; + } + walk.markHex(oid); + if (meta.type === "blob") continue; // leaf: membership only + for (const child of childOids((await store.get(oid))!)) walk.addHex(child); + } + return walk; +} + +/** + * POST /git-upload-pack — stateless protocol v0 with single-ack negotiation, + * shallow (--depth) support, side-band-64k, and a streamed pack response. + * Stored pack entries are copied verbatim (deltas preserved) whenever their + * base ships in the same pack; everything else is inflated and re-deflated. + */ +export async function uploadPack( + store: GitStore, + body: Uint8Array, + release: () => void = () => {}, + packCache?: PackCache +): Promise { + const headers = { + "content-type": "application/x-git-upload-pack-result", + "cache-control": "no-cache", + }; + const req = parseUploadRequest(body); + if (req.command === "ls-refs") { + release(); + return new Response(await lsRefs(store, req) as unknown as BodyInit, { headers }); + } + const v2 = req.command === "fetch"; + if (!req.wants.length || req.wants.some((w) => !isOid(w))) { + release(); + return new Response(pkt("ERR no valid wants\n") as unknown as BodyInit, { headers }); + } + // a want must be an object we currently advertise, not merely one we store + const allowed = await advertisedOids(store); + for (const w of req.wants) { + if (!allowed.has(w) || !store.has(w)) { + release(); + return new Response(pkt(`ERR upload-pack: not our ref ${w}\n`) as unknown as BodyInit, { headers }); + } + } + + const preamble: Uint8Array[] = []; + + // shallow section (only when the client asked to deepen) + let commitLimit: Set | null = null; + if (req.deepen > 0) { + if (v2) preamble.push(pkt("shallow-info\n")); + const clientShallowSet = new Set(req.clientShallows); + if (req.deepen >= INFINITE_DEPTH) { + // --unshallow: full history, everything the client thought was shallow opens up + for (const s of req.clientShallows) { + if (store.has(s)) preamble.push(pkt(`unshallow ${s}\n`)); + } + } else { + const { commits, boundary } = await computeDepthSet(store, req.wants, req.deepen); + commitLimit = commits; + for (const b of boundary) { + if (!clientShallowSet.has(b)) preamble.push(pkt(`shallow ${b}\n`)); + } + for (const s of req.clientShallows) { + if (commits.has(s) && !boundary.has(s)) preamble.push(pkt(`unshallow ${s}\n`)); + } + } + preamble.push(v2 ? te.encode("0001") : FLUSH); + } + if (v2 && !req.done) preamble.length = 0; + + // Negotiation. A round with neither haves nor done (shallow discovery) gets + // no ack line at all — a stray NAK would desync the client's stateless + // response stream. + // + // Single-ack cannot carry a stateless fetch on its own: `ACK ` means + // "negotiation over, pack follows", so a client that receives one mid-round + // stops negotiating and reads the response as a pack — but git only batches + // 16 haves per round, and the follow-up request it sends carries no haves at + // all. The pack therefore has to be produced by the same request that + // carried the haves, which is exactly what multi_ack_detailed's `ready` plus + // `no-done` is for. This mirrors upload-pack's wire shape line for line; + // clients that negotiate neither capability keep the single-ack path. + const common = req.haves.filter((h) => isOid(h) && store.has(h)); + const lastCommon = common.length ? common[common.length - 1] : null; + let sendPack = req.done; + if (v2) { + if (req.done) preamble.push(pkt("packfile\n")); + else { + const acknowledgments = common.length ? common.map((oid) => pkt(`ACK ${oid}\n`)) : [pkt("NAK\n")]; + preamble.push(pkt("acknowledgments\n"), ...acknowledgments, FLUSH); + } + } else if (!req.caps.has("multi_ack_detailed")) { + if (req.done || req.haves.length) { + preamble.push(pkt(common.length ? `ACK ${common[0]}\n` : "NAK\n")); + } + } else if (req.done) { + for (const c of common) preamble.push(pkt(`ACK ${c} common\n`)); + preamble.push(pkt(lastCommon ? `ACK ${lastCommon}\n` : "NAK\n")); + } else if (req.haves.length) { + for (const c of common) preamble.push(pkt(`ACK ${c} common\n`)); + if (lastCommon && req.caps.has("no-done")) { + // enough common ground to build the pack, and the client agreed it can + // be answered without a `done` round trip: reply with it right here, + // while the haves are still in hand + preamble.push(pkt(`ACK ${lastCommon} ready\n`)); + preamble.push(pkt("NAK\n")); + preamble.push(pkt(`ACK ${lastCommon}\n`)); + sendPack = true; + } else { + preamble.push(pkt("NAK\n")); // keep negotiating + } + } + + if (!sendPack) { + // negotiation round only — client will POST again + release(); + return new Response(concat(preamble) as unknown as BodyInit, { headers }); + } + + const sideband = v2 || req.caps.has("side-band-64k"); + const noProgress = req.caps.has("no-progress"); + + // Full-clone fast path: no haves, not shallow/deepen, and the wants are + // exactly the current ref tips. The reachable object set is then identical to + // what the graph walk would rediscover, so serve it from the versioned cache + // and skip the walk (and every commit/tree inflation it drives) entirely. A + // missing or stale cache (version mismatch, or any failure) falls straight + // through to the walk, which then repopulates it — so a wrong pack is never + // served, and existing repos become fast on their next full clone. + const fullClone = !req.haves.length && req.deepen === 0 && wantsAreAllTips(store, req.wants); + + // R2 full-clone offload (write side). Only a standard side-band-64k full clone + // is eligible, and it is reached only after the advertised-oids gate above — so + // the versioned key can never warm an unreachable/force-pushed object. The key + // is the ref version, so a push/force-push/delete lands on a fresh key and + // stale packs are simply never referenced. HITs are served by the Worker + // streaming R2 directly; the DO only reaches here on a MISS, where it serves + // the client and self-warms the cache via multipart while it streams (see + // `capture` below). Absent R2 (celld / no binding) this is a plain DO clone. + const r2Key = + fullClone && sideband && packCache ? `pack/${packCache.repo}/${store.reachableVersion()}` : null; + + // Warm full-clone fast path: the reachable set is persisted and current, so + // stream the pack straight out of storage in (pack_id, offset) order without + // ever loading the object set into the isolate. This is the O(1)-memory clone + // — no OidSet, no parallel typed arrays — bounded by one keyset page instead + // of the object count. A cold or stale cache falls through to the walk below, + // which rebuilds and persists the set (one in-RAM walk, then warm forever). + if (fullClone && store.reachableCacheValid()) { + return warmFullClone(store, { + preamble, + sideband, + noProgress, + r2Key, + packCache, + release, + headers, + }); + } + + let send = fullClone ? store.loadReachable() : null; + if (!send) { + const excluded = await excludedObjects(store, req.haves, req.clientShallows, req.wants); + // a plain clone enumerates the whole database: size the walk's set up front + // so it never doubles (a doubling keeps the old and new arrays live at once) + const expected = + !req.haves.length && !commitLimit && !req.deepen ? Math.max(store.objectCount(), 4096) : 4096; + send = await collectPackOids( + store, + req.wants, + excluded, + commitLimit, + req.deepen > 0, // descendThroughExcluded: only while deepening/unshallowing + expected + ); + if (fullClone) { + try { + await store.saveReachable(send); + } catch { + // the cache is best-effort: a failed persist just means the next full + // clone walks again, never a wrong pack + } + } + } + // Emit objects in pack storage order — (packId, offset) — rather than the + // DFS walk order they were collected in. Reused entries are copied straight + // out of stored packs via readRaw, and the raw-chunk LRU only pays off when + // consecutive reads stay inside the same 1MB pack chunk; walk order jumps + // all over the pack, so it rarely does. Marching sequentially through each + // pack lifts that hit rate to ~100% and cuts per-object decode cost. + // + // Order-safe: the SET of emitted entries and every entry's bytes are decided + // by set membership alone (isMarkedHex on the delta base), never by position, + // so only the ordering changes. Delta entries are re-addressed as REF-deltas + // (see PackWriter.rawDelta) and git's index-pack resolves ref-deltas in any + // order via a second pass; no ofs-deltas are ever emitted. Loose objects + // (no pack entry) sort last, ordered by oid, for a stable total order. + // + // Only worth it once the packs outgrow the raw-chunk LRU: below that every + // chunk stays cached regardless of order, so the sort would be pure overhead. + // The arrays stay null then and emission falls back to walk order with a + // per-object lookup, exactly as before. + // + // The lookups done to build the sort key are *retained* — in LEAN parallel + // typed arrays, not an array of PackedEntry objects — and reused by the + // stream, so sorting adds an in-memory sort but not a second round of SQL + // lookups. Storing the reused fields as five typed arrays (~28 B/obj) rather + // than live objects (~204 B/obj) is what keeps a one-shot full clone inside + // the 128MB isolate at multi-million-object scale. + // + // ePack Int32 pack id (1-based), or LOOSE_PACK for objects with no + // pack entry (loose / unindexed) — those sort last, by oid. + // eDataOff Float64 start of the stored (compressed) region. Offsets on a + // pack past 4GB exceed 2^32, so this must NOT be a Uint32. The + // (packId, dataOff) pair is also the sort key: dataOff rises + // monotonically with entry offset within a pack, so ordering by + // it reproduces pack storage order exactly. + // eDataLen Uint32 length of that region (a single entry never reaches + // the 4GB a Uint32 caps, and readRaw could not allocate one). + // eSize Float64 uncompressed entry size for the pack object header. + // A blob copied verbatim on a big-heap celld node can exceed 4GB + // uncompressed, so this is not a Uint32 either. + // eCode Int32 how to emit the object, folding type and delta base + // into one slot (they are mutually exclusive per entry): + // >= 0 ref-delta whose base ships in this pack; the value is + // the base's insertion index in `send` (base oid = + // send.atHex(code)). + // <= -3 full entry copied verbatim; NUM_TYPE[-2 - code] is its + // type (commit=-3, tree=-4, blob=-5, tag=-6). + // -1 inflate via store.get: a loose object, or a delta whose + // base is not being sent (so it cannot be a ref-delta). + const total = send.markedSize; + let order: Int32Array | null = null; + let ePack: Int32Array | null = null; + let eDataOff: Float64Array | null = null; + let eDataLen: Uint32Array | null = null; + let eSize: Float64Array | null = null; + let eCode: Int32Array | null = null; + const LOOSE_PACK = 0x7fffffff; // sorts after every real (1-based) pack id + if (store.packs.totalPackBytes() > store.packs.rawCacheWindow()) { + ePack = new Int32Array(total); + eDataOff = new Float64Array(total); + eDataLen = new Uint32Array(total); + eSize = new Float64Array(total); + eCode = new Int32Array(total); + for (let i = 0; i < total; i++) { + const entry = store.packs.lookup(send.markedAtHex(i)); + if (!entry) { + ePack[i] = LOOSE_PACK; + eCode[i] = -1; + } else { + ePack[i] = entry.packId; + eDataOff[i] = entry.dataOff; + eDataLen[i] = entry.dataLen; + eSize[i] = entry.entrySize; + if (entry.baseOid) { + // ref-delta only when the base also ships here; else inflate it + eCode[i] = send.isMarkedHex(entry.baseOid) ? send.indexOfHex(entry.baseOid) : -1; + } else { + eCode[i] = -2 - TYPE_NUM[entry.type]; + } + } + if ((i & 8191) === 8191) await new Promise((r) => setTimeout(r, 0)); + } + order = new Int32Array(total); + for (let i = 0; i < total; i++) order[i] = i; + order.sort((a, b) => { + if (ePack![a] !== ePack![b]) return ePack![a] - ePack![b]; + if (ePack![a] === LOOSE_PACK) { + const oa = send.markedAtHex(a); + const ob = send.markedAtHex(b); + return oa < ob ? -1 : oa > ob ? 1 : 0; + } + return eDataOff![a] - eDataOff![b]; + }); + } + + // stream the pack: preamble, then pack bytes (side-band framed if negotiated) + const pending: Uint8Array[] = [concat(preamble)]; + let buffered: Uint8Array[] = []; + let bufferedLen = 0; + const flushBuffered = () => { + if (!bufferedLen) return; + const payload = concat(buffered); + buffered = []; + bufferedLen = 0; + if (sideband) pending.push(...sidebandFrames(1, payload)); + else pending.push(payload); + }; + // Self-warm R2 on a full-clone MISS: tee the raw pack (writer output, verbatim + // — same bytes a later HIT re-frames) into a multipart upload alongside the + // live stream. The pack streams into R2 in 16 MiB parts as it is generated, so + // isolate memory is never proportional to pack size and there is no size cap. + // A failed begin just streams the clone without caching. + let capture: MultipartCapture | null = null; + if (r2Key && packCache) { + const mp = await packCache.beginMultipart(r2Key, total); + if (mp) capture = new MultipartCapture(mp); + } + const writer = new PackWriter((chunk) => { + if (capture) capture.push(chunk); + buffered.push(chunk); + bufferedLen += chunk.length; + if (bufferedLen >= SIDEBAND_CHUNK) flushBuffered(); + }); + + let i = 0; + let finished = false; + const stream = new ReadableStream({ + start: (ctrl) => { + if (sideband && !noProgress) { + pending.push(...sidebandFrames(2, te.encode(`Enumerating objects: ${total}, done.\n`))); + } + writer.header(total); + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + }, + pull: async (ctrl) => { + try { + for (let n = 0; n < 64 && i < total; n++, i++) { + const idx = order ? order[i] : i; + if (!eCode) { + // unsorted (small-pack) path: no sort pass ran, so do a fresh + // per-object lookup in walk order, exactly as before OPT 2. + const oid = send.markedAtHex(idx); + const entry = store.packs.lookup(oid); + if (entry && !entry.baseOid) { + writer.rawFull(entry.type, entry.entrySize, await store.packs.readRaw(entry.packId, entry.dataOff, entry.dataLen)); + } else if (entry && entry.baseOid && send.isMarkedHex(entry.baseOid)) { + writer.rawDelta(entry.entrySize, entry.baseOid, await store.packs.readRaw(entry.packId, entry.dataOff, entry.dataLen)); + } else { + const obj = await store.get(oid); + if (!obj) throw new Error(`missing object ${oid}`); + writer.object(obj.type, obj.data); + } + continue; + } + // sorted path: everything needed to emit the object was captured in + // the lean typed arrays, so no SQL lookup happens here. + const code = eCode[idx]; + if (code <= -3) { + writer.rawFull(NUM_TYPE[-2 - code], eSize![idx], await store.packs.readRaw(ePack![idx], eDataOff![idx], eDataLen![idx])); + } else if (code >= 0) { + writer.rawDelta(eSize![idx], send.atHex(code), await store.packs.readRaw(ePack![idx], eDataOff![idx], eDataLen![idx])); + } else { + const oid = send.markedAtHex(idx); + const obj = await store.get(oid); + if (!obj) throw new Error(`missing object ${oid}`); + writer.object(obj.type, obj.data); + } + } + if (i >= total && !finished) { + finished = true; + writer.finish(); + flushBuffered(); + if (sideband) pending.push(FLUSH); + } else { + flushBuffered(); + } + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + // Warm R2 in lock-step with generation: the client already has this + // batch's bytes, and awaiting the part upload here is what bounds isolate + // memory to one part regardless of pack size. finish() flushes the final + // part and completes; a failure aborts, leaving no partial R2 object. + if (capture) { + if (finished) await capture.finish(); + else await capture.drain(); + } + if (finished) { + ctrl.close(); + release(); // stream fully drained: this upload no longer holds a slot + } + } catch (err) { + if (capture) await capture.abort(); + release(); + ctrl.error(err); + } + }, + cancel: async () => { + // client went away mid-transfer (e.g. negotiation round abort): abort the + // half-built multipart upload so R2 keeps no partial object + if (capture) await capture.abort(); + release(); + }, + }); + return new Response(stream, { headers }); +} + +/** + * Stream a full clone straight from the persisted reachable set, holding no + * object set in the isolate. The reachable cache is current (the caller checked + * `reachableCacheValid`), so the objects to send are exactly its rows: emit the + * packed ones in (pack_id, offset) storage order a keyset page at a time, then + * the loose ones by oid. Peak memory is one page plus one object, independent + * of repo size — the walk path's OidSet and parallel typed arrays are gone. + * + * Emission is byte-identical to the walk path: a stored delta ships as a + * ref-delta when its base is also reachable (so also sent), else it is inflated + * whole; index-pack resolves ref-deltas by oid in any order. `total` is the + * reachable count, declared in the header; if the set drifts mid-stream (a push + * landing during the clone) the count guard aborts rather than ship a pack that + * disagrees with its header — the client simply retries. + */ +async function warmFullClone( + store: GitStore, + opts: { + preamble: Uint8Array[]; + sideband: boolean; + noProgress: boolean; + r2Key: string | null; + packCache: PackCache | undefined; + release: () => void; + headers: Record; + }, +): Promise { + const { preamble, sideband, noProgress, r2Key, packCache, release, headers } = opts; + const total = store.reachableCount(); + const PAGE = 1000; + + // One emit-thunk per object, in storage order: every packed reachable object + // (marching packs sequentially), then every loose reachable object by oid. + async function* objects(): AsyncGenerator<(w: PackWriter) => Promise> { + let curPack = 0; + let curOff = -1; + for (;;) { + const rows = store.reachablePackedAfter(curPack, curOff, PAGE); + for (const e of rows) { + curPack = e.packId; + curOff = e.offset; + if (e.baseOid !== null && store.reachableHas(e.baseOid)) { + const base = e.baseOid; + yield async (w) => + w.rawDelta(e.entrySize, base, await store.packs.readRaw(e.packId, e.dataOff, e.dataLen)); + } else if (e.baseOid !== null) { + // base is not itself being sent: it cannot be a ref-delta, inflate it + yield async (w) => { + const obj = await store.get(e.oid); + if (!obj) throw new Error(`missing object ${e.oid}`); + w.object(obj.type, obj.data); + }; + } else { + yield async (w) => + w.rawFull(e.type, e.entrySize, await store.packs.readRaw(e.packId, e.dataOff, e.dataLen)); + } + } + if (rows.length < PAGE) break; + } + let afterOid = ""; + for (;;) { + const loose = store.reachableLooseAfter(afterOid, PAGE); + for (const oid of loose) { + afterOid = oid; + yield async (w) => { + const obj = await store.get(oid); + if (!obj) throw new Error(`missing object ${oid}`); + w.object(obj.type, obj.data); + }; + } + if (loose.length < PAGE) break; + } + } + const it = objects(); + + const pending: Uint8Array[] = [concat(preamble)]; + let buffered: Uint8Array[] = []; + let bufferedLen = 0; + const flushBuffered = () => { + if (!bufferedLen) return; + const payload = concat(buffered); + buffered = []; + bufferedLen = 0; + if (sideband) pending.push(...sidebandFrames(1, payload)); + else pending.push(payload); + }; + let capture: MultipartCapture | null = null; + if (r2Key && packCache) { + const mp = await packCache.beginMultipart(r2Key, total); + if (mp) capture = new MultipartCapture(mp); + } + const writer = new PackWriter((chunk) => { + if (capture) capture.push(chunk); + buffered.push(chunk); + bufferedLen += chunk.length; + if (bufferedLen >= SIDEBAND_CHUNK) flushBuffered(); + }); + + let emitted = 0; + let finished = false; + const stream = new ReadableStream({ + start: (ctrl) => { + if (sideband && !noProgress) { + pending.push(...sidebandFrames(2, te.encode(`Enumerating objects: ${total}, done.\n`))); + } + writer.header(total); + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + }, + pull: async (ctrl) => { + try { + let drained = false; + for (let n = 0; n < 64; n++) { + const next = await it.next(); + if (next.done) { + drained = true; + break; + } + await next.value(writer); + emitted++; + } + if (drained && !finished) { + // A count check, not a full set-consistency check: it catches a push + // that grew or shrank the reachable set mid-stream (the pack would + // disagree with its declared header), so the client retries rather + // than resolve a malformed pack. The cold path snapshots the set into + // an OidSet and has no such window; this is the warm path's tradeoff. + if (emitted !== total) { + throw new Error(`reachable set drifted mid-clone: emitted ${emitted}, declared ${total}`); + } + finished = true; + writer.finish(); + flushBuffered(); + if (sideband) pending.push(FLUSH); + } else { + flushBuffered(); + } + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + if (capture) { + if (finished) await capture.finish(); + else await capture.drain(); + } + if (finished) { + ctrl.close(); + release(); + } + } catch (err) { + if (capture) await capture.abort(); + release(); + ctrl.error(err); + } + }, + cancel: async () => { + if (capture) await capture.abort(); + release(); + }, + }); + return new Response(stream, { headers }); +} + +/** Is `anc` an ancestor of (or equal to) `desc`? Bounded walk. */ +export async function isAncestor(store: GitStore, anc: string, desc: string): Promise { + if (anc === desc) return true; + const seen = new Set([desc]); + const stack = [desc]; + let visited = 0; + while (stack.length && visited++ < 10000) { + const obj = await store.get(stack.pop()!); + if (obj?.type !== "commit") continue; + for (const p of parseCommit(obj.data).parents) { + if (p === anc) return true; + if (!seen.has(p)) { + seen.add(p); + stack.push(p); + } + } + } + return false; +} + +export interface PushCommand { + old: string; + next: string; + ref: string; +} + +export interface CommandResult { + ref: string; + ok: boolean; + msg?: string; +} + +/** Parse the command section of a receive-pack request (already buffered). */ +export function parsePushCommands(section: Uint8Array): { commands: PushCommand[]; caps: string[] } { + const parser = new PktParser(section); + const commands: PushCommand[] = []; + let caps: string[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind === "flush") break; + if (p.kind !== "line") continue; + let line = p.text; + const nul = line.indexOf("\0"); + if (nul !== -1) { + caps = line.slice(nul + 1).trim().split(" "); + line = line.slice(0, nul); + } + const m = line.match(/^([0-9a-f]{40}) ([0-9a-f]{40}) (.+)$/); + if (m) commands.push({ old: m[1], next: m[2], ref: m[3] }); + } + return { commands, caps }; +} + +/** Characters git's check_ref_format rejects, plus HTML-dangerous ones. */ +const BAD_REF = /[\s~^:?*\[\\'"<>&`\x00-\x1f\x7f]/; + +/** + * Every object in the closure of `tip` is present, so setting a ref to it + * cannot brick the repo. A thin/broken pack that fails to close over its new + * ref leaves a referenced object absent; walking commit->tree->subtrees+blobs + * (and tag->target) with a presence probe at each node catches it before the + * ref moves. `known` is pre-seeded with the pre-existing ref tips, whose + * closure was validated at their own push, so descent stops there — the walk + * touches only objects this push introduced. + */ +async function reachableComplete(store: GitStore, tip: string, known: OidSet): Promise { + // Cursor BFS over `known` itself: newly reached oids append past `start`, + // and pre-existing entries (a fast-forward's already-validated closure) sit + // before it and are never re-walked. Reusing the set as its own frontier + // needs no separate hex-oid stack to walk it. + const start = known.size; + if (!known.addHex(tip)) return true; // tip already in a validated closure + for (let i = start; i < known.size; i++) { + const oid = known.atHex(i); + const meta = store.typeAndSize(oid); + if (!meta) return false; + if (meta.type === "blob") continue; + const obj = await store.get(oid); + if (!obj) return false; + for (const child of childOids(obj)) known.addHex(child); + } + return true; +} + +/** Per-command outcome decided by the object-reading validation pass. */ +interface PushDecision { + ref: string; + expectedOld: string; // CAS value re-checked atomically at commit + reject?: string; // ng message; the command does not apply + del?: boolean; // delete the ref + set?: string; // move the ref to this oid + forced?: boolean; // a set that strands old history (non-fast-forward) +} + +/** Result of the async push validation, consumed by the sync commit under a savepoint. */ +export interface PushPlan { + decisions: PushDecision[]; + known: OidSet; + hadCache: boolean; +} + +/** + * Validate push commands against the (already ingested) object database. This + * is the object-reading half — connectivity + ancestry walks — and is async + * because an R2-backed pack's bytes are fetched over the network. It performs no + * writes; the ref mutations happen in commitPush under a savepoint. Splitting + * the read pass out is what lets the writes stay inside transactionSync (which + * cannot await) while still reading R2-backed objects. Pushes are serialized + * (receiveChain) and only pushes write refs, so ref state read here is stable + * through to commit; commitPush re-checks each CAS atomically regardless. + */ +/** The child oids a non-blob object references (blobs are leaves). */ +function childOids(obj: { type: ObjType; data: Uint8Array }): string[] { + if (obj.type === "commit") { + const c = parseCommit(obj.data); + return [c.tree, ...c.parents]; + } + if (obj.type === "tag") { + const t = parseTag(obj.data); + return t.object ? [t.object] : []; + } + if (obj.type === "tree") { + const out: string[] = []; + for (const e of parseTree(obj.data)) if (!isGitlinkMode(e.mode)) out.push(e.oid); + return out; + } + return []; +} + +/** + * Verify a freshly ingested pack is connectivity-complete — every child oid its + * objects reference is present in `pack_objects` ∪ `objects` — and return the + * first missing child, or null when complete. This is the storage-backed + * counterpart to walking the graph: it scans the pack's non-blob objects one + * keyset page at a time, stages their referenced children into `push_edges` in + * bounded batches, and lets SQLite anti-join each batch against the stores. A + * complete pack means every tip in it has a complete closure (by induction over + * the edges), so the whole push is connected — checked in flat memory, with no + * OidSet that scales with the object count. Used for a fresh push, where the + * old walk built a reachable set the commit step then discarded anyway. + */ +async function packComplete(store: GitStore, packId: number): Promise { + const PAGE = 1000; + const EDGE_BATCH = 8192; + store.resetPushEdges(); + let after = ""; + let pending: string[] = []; + const flush = (): string | null => { + if (!pending.length) return null; + store.addPushEdges(pending); + pending = []; + const miss = store.firstMissingPushEdge(); + store.resetPushEdges(); + return miss; + }; + for (;;) { + const page = store.packNonBlobOidsAfter(packId, after, PAGE); + if (!page.length) break; + for (const oid of page) { + const obj = await store.get(oid); + if (!obj) return oid; // indexed but unreadable — the pack is not complete + for (const child of childOids(obj)) pending.push(child); + if (pending.length >= EDGE_BATCH) { + const miss = flush(); + if (miss) return miss; + } + } + after = page[page.length - 1]; + } + return flush(); +} + +export async function validatePush( + store: GitStore, + commands: PushCommand[], + unpackError: string | null, + packId: number | null +): Promise { + // whether the reachable cache is valid for the pre-push refs: only then can + // it be extended in place (union with the connectivity walk) instead of + // rebuilt from scratch on the next full clone + const hadCache = store.getMeta("reachable-version") === store.reachableVersion(); + // A fresh push (no cache to extend) verifies connectivity in SQL rather than + // by walking into an OidSet — the walk's result would be discarded by the + // commit step's invalidate below, so it was pure memory spent to reject a + // broken pack. `packMissing` names the first unresolved child, or stays null. + // A fast-forward keeps the cheap new-object walk, which both verifies and + // extends the cache in one pass. + const packMissing = + !hadCache && !unpackError && packId !== null ? await packComplete(store, packId) : null; + // pre-existing ref tips bound the connectivity walk: their closure is + // already validated, so a normal fast-forward only re-checks new objects + const known = new OidSet(4096); + for (const r of store.refs()) { + known.addHex(r.target); + const c = await peelToCommitOid(store, r.target); + if (c) known.addHex(c); + } + const knownHead = store.resolveHead(); + if (knownHead) known.addHex(knownHead); + + const decisions: PushDecision[] = []; + for (const cmd of commands) { + if (unpackError) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "unpacker error" }); + continue; + } + const bad = !cmd.ref.startsWith("refs/") || cmd.ref.includes("..") || BAD_REF.test(cmd.ref) + || cmd.ref.endsWith(".lock") || cmd.ref.includes("@{") || cmd.ref.includes("//") + || cmd.ref.endsWith("/") || cmd.ref.length > 255 + || cmd.ref.split("/").some((c) => c.startsWith(".")); + if (bad) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "funny refname" }); + continue; + } + const current = store.getRef(cmd.ref) ?? ZERO_OID; + if (current !== cmd.old) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "fetch first" }); + continue; + } + if (cmd.next === ZERO_OID) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, del: true }); + continue; + } + const connected = hadCache + ? await reachableComplete(store, cmd.next, known) + : packMissing === null && store.has(cmd.next); + if (!connected) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "missing necessary objects" }); + continue; + } + const forced = cmd.old !== ZERO_OID && !(await isAncestor(store, cmd.old, cmd.next)); + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, set: cmd.next, forced }); + } + return { decisions, known, hadCache }; +} + +/** + * Apply a validated PushPlan under a savepoint (transactionSync): a multi-ref + * push must not leave half its branches moved if a later update throws. Each CAS + * is re-checked here against live ref state so the write is atomic with its + * guard; a mismatch (a ref moved between validation and commit, which the push + * serialization normally prevents) both rejects that command and forces the + * reachable cache to be rebuilt rather than extended from a now-stale walk. + */ +export function commitPush(store: GitStore, plan: PushPlan): { results: CommandResult[]; changed: boolean; needsGc: boolean } { + const results: CommandResult[] = []; + let changed = false; + let needsGc = false; + let casMismatch = false; + for (const d of plan.decisions) { + if (d.reject) { + results.push({ ref: d.ref, ok: false, msg: d.reject }); + continue; + } + const current = store.getRef(d.ref) ?? ZERO_OID; + if (current !== d.expectedOld) { + results.push({ ref: d.ref, ok: false, msg: "fetch first" }); + casMismatch = true; + continue; + } + if (d.del) { + store.delRef(d.ref); + needsGc = true; + } else { + store.setRef(d.ref, d.set!); + if (d.forced) needsGc = true; // forced update strands old history + } + changed = true; + results.push({ ref: d.ref, ok: true }); + } + + // keep HEAD pointing at a branch that exists (first push wins, prefer main/master) + if (changed && store.getRef(store.head()) === null) { + const branches = store.refs().filter((r) => r.name.startsWith("refs/heads/")); + const preferred = + branches.find((b) => b.name === "refs/heads/main") ?? + branches.find((b) => b.name === "refs/heads/master") ?? + branches[0]; + if (preferred) store.setHead(preferred.name); + } + + // maintain the full-clone reachable cache. `known` holds the connectivity + // walk: the pre-existing tips plus every object this push newly connected. On + // a pure fast-forward with a valid prior cache, union closes over exactly the + // new reachable set. Anything else (a force-push/delete that strands history, + // no prior cache to extend, or a commit-time CAS mismatch that leaves `known` + // describing a command that did not apply) invalidates it, so the next full + // clone rebuilds by walking rather than risk serving unreachable objects. + if (changed) { + if (plan.hadCache && !needsGc && !casMismatch) store.extendReachable(plan.known); + else store.invalidateReachable(); + } + return { results, changed, needsGc }; +} + +/** report-status payload; ends with its own flush (nested inside band 1 when sidebanded). */ +export function renderStatus(results: CommandResult[], unpackError: string | null, sideband: boolean): Uint8Array { + const lines: Uint8Array[] = [pkt(unpackError ? `unpack ${unpackError}\n` : "unpack ok\n")]; + for (const r of results) { + lines.push(pkt(r.ok ? `ok ${r.ref}\n` : `ng ${r.ref} ${r.msg}\n`)); + } + lines.push(FLUSH); + if (!sideband) return concat(lines); + return concat([...sidebandFrames(1, concat(lines)), FLUSH]); +} diff --git a/apps/api/src/vendor/dgit/git/sha1.ts b/apps/api/src/vendor/dgit/git/sha1.ts new file mode 100644 index 0000000000..1e3fbb2502 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/sha1.ts @@ -0,0 +1,369 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { SHA1_DVS, ubcCheck } from "./sha1dc-tables"; + +/** + * Incremental SHA-1. Workers' crypto.subtle is one-shot and async; pack + * streaming needs a running digest and the object database wants sync + * hashing, so we carry our own (git still speaks SHA-1 for object ids). + */ +export class Sha1 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + private block = new Uint8Array(64); + private blockLen = 0; + private bytes = 0; + private w = new Int32Array(80); + + /** Reinitialize so one instance can hash many inputs without reallocating. */ + reset(): this { + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + this.blockLen = 0; + this.bytes = 0; + return this; + } + + update(data: Uint8Array): this { + this.bytes += data.length; + let off = 0; + if (this.blockLen > 0) { + const need = 64 - this.blockLen; + const take = Math.min(need, data.length); + this.block.set(data.subarray(0, take), this.blockLen); + this.blockLen += take; + off = take; + if (this.blockLen === 64) { + this.compress(this.block, 0); + this.blockLen = 0; + } + } + while (off + 64 <= data.length) { + this.compress(data, off); + off += 64; + } + if (off < data.length) { + this.block.set(data.subarray(off), 0); + this.blockLen = data.length - off; + } + return this; + } + + digest(): Uint8Array { + const bitLenHi = Math.floor((this.bytes * 8) / 0x100000000); + const bitLenLo = (this.bytes * 8) >>> 0; + const pad = new Uint8Array(((this.blockLen < 56 ? 56 : 120) - this.blockLen) + 8); + pad[0] = 0x80; + const dv = new DataView(pad.buffer); + dv.setUint32(pad.length - 8, bitLenHi); + dv.setUint32(pad.length - 4, bitLenLo); + this.update(pad); + const out = new Uint8Array(20); + const ov = new DataView(out.buffer); + ov.setInt32(0, this.h0); + ov.setInt32(4, this.h1); + ov.setInt32(8, this.h2); + ov.setInt32(12, this.h3); + ov.setInt32(16, this.h4); + return out; + } + + private compress(buf: Uint8Array, off: number): void { + const w = this.w; + for (let i = 0; i < 16; i++) { + const j = off + i * 4; + w[i] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3]; + } + for (let i = 16; i < 80; i++) { + const n = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + w[i] = (n << 1) | (n >>> 31); + } + let a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; + for (let i = 0; i < 80; i++) { + let f: number, k: number; + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5a827999; + } else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8f1bbcdc | 0; + } else { + f = b ^ c ^ d; + k = 0xca62c1d6 | 0; + } + const t = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0; + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + this.h0 = (this.h0 + a) | 0; + this.h1 = (this.h1 + b) | 0; + this.h2 = (this.h2 + c) | 0; + this.h3 = (this.h3 + d) | 0; + this.h4 = (this.h4 + e) | 0; + } +} + +export function sha1(data: Uint8Array): Uint8Array { + return new Sha1().update(data).digest(); +} + +/* + * SHA-1 collision detection (SHA-1DC) + * + * A port of Stevens & Shumow's sha1collisiondetection, the same defence + * git adopted after SHAttered. Every compressed block is screened by + * ubcCheck against 32 known disturbance vectors; a flagged DV is then + * confirmed by recompressing the block from the DV's test step with the + * perturbed message. If the reconstructed chaining value reproduces the + * real one, the block is half of a collision attack. + * + * Like git, safe-hash mangling stays off: the digest is always plain + * SHA-1, so object ids never move. Detection is reported out-of-band and + * the caller refuses the object. + */ + +const DVS = SHA1_DVS.map((dv) => ({ + testt: dv.testt, + maskb: dv.maskb, + dm: Int32Array.from(dv.dm), +})); + +const K0 = 0x5a827999 | 0; +const K1 = 0x6ed9eba1 | 0; +const K2 = 0x8f1bbcdc | 0; +const K3 = 0xca62c1d6 | 0; + +/** + * One step of the compression function, run over a rotating register file + * so a single loop can serve any step index. At step `i` the roles + * (a,b,c,d,e) live at v[(role - i) mod 5]. + */ +function stepForward(v: Int32Array, i: number, m: Int32Array): void { + const ia = (5 - (i % 5)) % 5; + const ib = (ia + 1) % 5; + const ic = (ia + 2) % 5; + const id = (ia + 3) % 5; + const ie = (ia + 4) % 5; + const a = v[ia], b = v[ib], c = v[ic], d = v[id], e = v[ie]; + let f: number, k: number; + if (i < 20) { f = d ^ (b & (c ^ d)); k = K0; } + else if (i < 40) { f = b ^ c ^ d; k = K1; } + else if (i < 60) { f = (b & c) | (d & (b ^ c)); k = K2; } + else { f = b ^ c ^ d; k = K3; } + v[ie] = (e + (((a << 5) | (a >>> 27)) + f + k + m[i])) | 0; + v[ib] = (b << 30) | (b >>> 2); +} + +/** Inverse of stepForward: undoes step `i`. */ +function stepBackward(v: Int32Array, i: number, m: Int32Array): void { + const ia = (5 - (i % 5)) % 5; + const ib = (ia + 1) % 5; + const ic = (ia + 2) % 5; + const id = (ia + 3) % 5; + const ie = (ia + 4) % 5; + const a = v[ia]; + const b = ((v[ib] >>> 30) | (v[ib] << 2)) | 0; + v[ib] = b; + const c = v[ic], d = v[id], e = v[ie]; + let f: number, k: number; + if (i < 20) { f = d ^ (b & (c ^ d)); k = K0; } + else if (i < 40) { f = b ^ c ^ d; k = K1; } + else if (i < 60) { f = (b & c) | (d & (b ^ c)); k = K2; } + else { f = b ^ c ^ d; k = K3; } + v[ie] = (e - (((a << 5) | (a >>> 27)) + f + k + m[i])) | 0; +} + +/** + * Reconstruct the chaining values a block would have had, had it been + * compressed with the perturbed message `me2`. Runs backwards from step + * `t` to recover the input chaining value, then forwards to step 79 for + * the output. `state` is the real block's register file entering step t. + */ +function recompress( + t: number, + ihvin: Int32Array, + ihvout: Int32Array, + me2: Int32Array, + state: Int32Array, + scratch: Int32Array +): void { + scratch.set(state); + for (let i = t - 1; i >= 0; i--) stepBackward(scratch, i, me2); + ihvin.set(scratch); + scratch.set(state); + for (let i = t; i < 80; i++) stepForward(scratch, i, me2); + for (let j = 0; j < 5; j++) ihvout[j] = (ihvin[j] + scratch[j]) | 0; +} + +/** + * Collision-detecting SHA-1. Drop-in for {@link Sha1}: `digest()` returns + * the identical bytes for every input. After digesting, {@link collision} + * reports whether any block looked like a collision-attack near-collision + * block. + */ +export class Sha1Dc { + private ihv = new Int32Array(5); + private block = new Uint8Array(64); + private blockLen = 0; + private bytes = 0; + /** expanded message of the block being compressed */ + private m1 = new Int32Array(80); + private m2 = new Int32Array(80); + /** register file entering steps 58 and 65 — the only DV test steps */ + private state58 = new Int32Array(5); + private state65 = new Int32Array(5); + private ihvin = new Int32Array(5); + private ihvout = new Int32Array(5); + private scratch = new Int32Array(5); + private found = false; + + constructor() { + this.reset(); + } + + /** True when a near-collision block was seen since the last reset. */ + get collision(): boolean { + return this.found; + } + + reset(): this { + this.ihv[0] = 0x67452301 | 0; + this.ihv[1] = 0xefcdab89 | 0; + this.ihv[2] = 0x98badcfe | 0; + this.ihv[3] = 0x10325476 | 0; + this.ihv[4] = 0xc3d2e1f0 | 0; + this.blockLen = 0; + this.bytes = 0; + this.found = false; + return this; + } + + update(data: Uint8Array): this { + this.bytes += data.length; + let off = 0; + if (this.blockLen > 0) { + const need = 64 - this.blockLen; + const take = Math.min(need, data.length); + this.block.set(data.subarray(0, take), this.blockLen); + this.blockLen += take; + off = take; + if (this.blockLen === 64) { + this.process(this.block, 0); + this.blockLen = 0; + } + } + while (off + 64 <= data.length) { + this.process(data, off); + off += 64; + } + if (off < data.length) { + this.block.set(data.subarray(off), 0); + this.blockLen = data.length - off; + } + return this; + } + + digest(): Uint8Array { + const bitLenHi = Math.floor((this.bytes * 8) / 0x100000000); + const bitLenLo = (this.bytes * 8) >>> 0; + const pad = new Uint8Array(((this.blockLen < 56 ? 56 : 120) - this.blockLen) + 8); + pad[0] = 0x80; + const dv = new DataView(pad.buffer); + dv.setUint32(pad.length - 8, bitLenHi); + dv.setUint32(pad.length - 4, bitLenLo); + this.update(pad); + const out = new Uint8Array(20); + const ov = new DataView(out.buffer); + for (let i = 0; i < 5; i++) ov.setInt32(i * 4, this.ihv[i]); + return out; + } + + /** Compress one block, retaining what the collision check needs. */ + private process(buf: Uint8Array, off: number): void { + const w = this.m1; + for (let i = 0; i < 16; i++) { + const j = off + i * 4; + w[i] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3]; + } + for (let i = 16; i < 80; i++) { + const n = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + w[i] = (n << 1) | (n >>> 31); + } + const ihv = this.ihv; + let a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4]; + for (let i = 0; i < 80; i++) { + // The unrolled reference names registers canonically while this loop + // shifts them, so a snapshot at step i must be rotated back by i mod 5. + if (i === 58) { + // 58 mod 5 == 3 + this.state58[0] = d; this.state58[1] = e; this.state58[2] = a; + this.state58[3] = b; this.state58[4] = c; + } else if (i === 65) { + // 65 mod 5 == 0 + this.state65[0] = a; this.state65[1] = b; this.state65[2] = c; + this.state65[3] = d; this.state65[4] = e; + } + let f: number, k: number; + if (i < 20) { f = (b & c) | (~b & d); k = K0; } + else if (i < 40) { f = b ^ c ^ d; k = K1; } + else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = K2; } + else { f = b ^ c ^ d; k = K3; } + const t = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0; + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + ihv[0] = (ihv[0] + a) | 0; + ihv[1] = (ihv[1] + b) | 0; + ihv[2] = (ihv[2] + c) | 0; + ihv[3] = (ihv[3] + d) | 0; + ihv[4] = (ihv[4] + e) | 0; + + if (this.found) return; // already refused; skip the rest of the work + const mask = ubcCheck(w); + if (mask === 0) return; + const m2 = this.m2; + for (const dv of DVS) { + if ((mask & (1 << dv.maskb)) === 0) continue; + const dm = dv.dm; + for (let j = 0; j < 80; j++) m2[j] = w[j] ^ dm[j]; + recompress( + dv.testt, + this.ihvin, + this.ihvout, + m2, + dv.testt === 58 ? this.state58 : this.state65, + this.scratch + ); + const o = this.ihvout; + if (((o[0] ^ ihv[0]) | (o[1] ^ ihv[1]) | (o[2] ^ ihv[2]) | (o[3] ^ ihv[3]) | (o[4] ^ ihv[4])) === 0) { + this.found = true; + return; + } + } + } +} + +/** Thrown when a hashed object carries a SHA-1 collision-attack block. */ +export class Sha1CollisionError extends Error { + readonly oid: string; + constructor(oid: string) { + super(`object ${oid.slice(0, 12)} triggered SHA-1 collision detection; refused`); + this.name = "Sha1CollisionError"; + this.oid = oid; + } +} diff --git a/apps/api/src/vendor/dgit/git/sha1dc-tables.ts b/apps/api/src/vendor/dgit/git/sha1dc-tables.ts new file mode 100644 index 0000000000..20a2161ff7 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/sha1dc-tables.ts @@ -0,0 +1,324 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +// GENERATED — do not edit by hand. +// Transcribed from sha1collisiondetection/lib/ubc_check.c (Marc Stevens, Dan +// Shumow; MIT). Regenerate with scripts/gen-sha1dc-tables.mjs. +// +// C uint32 arithmetic maps onto JS int32 bit-for-bit: '>>' becomes '>>>' and +// wrapping subtraction is left to two's-complement, since every result feeds a +// bitwise operator. + +/** One disturbance vector: the step to recompress from, its bit in the UBC + * mask, and the expanded-message XOR difference. */ +export interface Sha1Dv { + readonly testt: number; + readonly maskb: number; + readonly dm: readonly number[]; +} + +/** The 32 disturbance vectors checked by SHA-1DC. */ +export const SHA1_DVS: readonly Sha1Dv[] = [ + { testt: 58, maskb: 0, dm: [0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161,0x80000599] }, // I(43,0) + { testt: 58, maskb: 1, dm: [0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161] }, // I(44,0) + { testt: 58, maskb: 2, dm: [0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803] }, // I(45,0) + { testt: 58, maskb: 3, dm: [0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c] }, // I(46,0) + { testt: 58, maskb: 4, dm: [0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a,0x00000132] }, // I(46,2) + { testt: 58, maskb: 5, dm: [0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6] }, // I(47,0) + { testt: 58, maskb: 6, dm: [0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a] }, // I(47,2) + { testt: 58, maskb: 7, dm: [0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408] }, // I(48,0) + { testt: 58, maskb: 8, dm: [0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020] }, // I(48,2) + { testt: 58, maskb: 9, dm: [0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164] }, // I(49,0) + { testt: 58, maskb: 10, dm: [0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590] }, // I(49,2) + { testt: 65, maskb: 11, dm: [0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018] }, // I(50,0) + { testt: 65, maskb: 12, dm: [0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060] }, // I(50,2) + { testt: 65, maskb: 13, dm: [0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202] }, // I(51,0) + { testt: 65, maskb: 14, dm: [0xa0000003,0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a] }, // I(51,2) + { testt: 65, maskb: 15, dm: [0x04000010,0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012] }, // I(52,0) + { testt: 58, maskb: 16, dm: [0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054,0x00000967] }, // II(45,0) + { testt: 58, maskb: 17, dm: [0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054] }, // II(46,0) + { testt: 58, maskb: 18, dm: [0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6,0x0000106a,0x00000b90,0x00000152] }, // II(46,2) + { testt: 58, maskb: 19, dm: [0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4] }, // II(47,0) + { testt: 58, maskb: 20, dm: [0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a] }, // II(48,0) + { testt: 58, maskb: 21, dm: [0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d] }, // II(49,0) + { testt: 58, maskb: 22, dm: [0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6] }, // II(49,2) + { testt: 65, maskb: 23, dm: [0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b] }, // II(50,0) + { testt: 65, maskb: 24, dm: [0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c] }, // II(50,2) + { testt: 65, maskb: 25, dm: [0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b] }, // II(51,0) + { testt: 65, maskb: 26, dm: [0x00000043,0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e] }, // II(51,2) + { testt: 65, maskb: 27, dm: [0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014] }, // II(52,0) + { testt: 65, maskb: 28, dm: [0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089] }, // II(53,0) + { testt: 65, maskb: 29, dm: [0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107] }, // II(54,0) + { testt: 65, maskb: 30, dm: [0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b] }, // II(55,0) + { testt: 65, maskb: 31, dm: [0x2600001a,0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046] }, // II(56,0) +]; + +/** + * Check the unavoidable bit conditions for every DV against an expanded + * message block. Returns a mask whose bit `maskb` is set when every UBC for + * that DV holds, i.e. when the DV is worth the cost of a recompression check. + */ +export function ubcCheck(W: Int32Array): number { + let mask = ~0; + + + mask &= (((((W[44]^W[45])>>>29)&1)-1) | ~((1 << 7)|(1 << 13)|(1 << 15)|(1 << 16)|(1 << 17)|(1 << 23)|(1 << 25))); + mask &= (((((W[49]^W[50])>>>29)&1)-1) | ~((1 << 3)|(1 << 16)|(1 << 23)|(1 << 25)|(1 << 30)|(1 << 31))); + mask &= (((((W[48]^W[49])>>>29)&1)-1) | ~((1 << 2)|(1 << 15)|(1 << 21)|(1 << 23)|(1 << 29)|(1 << 30))); + mask &= ((((W[47]^(W[50]>>>25))&(1<<4))-(1<<4)) | ~((1 << 5)|(1 << 9)|(1 << 13)|(1 << 16)|(1 << 25)|(1 << 31))); + mask &= (((((W[47]^W[48])>>>29)&1)-1) | ~((1 << 1)|(1 << 13)|(1 << 20)|(1 << 21)|(1 << 28)|(1 << 29))); + mask &= (((((W[46]>>>4)^(W[49]>>>29))&1)-1) | ~((1 << 3)|(1 << 7)|(1 << 11)|(1 << 15)|(1 << 23)|(1 << 30))); + mask &= (((((W[46]^W[47])>>>29)&1)-1) | ~((1 << 0)|(1 << 11)|(1 << 19)|(1 << 20)|(1 << 27)|(1 << 28))); + mask &= (((((W[45]>>>4)^(W[48]>>>29))&1)-1) | ~((1 << 2)|(1 << 5)|(1 << 9)|(1 << 13)|(1 << 21)|(1 << 29))); + mask &= (((((W[45]^W[46])>>>29)&1)-1) | ~((1 << 9)|(1 << 15)|(1 << 17)|(1 << 19)|(1 << 25)|(1 << 27))); + mask &= (((((W[44]>>>4)^(W[47]>>>29))&1)-1) | ~((1 << 1)|(1 << 3)|(1 << 7)|(1 << 11)|(1 << 20)|(1 << 28))); + mask &= (((((W[43]>>>4)^(W[46]>>>29))&1)-1) | ~((1 << 0)|(1 << 2)|(1 << 5)|(1 << 9)|(1 << 19)|(1 << 27))); + mask &= (((((W[43]^W[44])>>>29)&1)-1) | ~((1 << 5)|(1 << 11)|(1 << 13)|(1 << 16)|(1 << 21)|(1 << 23))); + mask &= (((((W[42]>>>4)^(W[45]>>>29))&1)-1) | ~((1 << 1)|(1 << 3)|(1 << 7)|(1 << 15)|(1 << 17)|(1 << 25))); + mask &= (((((W[41]>>>4)^(W[44]>>>29))&1)-1) | ~((1 << 0)|(1 << 2)|(1 << 5)|(1 << 13)|(1 << 16)|(1 << 23))); + mask &= (((((W[40]^W[41])>>>29)&1)-1) | ~((1 << 1)|(1 << 5)|(1 << 7)|(1 << 17)|(1 << 19)|(1 << 31))); + mask &= (((((W[54]^W[55])>>>29)&1)-1) | ~((1 << 13)|(1 << 19)|(1 << 23)|(1 << 30)|(1 << 31))); + mask &= (((((W[53]^W[54])>>>29)&1)-1) | ~((1 << 11)|(1 << 17)|(1 << 21)|(1 << 29)|(1 << 30))); + mask &= (((((W[52]^W[53])>>>29)&1)-1) | ~((1 << 9)|(1 << 16)|(1 << 20)|(1 << 28)|(1 << 29))); + mask &= ((((W[50]^(W[53]>>>25))&(1<<4))-(1<<4)) | ~((1 << 11)|(1 << 15)|(1 << 17)|(1 << 20)|(1 << 29))); + mask &= (((((W[50]^W[51])>>>29)&1)-1) | ~((1 << 5)|(1 << 17)|(1 << 25)|(1 << 27)|(1 << 31))); + mask &= ((((W[49]^(W[52]>>>25))&(1<<4))-(1<<4)) | ~((1 << 9)|(1 << 13)|(1 << 16)|(1 << 19)|(1 << 28))); + mask &= ((((W[48]^(W[51]>>>25))&(1<<4))-(1<<4)) | ~((1 << 7)|(1 << 11)|(1 << 15)|(1 << 17)|(1 << 27))); + mask &= (((((W[42]^W[43])>>>29)&1)-1) | ~((1 << 3)|(1 << 9)|(1 << 11)|(1 << 20)|(1 << 21))); + mask &= (((((W[41]^W[42])>>>29)&1)-1) | ~((1 << 2)|(1 << 7)|(1 << 9)|(1 << 19)|(1 << 20))); + mask &= (((((W[40]>>>4)^(W[43]>>>29))&1)-1) | ~((1 << 1)|(1 << 3)|(1 << 11)|(1 << 21)|(1 << 31))); + mask &= (((((W[39]>>>4)^(W[42]>>>29))&1)-1) | ~((1 << 0)|(1 << 2)|(1 << 9)|(1 << 20)|(1 << 30))); + if (mask & ((1 << 1)|(1 << 7)|(1 << 19)|(1 << 29)|(1 << 31))) + mask &= (((((W[38]>>>4)^(W[41]>>>29))&1)-1) | ~((1 << 1)|(1 << 7)|(1 << 19)|(1 << 29)|(1 << 31))); + mask &= (((((W[37]>>>4)^(W[40]>>>29))&1)-1) | ~((1 << 0)|(1 << 5)|(1 << 17)|(1 << 28)|(1 << 30))); + if (mask & ((1 << 15)|(1 << 20)|(1 << 25)|(1 << 31))) + mask &= (((((W[55]^W[56])>>>29)&1)-1) | ~((1 << 15)|(1 << 20)|(1 << 25)|(1 << 31))); + if (mask & ((1 << 15)|(1 << 20)|(1 << 23)|(1 << 31))) + mask &= ((((W[52]^(W[55]>>>25))&(1<<4))-(1<<4)) | ~((1 << 15)|(1 << 20)|(1 << 23)|(1 << 31))); + if (mask & ((1 << 13)|(1 << 19)|(1 << 21)|(1 << 30))) + mask &= ((((W[51]^(W[54]>>>25))&(1<<4))-(1<<4)) | ~((1 << 13)|(1 << 19)|(1 << 21)|(1 << 30))); + if (mask & ((1 << 7)|(1 << 19)|(1 << 27)|(1 << 28))) + mask &= (((((W[51]^W[52])>>>29)&1)-1) | ~((1 << 7)|(1 << 19)|(1 << 27)|(1 << 28))); + if (mask & ((1 << 3)|(1 << 9)|(1 << 16)|(1 << 20))) + mask &= (((((W[36]>>>4)^(W[40]>>>29))&1)-1) | ~((1 << 3)|(1 << 9)|(1 << 16)|(1 << 20))); + if (mask & ((1 << 15)|(1 << 20)|(1 << 21))) + mask &= ((0-(((W[53]^W[56])>>>29)&1)) | ~((1 << 15)|(1 << 20)|(1 << 21))); + if (mask & ((1 << 11)|(1 << 17)|(1 << 19))) + mask &= ((0-(((W[51]^W[54])>>>29)&1)) | ~((1 << 11)|(1 << 17)|(1 << 19))); + if (mask & ((1 << 9)|(1 << 13)|(1 << 16))) + mask &= ((0-(((W[50]^W[52])>>>29)&1)) | ~((1 << 9)|(1 << 13)|(1 << 16))); + if (mask & ((1 << 7)|(1 << 11)|(1 << 15))) + mask &= ((0-(((W[49]^W[51])>>>29)&1)) | ~((1 << 7)|(1 << 11)|(1 << 15))); + if (mask & ((1 << 5)|(1 << 9)|(1 << 13))) + mask &= ((0-(((W[48]^W[50])>>>29)&1)) | ~((1 << 5)|(1 << 9)|(1 << 13))); + if (mask & ((1 << 3)|(1 << 7)|(1 << 11))) + mask &= ((0-(((W[47]^W[49])>>>29)&1)) | ~((1 << 3)|(1 << 7)|(1 << 11))); + if (mask & ((1 << 2)|(1 << 5)|(1 << 9))) + mask &= ((0-(((W[46]^W[48])>>>29)&1)) | ~((1 << 2)|(1 << 5)|(1 << 9))); + mask &= ((((W[45]^W[47])&(1<<6))-(1<<6)) | ~((1 << 6)|(1 << 10)|(1 << 14))); + if (mask & ((1 << 1)|(1 << 3)|(1 << 7))) + mask &= ((0-(((W[45]^W[47])>>>29)&1)) | ~((1 << 1)|(1 << 3)|(1 << 7))); + mask &= (((((W[44]^W[46])>>>6)&1)-1) | ~((1 << 4)|(1 << 8)|(1 << 12))); + if (mask & ((1 << 0)|(1 << 2)|(1 << 5))) + mask &= ((0-(((W[44]^W[46])>>>29)&1)) | ~((1 << 0)|(1 << 2)|(1 << 5))); + mask &= ((0-((W[41]^(W[42]>>>5))&(1<<1))) | ~((1 << 8)|(1 << 18)|(1 << 26))); + mask &= ((0-((W[40]^(W[41]>>>5))&(1<<1))) | ~((1 << 6)|(1 << 14)|(1 << 24))); + if (mask & ((1 << 1)|(1 << 3)|(1 << 31))) + mask &= ((0-(((W[40]^W[42])>>>4)&1)) | ~((1 << 1)|(1 << 3)|(1 << 31))); + mask &= ((0-((W[39]^(W[40]>>>5))&(1<<1))) | ~((1 << 4)|(1 << 12)|(1 << 22))); + if (mask & ((1 << 0)|(1 << 2)|(1 << 30))) + mask &= ((0-(((W[39]^W[41])>>>4)&1)) | ~((1 << 0)|(1 << 2)|(1 << 30))); + if (mask & ((1 << 1)|(1 << 29)|(1 << 31))) + mask &= ((0-(((W[38]^W[40])>>>4)&1)) | ~((1 << 1)|(1 << 29)|(1 << 31))); + if (mask & ((1 << 0)|(1 << 28)|(1 << 30))) + mask &= ((0-(((W[37]^W[39])>>>4)&1)) | ~((1 << 0)|(1 << 28)|(1 << 30))); + mask &= ((0-((W[36]^(W[37]>>>5))&(1<<1))) | ~((1 << 6)|(1 << 12)|(1 << 18))); + if (mask & ((1 << 2)|(1 << 7)|(1 << 19))) + mask &= (((((W[35]>>>4)^(W[39]>>>29))&1)-1) | ~((1 << 2)|(1 << 7)|(1 << 19))); + if (mask & ((1 << 7)|(1 << 20))) + mask &= ((0-((W[63]^(W[64]>>>5))&(1<<0))) | ~((1 << 7)|(1 << 20))); + if (mask & ((1 << 2)|(1 << 16))) + mask &= ((0-((W[63]^(W[64]>>>5))&(1<<1))) | ~((1 << 2)|(1 << 16))); + if (mask & ((1 << 5)|(1 << 19))) + mask &= ((0-((W[62]^(W[63]>>>5))&(1<<0))) | ~((1 << 5)|(1 << 19))); + if (mask & ((1 << 3)|(1 << 17))) + mask &= ((0-((W[61]^(W[62]>>>5))&(1<<0))) | ~((1 << 3)|(1 << 17))); + mask &= ((0-((W[61]^(W[62]>>>5))&(1<<2))) | ~((1 << 4)|(1 << 18))); + if (mask & ((1 << 2)|(1 << 16))) + mask &= ((0-((W[60]^(W[61]>>>5))&(1<<0))) | ~((1 << 2)|(1 << 16))); + if (mask & ((1 << 25)|(1 << 29))) + mask &= (((((W[58]^W[59])>>>29)&1)-1) | ~((1 << 25)|(1 << 29))); + if (mask & ((1 << 23)|(1 << 28))) + mask &= (((((W[57]^W[58])>>>29)&1)-1) | ~((1 << 23)|(1 << 28))); + if (mask & ((1 << 27)|(1 << 29))) + mask &= ((((W[56]^(W[59]>>>25))&(1<<4))-(1<<4)) | ~((1 << 27)|(1 << 29))); + if (mask & ((1 << 25)|(1 << 27))) + mask &= ((0-(((W[56]^W[59])>>>29)&1)) | ~((1 << 25)|(1 << 27))); + if (mask & ((1 << 21)|(1 << 27))) + mask &= (((((W[56]^W[57])>>>29)&1)-1) | ~((1 << 21)|(1 << 27))); + if (mask & ((1 << 25)|(1 << 28))) + mask &= ((((W[55]^(W[58]>>>25))&(1<<4))-(1<<4)) | ~((1 << 25)|(1 << 28))); + if (mask & ((1 << 23)|(1 << 27))) + mask &= ((((W[54]^(W[57]>>>25))&(1<<4))-(1<<4)) | ~((1 << 23)|(1 << 27))); + if (mask & ((1 << 21)|(1 << 25))) + mask &= ((((W[53]^(W[56]>>>25))&(1<<4))-(1<<4)) | ~((1 << 21)|(1 << 25))); + mask &= ((((W[51]^(W[50]>>>5))&(1<<1))-(1<<1)) | ~((1 << 12)|(1 << 18))); + mask &= ((((W[48]^W[50])&(1<<6))-(1<<6)) | ~((1 << 12)|(1 << 18))); + if (mask & ((1 << 13)|(1 << 15))) + mask &= ((0-(((W[48]^W[55])>>>29)&1)) | ~((1 << 13)|(1 << 15))); + mask &= ((((W[47]^W[49])&(1<<6))-(1<<6)) | ~((1 << 10)|(1 << 14))); + mask &= ((((W[48]^(W[47]>>>5))&(1<<1))-(1<<1)) | ~((1 << 6)|(1 << 26))); + mask &= ((((W[46]^W[48])&(1<<6))-(1<<6)) | ~((1 << 8)|(1 << 12))); + mask &= ((((W[47]^(W[46]>>>5))&(1<<1))-(1<<1)) | ~((1 << 4)|(1 << 24))); + mask &= ((0-((W[44]^(W[45]>>>5))&(1<<1))) | ~((1 << 14)|(1 << 22))); + mask &= ((((W[43]^W[45])&(1<<6))-(1<<6)) | ~((1 << 6)|(1 << 10))); + mask &= (((((W[42]^W[44])>>>6)&1)-1) | ~((1 << 4)|(1 << 8))); + mask &= ((((W[43]^(W[42]>>>5))&(1<<1))-(1<<1)) | ~((1 << 18)|(1 << 26))); + mask &= ((((W[42]^(W[41]>>>5))&(1<<1))-(1<<1)) | ~((1 << 14)|(1 << 24))); + mask &= ((((W[41]^(W[40]>>>5))&(1<<1))-(1<<1)) | ~((1 << 12)|(1 << 22))); + if (mask & ((1 << 15)|(1 << 25))) + mask &= ((((W[39]^(W[43]>>>25))&(1<<4))-(1<<4)) | ~((1 << 15)|(1 << 25))); + if (mask & ((1 << 13)|(1 << 23))) + mask &= ((((W[38]^(W[42]>>>25))&(1<<4))-(1<<4)) | ~((1 << 13)|(1 << 23))); + if (mask & ((1 << 8)|(1 << 14))) + mask &= ((0-((W[37]^(W[38]>>>5))&(1<<1))) | ~((1 << 8)|(1 << 14))); + if (mask & ((1 << 11)|(1 << 21))) + mask &= ((((W[37]^(W[41]>>>25))&(1<<4))-(1<<4)) | ~((1 << 11)|(1 << 21))); + if (mask & ((1 << 27)|(1 << 29))) + mask &= ((0-((W[36]^W[38])&(1<<4))) | ~((1 << 27)|(1 << 29))); + mask &= ((0-((W[35]^(W[36]>>>5))&(1<<1))) | ~((1 << 4)|(1 << 10))); + if (mask & ((1 << 13)|(1 << 19))) + mask &= ((((W[35]^(W[39]>>>25))&(1<<3))-(1<<3)) | ~((1 << 13)|(1 << 19))); +if (mask) { + + if (mask & (1 << 0)) + if ( + !((W[61]^(W[62]>>>5)) & (1<<1)) + || !(!((W[59]^(W[63]>>>25)) & (1<<5))) + || !((W[58]^(W[63]>>>30)) & (1<<0)) + ) mask &= ~(1 << 0); + if (mask & (1 << 1)) + if ( + !((W[62]^(W[63]>>>5)) & (1<<1)) + || !(!((W[60]^(W[64]>>>25)) & (1<<5))) + || !((W[59]^(W[64]>>>30)) & (1<<0)) + ) mask &= ~(1 << 1); + if (mask & (1 << 4)) + mask &= ((~((W[40]^W[42])>>>2)) | ~(1 << 4)); + if (mask & (1 << 6)) + if ( + !((W[62]^(W[63]>>>5)) & (1<<2)) + || !(!((W[41]^W[43]) & (1<<6))) + ) mask &= ~(1 << 6); + if (mask & (1 << 8)) + if ( + !((W[63]^(W[64]>>>5)) & (1<<2)) + || !(!((W[48]^(W[49]<<5)) & (1<<6))) + ) mask &= ~(1 << 8); + if (mask & (1 << 10)) + if ( + !(!((W[49]^(W[50]<<5)) & (1<<6))) + || !((W[42]^W[50]) & (1<<1)) + || !(!((W[39]^(W[40]<<5)) & (1<<6))) + || !((W[38]^W[40]) & (1<<1)) + ) mask &= ~(1 << 10); + if (mask & (1 << 11)) + mask &= ((((W[36]^W[37])<<7)) | ~(1 << 11)); + if (mask & (1 << 12)) + mask &= ((((W[43]^W[51])<<11)) | ~(1 << 12)); + if (mask & (1 << 13)) + mask &= ((((W[37]^W[38])<<9)) | ~(1 << 13)); + if (mask & (1 << 14)) + if ( + !(!((W[51]^(W[52]<<5)) & (1<<6))) + || !(!((W[49]^W[51]) & (1<<6))) + || !(!((W[37]^(W[37]>>>5)) & (1<<1))) + || !(!((W[35]^(W[39]>>>25)) & (1<<5))) + ) mask &= ~(1 << 14); + if (mask & (1 << 15)) + mask &= ((((W[38]^W[39])<<11)) | ~(1 << 15)); + if (mask & (1 << 18)) + mask &= ((((W[47]^W[51])<<17)) | ~(1 << 18)); + if (mask & (1 << 20)) + if ( + !(!((W[36]^(W[40]>>>25)) & (1<<3))) + || !((W[35]^(W[40]<<2)) & (1<<30)) + ) mask &= ~(1 << 20); + if (mask & (1 << 21)) + if ( + !(!((W[37]^(W[41]>>>25)) & (1<<3))) + || !((W[36]^(W[41]<<2)) & (1<<30)) + ) mask &= ~(1 << 21); + if (mask & (1 << 22)) + if ( + !(!((W[53]^(W[54]<<5)) & (1<<6))) + || !(!((W[51]^W[53]) & (1<<6))) + || !((W[50]^W[54]) & (1<<1)) + || !(!((W[45]^(W[46]<<5)) & (1<<6))) + || !(!((W[37]^(W[41]>>>25)) & (1<<5))) + || !((W[36]^(W[41]>>>30)) & (1<<0)) + ) mask &= ~(1 << 22); + if (mask & (1 << 23)) + if ( + !((W[55]^W[58]) & (1<<29)) + || !(!((W[38]^(W[42]>>>25)) & (1<<3))) + || !((W[37]^(W[42]<<2)) & (1<<30)) + ) mask &= ~(1 << 23); + if (mask & (1 << 24)) + if ( + !(!((W[54]^(W[55]<<5)) & (1<<6))) + || !(!((W[52]^W[54]) & (1<<6))) + || !((W[51]^W[55]) & (1<<1)) + || !((W[45]^W[47]) & (1<<1)) + || !(!((W[38]^(W[42]>>>25)) & (1<<5))) + || !((W[37]^(W[42]>>>30)) & (1<<0)) + ) mask &= ~(1 << 24); + if (mask & (1 << 25)) + if ( + !(!((W[39]^(W[43]>>>25)) & (1<<3))) + || !((W[38]^(W[43]<<2)) & (1<<30)) + ) mask &= ~(1 << 25); + if (mask & (1 << 26)) + if ( + !(!((W[55]^(W[56]<<5)) & (1<<6))) + || !(!((W[53]^W[55]) & (1<<6))) + || !((W[52]^W[56]) & (1<<1)) + || !((W[46]^W[48]) & (1<<1)) + || !(!((W[39]^(W[43]>>>25)) & (1<<5))) + || !((W[38]^(W[43]>>>30)) & (1<<0)) + ) mask &= ~(1 << 26); + if (mask & (1 << 27)) + if ( + !(!((W[59]^W[60]) & (1<<29))) + || !(!((W[40]^(W[44]>>>25)) & (1<<3))) + || !(!((W[40]^(W[44]>>>25)) & (1<<4))) + || !((W[39]^(W[44]<<2)) & (1<<30)) + ) mask &= ~(1 << 27); + if (mask & (1 << 28)) + if ( + !((W[58]^W[61]) & (1<<29)) + || !(!((W[57]^(W[61]>>>25)) & (1<<4))) + || !(!((W[41]^(W[45]>>>25)) & (1<<3))) + || !(!((W[41]^(W[45]>>>25)) & (1<<4))) + ) mask &= ~(1 << 28); + if (mask & (1 << 29)) + if ( + !(!((W[58]^(W[62]>>>25)) & (1<<4))) + || !(!((W[42]^(W[46]>>>25)) & (1<<3))) + || !(!((W[42]^(W[46]>>>25)) & (1<<4))) + ) mask &= ~(1 << 29); + if (mask & (1 << 30)) + if ( + !(!((W[59]^(W[63]>>>25)) & (1<<4))) + || !(!((W[57]^(W[59]>>>25)) & (1<<4))) + || !(!((W[43]^(W[47]>>>25)) & (1<<3))) + || !(!((W[43]^(W[47]>>>25)) & (1<<4))) + ) mask &= ~(1 << 30); + if (mask & (1 << 31)) + if ( + !(!((W[60]^(W[64]>>>25)) & (1<<4))) + || !(!((W[44]^(W[48]>>>25)) & (1<<3))) + || !(!((W[44]^(W[48]>>>25)) & (1<<4))) + ) mask &= ~(1 << 31); +} + return mask; +} diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts new file mode 100644 index 0000000000..f7d2c3583a --- /dev/null +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -0,0 +1,491 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import { concat, te, sha1hex } from "./util"; +import { deflate, inflate } from "./zlib"; +import { ObjType } from "./objects"; +import { OidSet } from "./oidset"; +import { PackStore, ObjCache, ObjRec } from "./packstore"; + +/** A reachable pack entry, streamed in storage order by `reachablePackedAfter`. + * The `size` field of a full PackedEntry is not needed to emit the pack, so it + * is left unselected. */ +export interface PackedReachable { + oid: string; + packId: number; + offset: number; + dataOff: number; + dataLen: number; + type: ObjType; + entrySize: number; + baseOid: string | null; +} + +const CHUNK = 1024 * 1024; // stay well under the DO SQLite per-row limit +// serving cache: Workers isolates have a hard 128MB total, so stay modest +// there; self-hosted celld nodes run with multi-GB heaps +const CACHE_BUDGET = typeof caches !== "undefined" ? 16 * 1024 * 1024 : 128 * 1024 * 1024; + +/** + * Git object database + refs, stored in a Durable Object's SQLite database. + * Small/legacy objects live loose (zlib-deflated, chunked across rows); + * pushed packs are kept verbatim and served through the PackStore index. + */ +export class GitStore { + readonly packs: PackStore; + readonly cache = new ObjCache(CACHE_BUDGET); + /** + * Whether the loose `objects` table holds anything. A pushed repo is + * pack-native — loose objects only appear after a gc migration (see + * runGc) — so on the normal path this is false and every get/has/typeAndSize + * skips a guaranteed-miss loose SELECT and goes straight to the pack index. + * Cached in memory and mirrored to the `has-loose` meta row so it survives + * isolate eviction; back-filled once for repos that predate the flag. + */ + private hasLoose: boolean; + + constructor(private sql: SqlStorage) { + this.packs = new PackStore(sql, (oid) => this.getLoose(oid)); + sql.exec(` + CREATE TABLE IF NOT EXISTS objects ( + oid TEXT PRIMARY KEY, + type TEXT NOT NULL, + size INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS chunks ( + oid TEXT NOT NULL, + seq INTEGER NOT NULL, + data BLOB NOT NULL, + PRIMARY KEY (oid, seq) + ); + CREATE TABLE IF NOT EXISTS refs ( + name TEXT PRIMARY KEY, + target TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS reachable ( + oid TEXT PRIMARY KEY + ); + CREATE TABLE IF NOT EXISTS peeled ( + oid TEXT PRIMARY KEY, + target TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS stats_cache ( + tip_oid TEXT NOT NULL, + period TEXT NOT NULL, + data TEXT NOT NULL, + PRIMARY KEY (tip_oid, period) + ); + CREATE TABLE IF NOT EXISTS push_edges ( + child TEXT NOT NULL + ); + `); + const flag = this.getMeta("has-loose"); + if (flag === null) { + // back-fill: a repo migrated by an older build may already hold loose + // objects with no flag set — probe once and record the answer + const any = this.sql.exec("SELECT 1 FROM objects LIMIT 1").toArray().length > 0; + this.setMeta("has-loose", any ? "1" : "0"); + this.hasLoose = any; + } else { + this.hasLoose = flag === "1"; + } + } + + has(oid: string): boolean { + if (this.hasLoose && this.sql.exec("SELECT 1 FROM objects WHERE oid = ?", oid).toArray().length > 0) return true; + return this.packs.typeAndSize(oid) !== null; + } + + typeAndSize(oid: string): { type: ObjType; size: number } | null { + if (this.hasLoose) { + const rows = this.sql + .exec<{ type: ObjType; size: number }>("SELECT type, size FROM objects WHERE oid = ?", oid) + .toArray(); + if (rows[0]) return rows[0]; + } + return this.packs.typeAndSize(oid); + } + + private getLoose(oid: string): ObjRec | null { + if (!this.hasLoose) return null; + const rows = this.sql + .exec<{ type: ObjType; size: number }>("SELECT type, size FROM objects WHERE oid = ?", oid) + .toArray(); + if (!rows.length) return null; + const chunks = this.sql + .exec<{ data: ArrayBuffer }>("SELECT data FROM chunks WHERE oid = ? ORDER BY seq", oid) + .toArray(); + const packed = concat(chunks.map((r) => new Uint8Array(r.data))); + return { type: rows[0].type, data: inflate(packed) }; + } + + async get(oid: string): Promise<{ type: ObjType; data: Uint8Array } | null> { + return this.getLoose(oid) ?? (await this.packs.getObject(oid, this.cache)); + } + + /** + * Bind (or clear) the R2 raw-pack backend for this repo. Absent binding keeps + * every pack in SQLite (celld / Workers without the binding). Idempotent and + * cheap: the DO is per-repo, so this is set on each request from the repo name. + */ + setR2(bucket: R2Bucket | undefined, repo: string): void { + this.packs.setR2(bucket, repo); + } + + put(oid: string, type: ObjType, data: Uint8Array): void { + if (this.sql.exec("SELECT 1 FROM objects WHERE oid = ?", oid).toArray().length > 0) return; + const packed = deflate(data); + this.sql.exec("INSERT INTO objects (oid, type, size) VALUES (?, ?, ?)", oid, type, data.length); + for (let seq = 0, off = 0; off < packed.length || seq === 0; seq++, off += CHUNK) { + const slice = packed.slice(off, off + CHUNK); + this.sql.exec("INSERT INTO chunks (oid, seq, data) VALUES (?, ?, ?)", oid, seq, slice.buffer); + } + // the repo now has at least one loose object (gc migration path): the + // loose probe can no longer be skipped + if (!this.hasLoose) { + this.hasLoose = true; + this.setMeta("has-loose", "1"); + } + } + + objectCount(): number { + return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM objects").one().n + this.packs.countObjects(); + } + + // --- push connectivity --------------------------------------------------- + // Connectivity of a fresh push is checked in SQL, not by an in-memory graph + // walk: the pushed pack must be complete, i.e. every object it introduces + // must have its referenced children in `pack_objects` ∪ `objects`. Children + // are staged into `push_edges` in bounded batches and each batch is + // anti-joined against the stores, so the check costs O(batch) rows of scratch + // rather than an OidSet that scales with the object count. + + /** A page of a pack's non-blob oids after `after` (keyset, so the scan holds + * one page, never the whole pack). Empty array ends the walk. */ + packNonBlobOidsAfter(packId: number, after: string, limit: number): string[] { + return this.sql + .exec<{ oid: string }>( + "SELECT oid FROM pack_objects WHERE pack_id = ? AND type != 'blob' AND oid > ? ORDER BY oid LIMIT ?", + packId, + after, + limit, + ) + .toArray() + .map((r) => r.oid); + } + + resetPushEdges(): void { + this.sql.exec("DELETE FROM push_edges"); + } + + /** Stage referenced child oids, chunked under the DO's ~100 bound-variable + * statement cap. */ + addPushEdges(children: string[]): void { + for (let i = 0; i < children.length; i += 64) { + const batch = children.slice(i, i + 64); + const values = batch.map(() => "(?)").join(","); + this.sql.exec(`INSERT INTO push_edges (child) VALUES ${values}`, ...batch); + } + } + + /** The first staged child absent from both stores, or null when every staged + * child is present. SQLite runs the membership test over its own indexes, so + * no oid set is built in the isolate. */ + firstMissingPushEdge(): string | null { + const rows = this.sql + .exec<{ child: string }>( + `SELECT e.child FROM push_edges e + WHERE NOT EXISTS (SELECT 1 FROM pack_objects p WHERE p.oid = e.child) + AND NOT EXISTS (SELECT 1 FROM objects o WHERE o.oid = e.child) + LIMIT 1`, + ) + .toArray(); + return rows.length ? rows[0].child : null; + } + + /** Resolve an abbreviated oid; null if unknown or ambiguous. */ + findOid(prefix: string): string | null { + if (!/^[0-9a-f]{4,40}$/.test(prefix)) return null; + const loose = this.hasLoose + ? this.sql + .exec<{ oid: string }>("SELECT oid FROM objects WHERE oid LIKE ? LIMIT 2", prefix + "%") + .toArray() + .map((r) => r.oid) + : []; + const all = [...new Set([...loose, ...this.packs.findOidPrefix(prefix)])]; + return all.length === 1 ? all[0] : null; + } + + allOids(): string[] { + return this.sql.exec<{ oid: string }>("SELECT oid FROM objects").toArray().map((r) => r.oid); + } + + deleteObject(oid: string): void { + this.sql.exec("DELETE FROM objects WHERE oid = ?", oid); + this.sql.exec("DELETE FROM chunks WHERE oid = ?", oid); + } + + dbSize(): number { + return this.sql.databaseSize; + } + + wipe(): void { + for (const t of ["objects", "chunks", "refs", "meta", "reachable", "peeled", "stats_cache"]) { + this.sql.exec(`DROP TABLE IF EXISTS ${t}`); + } + this.packs.wipe(); + // meta (with the flag) is gone; a fresh empty repo has no loose objects + this.hasLoose = false; + } + + + /** All refs except HEAD, sorted by name. */ + refs(): { name: string; target: string }[] { + return this.sql + .exec<{ name: string; target: string }>( + "SELECT name, target FROM refs WHERE name != 'HEAD' ORDER BY name" + ) + .toArray(); + } + + getRef(name: string): string | null { + const rows = this.sql + .exec<{ target: string }>("SELECT target FROM refs WHERE name = ?", name) + .toArray(); + return rows[0]?.target ?? null; + } + + setRef(name: string, target: string): void { + this.sql.exec( + "INSERT INTO refs (name, target) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET target = excluded.target", + name, + target + ); + } + + delRef(name: string): void { + this.sql.exec("DELETE FROM refs WHERE name = ?", name); + } + + /** HEAD symref target, e.g. "refs/heads/main". */ + head(): string { + const raw = this.getRef("HEAD"); + if (raw?.startsWith("ref: ")) return raw.slice(5); + return raw ?? "refs/heads/main"; + } + + setHead(refName: string): void { + this.setRef("HEAD", `ref: ${refName}`); + } + + /** Resolve HEAD to an oid, or null for an empty/unborn repo. */ + resolveHead(): string | null { + return this.getRef(this.head()); + } + + + getMeta(key: string): string | null { + const rows = this.sql + .exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key) + .toArray(); + return rows[0]?.value ?? null; + } + + setMeta(key: string, value: string): void { + this.sql.exec( + "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + key, + value + ); + } + + /** + * Cached peel target for an oid (tag -> ... -> commit). Tag oids are + * content-addressed and immutable, so a hit never needs a version check. + */ + getPeeled(oid: string): string | null { + const rows = this.sql.exec<{ target: string }>("SELECT target FROM peeled WHERE oid = ?", oid).toArray(); + return rows[0]?.target ?? null; + } + + setPeeled(oid: string, target: string): void { + this.sql.exec("INSERT OR IGNORE INTO peeled (oid, target) VALUES (?, ?)", oid, target); + } + + /** + * Cached commit-activity aggregation for a (tip commit oid, period) pair. + * Keyed on the tip's oid rather than a ref name: history under a fixed + * commit oid is immutable, so no version check is needed for a hit. + */ + getStatsCache(tipOid: string, period: string): string | null { + const rows = this.sql + .exec<{ data: string }>("SELECT data FROM stats_cache WHERE tip_oid = ? AND period = ?", tipOid, period) + .toArray(); + return rows[0]?.data ?? null; + } + + setStatsCache(tipOid: string, period: string, data: string): void { + this.sql.exec( + "INSERT OR REPLACE INTO stats_cache (tip_oid, period, data) VALUES (?, ?, ?)", + tipOid, + period, + data + ); + } + + /** + * A tag over the current ref state (names + tips + HEAD). The cached + * reachable object set is keyed on it: any push, ref delete, or gc changes + * a tip and so bumps the version, which is exactly when the set can change. + * A sha1 hex string never collides with the "" invalidation sentinel. + */ + reachableVersion(): string { + const parts: string[] = []; + for (const r of this.refs()) parts.push(`${r.name}\0${r.target}`); + parts.push(`HEAD\0${this.getRef("HEAD") ?? ""}`); + return sha1hex(te.encode(parts.join("\n"))); + } + + /** + * The cached reachable object set as an OidSet with every entry marked (so + * markedSize/markedAtHex/isMarkedHex feed the pack-emission path directly), + * or null when the cache is missing or its version no longer matches current + * refs. The version check is the only correctness gate — a stale set is + * never returned, so the fast path can never serve unreachable objects. + */ + loadReachable(): OidSet | null { + if (this.getMeta("reachable-version") !== this.reachableVersion()) return null; + const rows = this.sql.exec<{ oid: string }>("SELECT oid FROM reachable").toArray(); + if (!rows.length) return null; + const set = new OidSet(rows.length); + for (const r of rows) set.markHex(r.oid); + return set; + } + + /** + * Persist the marked sub-set of `set` (a full clone's reachable object set) + * and stamp it with the current ref version. Yields periodically so a large + * write never monopolizes the event loop; if refs change mid-write (a push + * landing during a cold clone) the version guard abandons the stamp, leaving + * the half-written table unversioned and thus ignored until it is rebuilt. + */ + async saveReachable(set: OidSet): Promise { + const version = this.reachableVersion(); + this.sql.exec("DELETE FROM reachable"); + const n = set.markedSize; + for (let i = 0; i < n; i++) { + this.sql.exec("INSERT OR IGNORE INTO reachable (oid) VALUES (?)", set.markedAtHex(i)); + if ((i & 8191) === 8191) { + if (this.reachableVersion() !== version) return; + await new Promise((r) => setTimeout(r, 0)); + } + } + if (this.reachableVersion() !== version) return; + this.setMeta("reachable-version", version); + } + + /** + * Fold every oid in `set` into the cached reachable set and re-stamp it with + * the current ref version. Used on a fast-forward push, where the receive + * connectivity walk already visited exactly the newly connected objects: + * union with the prior (validated) set yields the new reachable set without + * a fresh graph walk. Only sound when no object became unreachable — the + * caller must have a valid prior cache and no stranded history. + */ + extendReachable(set: OidSet): void { + for (let i = 0; i < set.size; i++) { + this.sql.exec("INSERT OR IGNORE INTO reachable (oid) VALUES (?)", set.atHex(i)); + } + this.setMeta("reachable-version", this.reachableVersion()); + } + + /** Drop the version stamp so the next full clone rebuilds the set by walking. */ + invalidateReachable(): void { + this.setMeta("reachable-version", ""); + } + + /** + * True when the persisted reachable set still matches the current refs, so a + * full clone can stream its objects straight from storage (see + * `reachablePackedAfter`) instead of loading the whole set into an OidSet and + * walking. The version check is the same correctness gate `loadReachable` + * uses — a stale set is never streamed. + */ + reachableCacheValid(): boolean { + return this.getMeta("reachable-version") === this.reachableVersion(); + } + + /** Size of the cached reachable set — the exact object count a warm full + * clone declares in its pack header. */ + reachableCount(): number { + return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM reachable").one().n; + } + + /** Whether `oid` is in the cached reachable set. On the warm full-clone path a + * stored delta ships as a ref-delta only when its base is also being sent, + * i.e. also reachable; otherwise that object is inflated whole. */ + reachableHas(oid: string): boolean { + return this.sql.exec("SELECT 1 FROM reachable WHERE oid = ? LIMIT 1", oid).toArray().length > 0; + } + + /** + * Reachable objects that live in a pack, one keyset page at a time in + * (pack_id, offset) storage order. Marching each pack sequentially keeps the + * raw-chunk cache hitting, and the (pack_id, offset) cursor holds no + * per-object state in the isolate — so a warm full clone streams in O(page) + * memory no matter how many objects the repo has, replacing the OidSet and + * parallel typed arrays the walk path builds. + */ + reachablePackedAfter(afterPack: number, afterOffset: number, limit: number): PackedReachable[] { + return this.sql + .exec<{ + oid: string; + pack_id: number; + offset: number; + data_off: number; + data_len: number; + type: ObjType; + entry_size: number; + base_oid: string | null; + }>( + `SELECT p.oid, p.pack_id, p.offset, p.data_off, p.data_len, p.type, p.entry_size, p.base_oid + FROM reachable r JOIN pack_objects p ON p.oid = r.oid + WHERE p.pack_id > ? OR (p.pack_id = ? AND p.offset > ?) + ORDER BY p.pack_id, p.offset + LIMIT ?`, + afterPack, + afterPack, + afterOffset, + limit, + ) + .toArray() + .map((r) => ({ + oid: r.oid, + packId: r.pack_id, + offset: r.offset, + dataOff: r.data_off, + dataLen: r.data_len, + type: r.type, + entrySize: r.entry_size, + baseOid: r.base_oid, + })); + } + + /** Reachable objects with no pack entry (loose), ordered by oid — streamed + * after every packed object so a warm full clone has a stable total order. */ + reachableLooseAfter(afterOid: string, limit: number): string[] { + return this.sql + .exec<{ oid: string }>( + `SELECT r.oid FROM reachable r + WHERE NOT EXISTS (SELECT 1 FROM pack_objects p WHERE p.oid = r.oid) AND r.oid > ? + ORDER BY r.oid LIMIT ?`, + afterOid, + limit, + ) + .toArray() + .map((r) => r.oid); + } +} diff --git a/apps/api/src/vendor/dgit/git/util.ts b/apps/api/src/vendor/dgit/git/util.ts new file mode 100644 index 0000000000..8904fc8af8 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/util.ts @@ -0,0 +1,41 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +export const te = new TextEncoder(); +export const td = new TextDecoder(); + +export function concat(parts: Uint8Array[]): Uint8Array { + let len = 0; + for (const p of parts) len += p.length; + const out = new Uint8Array(len); + let off = 0; + for (const p of parts) { + out.set(p, off); + off += p.length; + } + return out; +} + +export function toHex(b: Uint8Array): string { + let s = ""; + for (let i = 0; i < b.length; i++) s += b[i].toString(16).padStart(2, "0"); + return s; +} + +export function fromHex(s: string): Uint8Array { + const out = new Uint8Array(s.length / 2); + for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16); + return out; +} + +export const ZERO_OID = "0".repeat(40); + +export function isOid(s: string): boolean { + return /^[0-9a-f]{40}$/.test(s); +} + +export function sha1hex(data: Uint8Array): string { + return toHex(sha1(data)); +} + +import { sha1 } from "./sha1"; +export { sha1, Sha1 } from "./sha1"; diff --git a/apps/api/src/vendor/dgit/git/zlib.ts b/apps/api/src/vendor/dgit/git/zlib.ts new file mode 100644 index 0000000000..dd5592f813 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/zlib.ts @@ -0,0 +1,35 @@ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +/* eslint-disable */ +import pako from "pako"; +import { concat } from "./util"; + +/** Deflate with a zlib wrapper (what git uses for loose objects and pack entries). */ +export function deflate(data: Uint8Array): Uint8Array { + return pako.deflate(data); +} + +export function inflate(data: Uint8Array): Uint8Array { + return pako.inflate(data); +} + +/** + * gunzip with an output budget. A gzipped request body compresses ~1000:1 in + * the adversarial case, so the compressed length says nothing about what it + * inflates to: the only safe bound is on the bytes coming *out*. Inflating + * incrementally and stopping the moment the budget is passed means an + * over-inflating body costs the budget, not the bomb. + */ +export function gunzipLimited(data: Uint8Array, maxOut: number): Uint8Array { + const inf = new pako.Inflate({ windowBits: 15 + 16 }); + const parts: Uint8Array[] = []; + let out = 0; + (inf as unknown as { onData: (c: Uint8Array) => void }).onData = (c: Uint8Array) => { + out += c.length; + if (out > maxOut) throw new Error(`request body exceeds maximum size (${maxOut} bytes decompressed)`); + parts.push(c); + }; + inf.push(data, true); + const anyInf = inf as unknown as { err: number; msg: string }; + if (anyInf.err) throw new Error(`gunzip failed: ${anyInf.msg}`); + return concat(parts); +} diff --git a/apps/api/tests/helpers/selfhost-only-modules.ts b/apps/api/tests/helpers/selfhost-only-modules.ts index 83f6d046a0..82a4dfc24b 100644 --- a/apps/api/tests/helpers/selfhost-only-modules.ts +++ b/apps/api/tests/helpers/selfhost-only-modules.ts @@ -9,7 +9,7 @@ * * Every specifier `ts.preProcessFile` reports counts, type-only imports included: erring towards * a false alarm is cheaper than shipping the code. Workspace packages (`@simple-agent-manager/*`) - * are not descended into; none of them imports these modules or pako. + * are descended into through their declared exports, including sources behind dist/. */ import { existsSync, readFileSync, statSync } from 'node:fs'; import { dirname, relative, resolve } from 'node:path'; @@ -23,7 +23,7 @@ export const API_SRC = resolve(REPO_ROOT, 'apps/api/src'); export const SELFHOST_ONLY_PATHS: readonly string[] = [ 'apps/api/src/selfhost/', // hosted-git-repo.ts, hosted-git-gc.ts, hosted-git-ls-refs.ts and any file split out of them. - 'apps/api/src/durable-objects/hosted-git-', + 'apps/api/src/selfhost/hosted-git/hosted-git-', 'apps/api/src/vendor/dgit/', ]; @@ -83,6 +83,24 @@ export function collectImportGraph(entry: string): ImportGraph { } else { const name = packageName(specifier); if (!packages.has(name)) packages.set(name, relative(REPO_ROOT, file)); + if (name.startsWith('@simple-agent-manager/')) { + const packageDir = resolve(REPO_ROOT, 'packages', name.split('/')[1]!); + const manifestPath = resolve(packageDir, 'package.json'); + if (!isFile(manifestPath)) throw new Error(`missing workspace manifest: ${name}`); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')); + const subpath = specifier === name ? '.' : `.${specifier.slice(name.length)}`; + const exported = manifest.exports?.[subpath]; + const target = + typeof exported === 'string' + ? exported + : (exported?.import ?? + exported?.default ?? + (subpath === '.' ? manifest.main : undefined)); + if (!target) throw new Error(`cannot resolve workspace export: ${specifier}`); + // These TS packages publish dist/, but the guard must inspect current source edits. + const source = target.replace(/^\.\/dist\//, './src/').replace(/\.js$/, '.ts'); + pending.push(resolveRelative(manifestPath, source)); + } } } } diff --git a/apps/api/tests/hosted-git/celld-entry-bundle.test.ts b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts new file mode 100644 index 0000000000..3e9715f5d9 --- /dev/null +++ b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts @@ -0,0 +1,69 @@ +/** + * The generated self-host project bundles on celld with hosted git in it. + * + * The celld config and entry come from scripts/selfhost (celld-config.ts, celld-project.ts) and + * the real apps/api/wrangler.toml, exactly as `pnpm selfhost:deploy` writes them. The pinned celld + * then bundles each one with `celld deploy --dry-run`, which builds the Worker with esbuild and + * prints every binding without touching a bucket. This catches what the Cloudflare-side guard + * (tests/unit/selfhost/selfhost-only-modules.test.ts) cannot: a generated entry that no longer + * resolves the self-host module, or a celld config that lost the HOSTED_GIT binding. + */ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { mkdirSync } from 'node:fs'; +import { resolve as scratchResolve } from 'node:path'; +const tmpdir = () => { + const dir = scratchResolve(import.meta.dirname, '../../../../.tmp'); + mkdirSync(dir, { recursive: true }); + return dir; +}; +import { join, resolve } from 'node:path'; + +import * as TOML from '@iarna/toml'; +import { afterAll, describe, expect, it } from 'vitest'; + +import type { WranglerToml } from '../../../../scripts/deploy/types'; +import { ensureCelldBinary, resolveEsbuild } from '../../../../scripts/selfhost/celld-binary'; +import { buildCelldConfig } from '../../../../scripts/selfhost/celld-config'; +import { + CELLD_MAIN, + prepareCelldProject, + writeCelldConfig, +} from '../../../../scripts/selfhost/celld-project'; + +const API_DIR = resolve(import.meta.dirname, '../..'); +const scratch = mkdtempSync(join(tmpdir(), 'sam-celld-entry-')); + +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +describe('generated celld project', () => { + it.each([['plain', false]])( + 'bundles in %s mode with the HostedGitRepo binding', + async (_mode, _runtimeSecrets) => { + const plan = buildCelldConfig( + TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as unknown as WranglerToml, + { main: CELLD_MAIN, baseDomain: 'box.example.com' } + ); + const projectDir = join(scratch, runtimeSecrets ? 'sealed' : 'plain'); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan }); + writeCelldConfig(projectDir, plan.config); + + const celld = await ensureCelldBinary(join(tmpdir(), 'sam-celld-bin')); + const result = spawnSync( + celld, + ['deploy', projectDir, '--dry-run', '--bucket', 's3://dry-run-not-written'], + { + encoding: 'utf8', + timeout: 300_000, + env: { ...process.env, CELLD_ESBUILD: resolveEsbuild(API_DIR) }, + } + ); + const output = `${result.stdout}${result.stderr}`; + expect(result.status, output.slice(-4000)).toBe(0); + expect(output).toContain('Bundled workspaces-api'); + expect(output).toMatch(/env\.HOSTED_GIT \(HostedGitRepo\)\s+Durable Object \(SQLite\)/); + expect(output).toMatch(/env\.HOSTED_GIT_BACKEND \(Text\)/); + }, + 600_000 + ); +}); diff --git a/apps/api/tests/hosted-git/celld/README.md b/apps/api/tests/hosted-git/celld/README.md new file mode 100644 index 0000000000..4d045da921 --- /dev/null +++ b/apps/api/tests/hosted-git/celld/README.md @@ -0,0 +1,25 @@ +# Hosted git on celld (manual) + +Runs the real `HostedGitRepo` Durable Object under `celld dev` 0.6.3 with a bare router (no SAM +auth, which is plain JavaScript covered by `pnpm test:hosted-git` under workerd), then drives the +stock `git` CLI against it. Not part of CI. + +```bash +mkdir -p /tmp/celld-run/proj /tmp/celld-run/bin && cd /tmp/celld-run +curl -fsSL -o celld.gz https://github.com/denoland/celld/releases/download/v0.6.3/celld-x86_64-unknown-linux-gnu.gz +echo "5084a083472cf036551a7eac63fa24d22bb9a56323c517f63205724c12783047 celld.gz" | sha256sum -c +gunzip celld.gz && chmod +x celld +ln -s "$(find /node_modules/.pnpm -path '*@esbuild+linux-x64*/bin/esbuild' | head -1)" bin/esbuild +cp /apps/api/tests/hosted-git/celld/{entry.ts,wrangler.json} proj/ +ln -s /apps/api/src proj/src +PATH=/tmp/celld-run/bin:$PATH ./celld dev proj --port 9876 --no-watch & +bash /apps/api/tests/hosted-git/celld/conformance.sh +bash /apps/api/tests/hosted-git/celld/near-cap.sh +``` + +Result on 2026-11-12 (4 vCPU workspace, state on tmpfs, no bucket, so durability waits are not +included; the box's bucket adds latency): push, full clone + `fsck --strict`, shallow clone, fetch +into the shallow clone, and branch create and delete all pass. A 65 MiB push and a 30,071-object push +are refused with `remote: SAM: push refused: ...`. A `0004-004` pkt-line body answers 400 in 4 ms and +the repository keeps serving. Near the object cap (28,102 objects): push 3.2 s, cold clone 45 s, warm +clone 1.1 s, shallow clone 1.9 s, `fsck --strict` clean. diff --git a/apps/api/tests/hosted-git/celld/conformance.sh b/apps/api/tests/hosted-git/celld/conformance.sh new file mode 100755 index 0000000000..2094a0438c --- /dev/null +++ b/apps/api/tests/hosted-git/celld/conformance.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -u +cd /tmp/celld-run && rm -rf w && mkdir w && cd w +export GIT_TERMINAL_PROMPT=0 GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@e GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@e +G() { git -c gc.auto=0 -c protocol.version=2 "$@"; } +R=http://127.0.0.1:9876/repo/demo2.git +t() { local s=$(date +%s%N); "$@"; local rc=$?; echo " rc=$rc $(( ($(date +%s%N)-s)/1000000 )) ms: $*"; } +curl -s -X PUT -d '{"defaultBranch":"main"}' $R/init; echo +G init -q -b main src && cd src && for i in $(seq 1 50); do echo "line $i" > f$i.txt; done && G add . && G commit -qm one && for c in 2 3 4; do echo $c >> f1.txt; G commit -qam c$c; done +t G push -q $R main +cd ..; t G clone -q $R full; G -C full fsck --strict && echo " fsck ok, commits=$(G -C full rev-list --count HEAD)" +t G clone -q --depth 1 $R shallow; echo " shallow commits: $(G -C shallow rev-list --count HEAD)" +cd src && echo more >> f2.txt && G commit -qam c5 && t G push -q $R main && cd .. +t G -C shallow fetch -q origin main; echo " fetched $(G -C shallow rev-parse --short FETCH_HEAD) vs $(G -C src rev-parse --short HEAD)" +cd src && G checkout -qb gone && echo x > gone.txt && G add . && G commit -qm gone && t G push -q $R gone && t G push -q $R --delete gone && cd .. +echo "== push over the size cap (65 MiB random)" +cd src && G checkout -q main && head -c $((65*1024*1024)) /dev/urandom > big.bin && G add big.bin && G commit -qm big && t G push $R main:refs/heads/big 2>&1 | grep -E "remote:|error|rejected" | head -4; G reset -q --hard HEAD~1; cd .. +echo "== push over the object cap" +cd src && mkdir many && for i in $(seq 0 30000); do echo $i > many/f$i; done && G add many && G commit -qm many && t G push $R main:refs/heads/many 2>&1 | grep -E "remote:|error|rejected" | head -4; cd .. +echo "== repo still serves after refusals"; t G clone -q $R after; G -C after fsck --strict && echo " fsck ok" diff --git a/apps/api/tests/hosted-git/celld/entry.ts b/apps/api/tests/hosted-git/celld/entry.ts new file mode 100644 index 0000000000..976d2a12e2 --- /dev/null +++ b/apps/api/tests/hosted-git/celld/entry.ts @@ -0,0 +1,25 @@ +// celld dev harness (tests/hosted-git/celld/README.md): the real HostedGitRepo Durable Object behind a bare router (no auth). +import { HostedGitRepo } from './src/selfhost/hosted-git/hosted-git-repo'; + +export { HostedGitRepo }; + +interface Env { + HOSTED_GIT: DurableObjectNamespace; +} + +export default { + async fetch(req: Request, env: Env): Promise { + const url = new URL(req.url); + const m = /^\/repo\/([a-z0-9-]+)\.git(\/.*)$/.exec(url.pathname); + if (!m) return new Response('not found\n', { status: 404 }); + const stub = env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(m[1]!)); + url.pathname = m[2]!; + return stub.fetch( + new Request(url.toString(), { + method: req.method, + headers: req.headers, + body: req.method === 'GET' ? null : req.body, + }) + ); + }, +}; diff --git a/apps/api/tests/hosted-git/celld/near-cap.sh b/apps/api/tests/hosted-git/celld/near-cap.sh new file mode 100755 index 0000000000..c15d58415f --- /dev/null +++ b/apps/api/tests/hosted-git/celld/near-cap.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +cd /tmp/celld-run && rm -rf n && mkdir n && cd n +export GIT_TERMINAL_PROMPT=0 GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@e GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@e +G() { git -c gc.auto=0 "$@"; } +R=http://127.0.0.1:9876/repo/nearcap.git +curl -s -X PUT -d '{"defaultBranch":"main"}' $R/init >/dev/null +G init -q -b main src && cd src +for d in $(seq 0 99); do mkdir d$d; for i in $(seq 0 279); do echo "$d $i $RANDOM" > d$d/f$i; done; done +G add . && G commit -qm bulk +echo "objects: $(G count-objects -v | awk '/count|in-pack/{s+=$2} END{print s}')" +s=$(date +%s%N); G push -q $R main 2>/dev/null; echo "push rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +cd ..; s=$(date +%s%N); G clone -q $R cold; echo "cold clone rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +s=$(date +%s%N); G clone -q $R warm; echo "warm clone rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +s=$(date +%s%N); G clone -q --depth 1 $R shallow; echo "shallow clone rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +G -C cold fsck --strict && echo fsck ok diff --git a/apps/api/tests/hosted-git/celld/wrangler.json b/apps/api/tests/hosted-git/celld/wrangler.json new file mode 100644 index 0000000000..dab17175f0 --- /dev/null +++ b/apps/api/tests/hosted-git/celld/wrangler.json @@ -0,0 +1,7 @@ +{ + "name": "hosted-git-celld", + "main": "entry.ts", + "compatibility_date": "2026-01-01", + "durable_objects": { "bindings": [{ "name": "HOSTED_GIT", "class_name": "HostedGitRepo" }] }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["HostedGitRepo"] }] +} diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts new file mode 100644 index 0000000000..d064a56184 --- /dev/null +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -0,0 +1,726 @@ +/** + * Conformance of the SAM-hosted git server with a real git client. + * + * Everything below drives the stock `git` CLI over HTTP against the HostedGitRepo Durable Object + * running in Miniflare, through the same authenticated route production mounts at + * `https://api./git/.git`. Repositories are created through the real + * project-create route (artifacts provider, an email-only user with no GitHub link), which seeds + * the README in-process; workspace credentials come from the real POST /workspaces/:id/git-token. + */ +import { execFile } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { resolve as scratchResolve } from 'node:path'; +const tmpdir = () => { + const dir = scratchResolve(import.meta.dirname, '../../../../.tmp'); + mkdirSync(dir, { recursive: true }); + return dir; +}; +import { join } from 'node:path'; +import { promisify } from 'node:util'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { + DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES, + DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS, +} from '../../src/selfhost/hosted-git/limits'; +import { + HOSTED_GIT_TEST_BASE_DOMAIN, + type HostedGitRuntime, + startHostedGitRuntime, +} from './support/hosted-git-runtime'; + +const execFileAsync = promisify(execFile); + +let runtime: HostedGitRuntime; +let scratch: string; +/** Fake public forge: https://github.com/sam-test/.git is served from a hosted repo. */ +const fakeForge = new Map(); + +interface GitResult { + code: number; + stdout: string; + stderr: string; +} + +/** Run git with no ambient credentials, prompts or config. */ +async function git(args: string[], cwd?: string): Promise { + try { + const { stdout, stderr } = await execFileAsync( + 'git', + [ + '-c', + 'credential.helper=', + '-c', + 'protocol.version=2', + '-c', + 'gc.auto=0', + '-c', + 'maintenance.auto=false', + ...args, + ], + { + cwd, + maxBuffer: 64 * 1024 * 1024, + env: { + PATH: process.env.PATH ?? '', + HOME: scratch, + GIT_TERMINAL_PROMPT: '0', + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }, + } + ); + return { code: 0, stdout, stderr }; + } catch (error) { + const e = error as { code?: number; stdout?: string; stderr?: string }; + return { + code: typeof e.code === 'number' ? e.code : 1, + stdout: e.stdout ?? '', + stderr: e.stderr ?? '', + }; + } +} + +async function gitOk(args: string[], cwd?: string): Promise { + const result = await git(args, cwd); + if (result.code !== 0) { + throw new Error( + `git failed (${result.code}):\n${result.stderr.replace(/samgit1\.[A-Za-z0-9_.-]+/g, '[redacted]').replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/g, 'https://[redacted]@')}` + ); + } + return result; +} + +/** A local URL for a repository remote, with the token as the Basic password. */ +function localRemote(remote: string, token?: string): string { + const url = new URL(remote); + const local = new URL(runtime.origin); + local.pathname = url.pathname; + if (token) { + local.username = 'x'; + local.password = token; + } + return local.toString(); +} + +async function mintToken( + project: { artifactsRepoId: string; ownerId: string }, + scope: 'read' | 'write', + extra: { ttlSeconds?: number; workspaceId?: string; userId?: string } = {} +): Promise { + const res = await runtime.fetch('/__test/hosted-git-token', { + method: 'POST', + body: JSON.stringify({ + repo: project.artifactsRepoId, + scope, + userId: project.ownerId, + ...extra, + }), + }); + expect(res.status).toBe(200); + return ((await res.json()) as { token: string }).token; +} + +let userCounter = 0; +async function createEmailOnlyUser(): Promise { + userCounter += 1; + const id = `user-hosted-git-${userCounter}`; + await runtime.DATABASE.prepare( + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + VALUES (?, ?, 1, ?, 'user', 'active', ?, ?)` + ) + .bind(id, `${id}@example.com`, id, Date.now(), Date.now()) + .run(); + return id; +} + +interface CreatedProject { + id: string; + ownerId: string; + repository: string; + artifactsRepoId: string; + defaultBranch: string; +} + +async function createHostedProject(userId: string, name: string): Promise { + const res = await runtime.fetch('/api/projects', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test-user-id': userId }, + body: JSON.stringify({ name, repoProvider: 'artifacts', description: 'Hosted repo test' }), + }); + const body = (await res.json()) as Record; + expect(res.status, JSON.stringify(body)).toBe(201); + const row = await runtime.DATABASE.prepare( + `SELECT id, repository, artifacts_repo_id AS artifactsRepoId, default_branch AS defaultBranch + FROM projects WHERE id = ?` + ) + .bind(body.id) + .first(); + expect(row).not.toBeNull(); + return { ...row!, ownerId: userId }; +} + +async function freshDir(name: string): Promise { + const dir = join(scratch, `${name}-${randomBytes(4).toString('hex')}`); + await mkdir(dir, { recursive: true }); + return dir; +} + +beforeAll(async () => { + scratch = await mkdtemp(join(tmpdir(), 'sam-hosted-git-client-')); + runtime = await startHostedGitRuntime(async (request) => { + const url = new URL(request.url); + const match = /^\/sam-test\/([^/]+?)(?:\.git)?(\/.*)$/.exec(url.pathname); + const source = url.hostname === 'github.com' && match ? fakeForge.get(match[1]!) : undefined; + if (!source) return new Response('not found', { status: 404 }); + const headers = new Headers(request.headers); + headers.set('authorization', `Basic ${btoa(`x:${source.token}`)}`); + // Node's fetch sets these itself and refuses a forwarded content-length + // ("invalid content-length header") on the POST git sends for protocol v2 ls-refs. + headers.delete('content-length'); + headers.delete('host'); + return fetch(`${runtime.origin}/git/${source.repo}.git${match![2]}${url.search}`, { + method: request.method, + headers, + body: request.method === 'GET' ? undefined : await request.arrayBuffer(), + }); + }); +}); + +afterAll(async () => { + await runtime?.close(); + if (scratch) await rm(scratch, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); +}); + +describe('SAM-hosted repositories with a real git client', () => { + let owner: string; + let project: CreatedProject; + + beforeAll(async () => { + owner = await createEmailOnlyUser(); + project = await createHostedProject(owner, 'Hosted Conformance'); + }); + + it('creates the project with a hosted remote under api. and seeds a README', async () => { + expect(project.repository).toBe( + `https://api.${HOSTED_GIT_TEST_BASE_DOMAIN}/git/${project.artifactsRepoId}.git` + ); + const token = await mintToken(project, 'read'); + const dir = await freshDir('clone'); + await gitOk(['clone', localRemote(project.repository, token), dir]); + const readme = await readFile(join(dir, 'README.md'), 'utf8'); + expect(readme).toContain('Hosted Conformance'); + const branch = await gitOk(['rev-parse', '--abbrev-ref', 'HEAD'], dir); + expect(branch.stdout.trim()).toBe(project.defaultBranch); + const fsck = await git(['fsck', '--strict'], dir); + expect(fsck.code).toBe(0); + }); + + it('pushes a branch, then shallow-clones and fetches it', async () => { + const token = await mintToken(project, 'write'); + const work = await freshDir('work'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['checkout', '-b', 'feature/one'], work); + for (let i = 0; i < 3; i++) { + await writeFile(join(work, `file-${i}.txt`), `content ${i}\n`); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', `commit ${i}`], work); + } + await gitOk(['push', 'origin', 'feature/one'], work); + const head = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + + const shallow = await freshDir('shallow'); + await gitOk( + [ + 'clone', + '--depth', + '1', + '--branch', + 'feature/one', + localRemote(project.repository, token), + shallow, + ], + undefined + ); + expect((await gitOk(['rev-parse', 'HEAD'], shallow)).stdout.trim()).toBe(head); + expect((await gitOk(['rev-list', '--count', 'HEAD'], shallow)).stdout.trim()).toBe('1'); + + // A new commit on the server, then fetch it into the shallow clone. + await writeFile(join(work, 'later.txt'), 'later\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'later'], work); + await gitOk(['push', 'origin', 'feature/one'], work); + const later = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + await gitOk(['fetch', 'origin', 'feature/one'], shallow); + expect((await gitOk(['rev-parse', 'FETCH_HEAD'], shallow)).stdout.trim()).toBe(later); + + // A full clone sees every branch and passes fsck. + const full = await freshDir('full'); + await gitOk(['clone', localRemote(project.repository, token), full]); + const branches = (await gitOk(['branch', '-r'], full)).stdout; + expect(branches).toContain('origin/feature/one'); + expect((await git(['fsck', '--strict'], full)).code).toBe(0); + }); + + it('refuses an unauthenticated clone', async () => { + const dir = await freshDir('anon'); + const result = await git(['clone', localRemote(project.repository), dir]); + expect(result.code).not.toBe(0); + expect(result.stderr).toMatch(/Authentication failed|could not read Username|401/); + }); + + it('refuses a push with a read-scoped token, and accepts the same push with write scope', async () => { + const read = await mintToken(project, 'read'); + const work = await freshDir('readonly'); + await gitOk(['clone', localRemote(project.repository, read), work]); + await writeFile(join(work, 'nope.txt'), 'nope\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'nope'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/read-only'], work); + expect(refused.code).not.toBe(0); + + const write = await mintToken(project, 'write'); + await gitOk(['remote', 'set-url', 'origin', localRemote(project.repository, write)], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/read-only'], work); + }); + + it("refuses another project's token, with an owner control", async () => { + const other = await createHostedProject(await createEmailOnlyUser(), 'Other Tenant'); + const otherToken = await mintToken(other, 'write'); + const attack = await freshDir('attack'); + const refused = await git(['clone', localRemote(project.repository, otherToken), attack]); + expect(refused.code).not.toBe(0); + + // Owner control: the same token works on its own repository. + const control = await freshDir('control'); + await gitOk(['clone', localRemote(other.repository, otherToken), control]); + expect(await readFile(join(control, 'README.md'), 'utf8')).toContain('Other Tenant'); + }); + + it('refuses an expired or tampered token', async () => { + const token = await mintToken(project, 'read'); + const [prefix, payload, signature] = token.split('.'); + const forged = JSON.parse(Buffer.from(payload!, 'base64url').toString()); + forged.repo = 'someone-else'; + const tampered = `${prefix}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`; + const res = await runtime.fetch( + `/git/${project.artifactsRepoId}.git/info/refs?service=git-upload-pack`, + { headers: { authorization: `Basic ${btoa(`x:${tampered}`)}` } } + ); + expect(res.status).toBe(401); + const ok = await runtime.fetch( + `/git/${project.artifactsRepoId}.git/info/refs?service=git-upload-pack`, + { headers: { authorization: `Basic ${btoa(`x:${token}`)}` } } + ); + expect(ok.status).toBe(200); + }); + + it('refuses a small compressed pack with an oversized commit, then accepts a normal push', async () => { + const user = await createEmailOnlyUser(); + const target = await createHostedProject(user, 'Inflation bound'); + const token = await mintToken(target, 'write'); + const work = await freshDir('compressed-object'); + await gitOk(['clone', localRemote(target.repository, token), work]); + // A 17 MiB commit message compresses to a tiny pack, below the 64 MiB wire cap. + // Fixture stays fixed so raising/removing the 16 MiB object guard fails this test. + await writeFile(join(work, 'message'), 'a'.repeat(17 * 1024 * 1024)); + await gitOk(['commit', '--allow-empty', '-F', 'message'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/bomb'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain('inflated size limit'); + await gitOk(['reset', '--hard', 'origin/main'], work); + await gitOk(['commit', '--allow-empty', '-m', 'safe'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/safe'], work); + const refs = await gitOk(['ls-remote', 'origin'], work); + expect(refs.stdout).toContain('refs/heads/safe'); + expect(refs.stdout).not.toContain('refs/heads/bomb'); + }); + + it('refuses a push over the push-size cap with a clear message, and keeps the repository intact', async () => { + const token = await mintToken(project, 'write'); + const work = await freshDir('big'); + await gitOk(['clone', localRemote(project.repository, token), work]); + // Incompressible content just over the cap. + await writeFile( + join(work, 'big.bin'), + randomBytes(DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES + 1024 * 1024) + ); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'big'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/too-big'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain('SAM: push refused'); + expect(refused.stderr).toContain('MiB limit for one push'); + + const check = await freshDir('after-big'); + await gitOk(['clone', localRemote(project.repository, token), check]); + const remoteBranches = (await gitOk(['branch', '-r'], check)).stdout; + expect(remoteBranches).not.toContain('too-big'); + }); + + it('refuses a push that would exceed the object cap, naming the limit', async () => { + const token = await mintToken(project, 'write'); + const work = await freshDir('many'); + await gitOk(['clone', localRemote(project.repository, token), work]); + const dir = join(work, 'many'); + await mkdir(dir); + // One distinct blob per file: more blobs than the cap allows in total. + for (let i = 0; i <= DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS; i++) { + await writeFile(join(dir, `f${i}`), `${i}\n`); + } + await gitOk(['add', '.'], work); + await gitOk(['commit', '-q', '-m', 'many'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/too-many'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain(`${DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS}-object limit`); + }); +}); + +describe('hosted git hardening (security review findings)', () => { + let project: CreatedProject; + + beforeAll(async () => { + project = await createHostedProject(await createEmailOnlyUser(), 'Hardening'); + }); + + function infoRefs(token: string): Promise { + return runtime.fetch(`/git/${project.artifactsRepoId}.git/info/refs?service=git-upload-pack`, { + headers: { authorization: `Basic ${btoa(`x:${token}`)}` }, + }); + } + + it('answers a negative pkt-line length promptly with 400 and keeps serving the repository', async () => { + const token = await mintToken(project, 'write'); + for (const body of ['0004-004', '-001', '0002', '00zz']) { + const started = Date.now(); + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${btoa(`x:${token}`)}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body, + }); + expect(res.status, body).toBe(400); + expect(Date.now() - started).toBeLessThan(5_000); + } + // Liveness: the same repository still answers. + expect((await infoRefs(token)).status).toBe(200); + }); + + it('refuses a chunked upload-pack body over the cap without buffering it', async () => { + const token = await mintToken(project, 'read'); + const chunk = new Uint8Array(1024 * 1024); + let sent = 0; + const body = new ReadableStream({ + pull(controller) { + if (sent >= 20) return controller.close(); + sent++; + controller.enqueue(chunk); + }, + }); + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-upload-pack`, { + method: 'POST', + headers: { authorization: `Basic ${btoa(`x:${token}`)}` }, + body, + duplex: 'half', + } as RequestInit); + expect(res.status).toBe(413); + expect((await infoRefs(token)).status).toBe(200); + }); + + it('refuses a token with no person behind it (internal seeding tokens stay internal)', async () => { + const res = await runtime.fetch('/__test/hosted-git-token', { + method: 'POST', + body: JSON.stringify({ repo: project.artifactsRepoId, scope: 'read' }), + }); + const { token } = (await res.json()) as { token: string }; + expect((await infoRefs(token)).status).toBe(401); + expect((await infoRefs(await mintToken(project, 'read'))).status).toBe(200); + }); + + it("refuses a removed member's token, with an active-member control", async () => { + const member = await createEmailOnlyUser(); + const now = new Date().toISOString(); + await runtime.DATABASE.prepare( + `INSERT INTO project_members (project_id, user_id, role, status, created_at, updated_at) + VALUES (?, ?, 'maintainer', 'active', ?, ?)` + ) + .bind(project.id, member, now, now) + .run(); + const token = await mintToken(project, 'read', { userId: member }); + expect((await infoRefs(token)).status).toBe(200); + // A write token stops pushing as soon as the member's role loses write access. + const write = await mintToken(project, 'write', { userId: member }); + const receiveRefs = (t: string) => + runtime.fetch(`/git/${project.artifactsRepoId}.git/info/refs?service=git-receive-pack`, { + headers: { authorization: `Basic ${btoa(`x:${t}`)}` }, + }); + expect((await receiveRefs(write)).status).toBe(200); + await runtime.DATABASE.prepare( + `UPDATE project_members SET role = 'viewer' WHERE project_id = ? AND user_id = ?` + ) + .bind(project.id, member) + .run(); + expect((await receiveRefs(write)).status).toBe(401); + expect((await infoRefs(token)).status).toBe(200); + + await runtime.DATABASE.prepare( + `UPDATE project_members SET status = 'removed', removed_at = ? WHERE project_id = ? AND user_id = ?` + ) + .bind(now, project.id, member) + .run(); + expect((await infoRefs(token)).status).toBe(401); + }); +}); + +describe('browsing a hosted repository through the repo-browse API', () => { + it('lists branches, the tree and a file, and compares two branches', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Browse Me'); + const token = await mintToken(project, 'write'); + const work = await freshDir('browse'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['checkout', '-b', 'feature/browse'], work); + await mkdir(join(work, 'src')); + await writeFile(join(work, 'src', 'app.ts'), 'export const answer = 42;\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'add app'], work); + await gitOk(['push', 'origin', 'feature/browse'], work); + + const get = async (path: string) => { + const res = await runtime.fetch(`/api/projects/${project.id}${path}`, { + headers: { 'x-test-user-id': owner }, + }); + const body = (await res.json()) as Record; + expect(res.status, `${path} ${JSON.stringify(body)}`).toBe(200); + return body; + }; + const branches = (await get('/repo/branches')) as { + branches: Array<{ name: string; isDefault: boolean }>; + }; + // Exactly the branches: the list asks the server for refs/heads/ only, so HEAD is never one + // (box round R13 D11: dgit ignored ref-prefix and "HEAD" showed up as a branch). + expect(branches.branches).toEqual([ + { name: project.defaultBranch, isDefault: true }, + { name: 'feature/browse', isDefault: false }, + ]); + + const tree = (await get('/repo/tree?ref=feature/browse')) as { + entries: Array<{ path: string }>; + }; + const paths = tree.entries.map((e) => e.path); + expect(paths).toContain('README.md'); + expect(paths).toContain('src/app.ts'); + + const file = (await get('/repo/file?ref=feature/browse&path=src/app.ts')) as { + content?: string; + }; + expect(file.content).toBe('export const answer = 42;\n'); + + const compare = (await get( + `/repo/compare?base=${project.defaultBranch}&head=feature/browse` + )) as { files: Array<{ path: string; status: string }> }; + expect(compare.files.map((f) => f.path)).toEqual(['src/app.ts']); + + const stranger = await createEmailOnlyUser(); + const denied = await runtime.fetch(`/api/projects/${project.id}/repo/branches`, { + headers: { 'x-test-user-id': stranger }, + }); + expect([403, 404]).toContain(denied.status); + }); +}); + +describe('garbage collection', () => { + it('reclaims the objects of a deleted branch and keeps the repository intact', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'GC Me'); + const token = await mintToken(project, 'write'); + const work = await freshDir('gc'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['checkout', '-b', 'throwaway'], work); + for (let i = 0; i < 20; i++) await writeFile(join(work, `junk-${i}.bin`), randomBytes(4096)); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'junk'], work); + await gitOk(['push', 'origin', 'throwaway'], work); + type Info = { objects: number }; + const before = (await ( + await runtime.fetch(`/__test/info/${project.artifactsRepoId}`) + ).json()) as Info; + await gitOk(['push', 'origin', '--delete', 'throwaway'], work); + const after = (await ( + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }) + ).json()) as Info; + // 20 blobs + 1 tree + 1 commit were only reachable from the deleted branch. + expect(before.objects - after.objects).toBeGreaterThanOrEqual(22); + + const check = await freshDir('gc-check'); + await gitOk(['clone', localRemote(project.repository, token), check]); + expect(await readFile(join(check, 'README.md'), 'utf8')).toContain('GC Me'); + expect((await git(['fsck', '--strict'], check)).code).toBe(0); + }); +}); + +describe('public import remains unavailable in H2', () => { + it('refuses importUrl before creating a repository', async () => { + const owner = await createEmailOnlyUser(); + const res = await runtime.fetch('/api/projects', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test-user-id': owner }, + body: JSON.stringify({ + name: 'Import unavailable', + repoProvider: 'artifacts', + importUrl: 'https://github.com/sam-test/source.git', + }), + }); + expect(res.status).toBe(400); + expect(await res.text()).toContain('does not support importUrl'); + }); +}); + +describe('member clone credentials (POST /api/projects/:id/hosted-git/token)', () => { + it('lets the owner clone and push, and refuses a non-member', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Member Token'); + const res = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token?scope=write`, { + method: 'POST', + headers: { 'x-test-user-id': owner }, + }); + const body = (await res.json()) as { token: string; cloneUrl: string; host: string }; + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.cloneUrl).toBe(project.repository); + const work = await freshDir('member'); + await gitOk(['clone', localRemote(body.cloneUrl, body.token), work]); + await writeFile(join(work, 'human.txt'), 'from a laptop\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'human'], work); + await gitOk(['push', 'origin', 'HEAD'], work); + + const stranger = await createEmailOnlyUser(); + const denied = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token`, { + method: 'POST', + headers: { 'x-test-user-id': stranger }, + }); + expect([403, 404]).toContain(denied.status); + }); +}); + +describe('vertical: project creation to a workspace clone and push', () => { + it('a workspace gets a token from git-token, clones, pushes, and is refused once stopped', async () => { + const userId = await createEmailOnlyUser(); + const project = await createHostedProject(userId, 'Workspace Flow'); + const now = new Date().toISOString(); + const nodeId = 'node-hosted-git-1'; + const workspaceId = 'ws-hosted-git-1'; + await runtime.DATABASE.prepare( + `INSERT INTO nodes (id, user_id, name, status, created_at, updated_at) + VALUES (?, ?, 'node', 'running', ?, ?)` + ) + .bind(nodeId, userId, now, now) + .run(); + await runtime.DATABASE.prepare( + `INSERT INTO workspaces (id, node_id, project_id, user_id, name, repository, branch, status, vm_size, vm_location, created_at, updated_at) + VALUES (?, ?, ?, ?, 'ws', ?, ?, 'running', 'small', 'local', ?, ?)` + ) + .bind( + workspaceId, + nodeId, + project.id, + userId, + project.repository, + project.defaultBranch, + now, + now + ) + .run(); + + const callback = (await ( + await runtime.fetch('/__test/workspace-callback-token', { + method: 'POST', + body: JSON.stringify({ workspaceId }), + }) + ).json()) as { token: string }; + const res = await runtime.fetch(`/api/workspaces/${workspaceId}/git-token`, { + method: 'POST', + headers: { authorization: `Bearer ${callback.token}` }, + }); + const body = (await res.json()) as { + token: string; + cloneUrl: string; + username?: string; + }; + expect(res.status, JSON.stringify(body)).toBe(200); + // What the VM agent's credential helper needs for a host it does not know by name. + // Main's L16 response: the VM agent derives the credential host from cloneUrl. + expect(body.cloneUrl).toBe(project.repository); + expect(new URL(body.cloneUrl).host).toBe(`api.${HOSTED_GIT_TEST_BASE_DOMAIN}`); + expect(body.username).toBe('x'); + + const work = await freshDir('workspace'); + await gitOk([ + 'clone', + '--branch', + project.defaultBranch, + localRemote(body.cloneUrl, body.token), + work, + ]); + await gitOk(['checkout', '-b', 'sam/agent-work'], work); + await writeFile(join(work, 'agent.txt'), 'agent output\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'agent work'], work); + await gitOk(['push', 'origin', 'sam/agent-work'], work); + + // The pushed branch is visible to a fresh reader. + const reader = await mintToken(project, 'read'); + const check = await freshDir('verify'); + await gitOk([ + 'clone', + '--branch', + 'sam/agent-work', + localRemote(project.repository, reader), + check, + ]); + expect(await readFile(join(check, 'agent.txt'), 'utf8')).toBe('agent output\n'); + + // Generation fence: a restarted runtime (rotated callback generation) retires the token. + await runtime.DATABASE.prepare( + `UPDATE workspaces SET callback_generation = 'rotated' WHERE id = ?` + ) + .bind(workspaceId) + .run(); + const retired = await git(['push', 'origin', 'sam/agent-work:refs/heads/after-rotate'], work); + expect(retired.code).not.toBe(0); + const fresh = (await ( + await runtime.fetch(`/api/workspaces/${workspaceId}/git-token`, { + method: 'POST', + headers: { + authorization: `Bearer ${ + ( + (await ( + await runtime.fetch('/__test/workspace-callback-token', { + method: 'POST', + body: JSON.stringify({ workspaceId }), + }) + ).json()) as { token: string } + ).token + }`, + }, + }) + ).json()) as { token: string }; + await gitOk(['remote', 'set-url', 'origin', localRemote(body.cloneUrl, fresh.token)], work); + await gitOk(['push', 'origin', 'sam/agent-work:refs/heads/after-rotate'], work); + + // Lifecycle fence: once the workspace stops, its token is refused. + await runtime.DATABASE.prepare(`UPDATE workspaces SET status = 'stopped' WHERE id = ?`) + .bind(workspaceId) + .run(); + const refused = await git(['push', 'origin', 'sam/agent-work:refs/heads/after-stop'], work); + expect(refused.code).not.toBe(0); + }); +}); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts new file mode 100644 index 0000000000..ff97451ca6 --- /dev/null +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -0,0 +1,88 @@ +/** + * Test Worker for the hosted git conformance suite. It wires the production pieces a self-hosted + * install uses for SAM-hosted repositories: the git smart-HTTP route, the real project-create + * route (artifacts provider) and the real workspace git-token route. Only authentication of the + * browser session is replaced (an `x-test-user-id` header stands in for BetterAuth), plus two + * test-only endpoints that mint credentials the production code would mint elsewhere. + */ +// The production entry (src/index.ts, imported by the celld entry) wires repo-hosting's ports +// first; the branch list, project create and import reach them, so this entry must too. +import '../../../src/repo-hosting-wiring'; + +import { Hono } from 'hono'; + +import { handleAppError } from '../../../src/middleware/app-error-handler'; +import { registerProjectCreateRoute } from '../../../src/routes/projects/project-create'; +import { repoBrowseRoutes } from '../../../src/routes/projects/repo-browse'; +import { runtimeRoutes } from '../../../src/routes/workspaces/runtime'; +// The self-host build's own module: the class and route the generated celld entry exports and mounts. +import { HostedGitRepo, mountHostedGitRoute } from '../../../src/selfhost/hosted-git'; +import type { HostedGitEnv as Env } from '../../../src/selfhost/hosted-git/env'; +import { hostedGitTokenRoutes } from '../../../src/selfhost/hosted-git/token-route'; +import { type HostedGitScope, mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; +import { signCurrentWorkspaceCallbackToken } from '../../../src/services/jwt'; + +/** Test-only: run the GC alarm on demand (production schedules it 5 minutes after a push). */ +export class HostedGitRepoTest extends HostedGitRepo { + override async fetch(req: Request): Promise { + if (new URL(req.url).pathname === '/__test/gc') { + this.ctx.storage.sql.exec( + "INSERT INTO meta (key, value) VALUES ('gc-pending', '1') ON CONFLICT(key) DO UPDATE SET value = '1'" + ); + await this.alarm(); + return new Response('ok'); + } + return super.fetch(req); + } +} + +const app = new Hono<{ Bindings: Env }>(); +app.onError(handleAppError); + +const projects = new Hono<{ Bindings: Env }>(); +projects.use('*', async (c, next) => { + const userId = c.req.header('x-test-user-id'); + if (!userId) return c.json({ error: 'UNAUTHORIZED' }, 401); + c.set('auth' as never, { user: { id: userId, role: 'user', status: 'active' } } as never); + await next(); +}); +registerProjectCreateRoute(projects); +projects.route('/', hostedGitTokenRoutes); +projects.route('/', repoBrowseRoutes); +app.route('/api/projects', projects); +app.route('/api/workspaces', runtimeRoutes); + +// The production mount, after the other routes as in the generated celld entry. +mountHostedGitRoute(app); + +app.post('/__test/hosted-git-token', async (c) => { + const body = await c.req.json<{ + repo: string; + scope: HostedGitScope; + ttlSeconds?: number; + workspaceId?: string; + userId?: string; + callbackGeneration?: string | null; + }>(); + return c.json(await mintHostedGitToken(c.env, body)); +}); + +app.post('/__test/gc/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + await ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/gc'); + const info = await ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/info'); + return c.json(await info.json()); +}); + +app.get('/__test/info/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + const info = await ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/info'); + return c.json(await info.json()); +}); + +app.post('/__test/workspace-callback-token', async (c) => { + const { workspaceId } = await c.req.json<{ workspaceId: string }>(); + return c.json({ token: await signCurrentWorkspaceCallbackToken(workspaceId, c.env) }); +}); + +export default app; diff --git a/apps/api/tests/hosted-git/support/hosted-git-runtime.ts b/apps/api/tests/hosted-git/support/hosted-git-runtime.ts new file mode 100644 index 0000000000..d0ce9f554d --- /dev/null +++ b/apps/api/tests/hosted-git/support/hosted-git-runtime.ts @@ -0,0 +1,119 @@ +/** + * Runs the hosted git test Worker as native workerd modules in Miniflare, listening on a local + * port, so the real `git` CLI can clone from and push to it. Real D1 (all migrations applied) + * and real Durable Object SQLite. Same approach as tests/workers/support/sam-native-runtime.ts. + */ +import { execFile } from 'node:child_process'; +import { generateKeyPairSync, randomBytes } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { resolve as scratchResolve } from 'node:path'; +const tmpdir = () => { + const dir = scratchResolve(import.meta.dirname, '../../../../../.tmp'); + mkdirSync(dir, { recursive: true }); + return dir; +}; +import { dirname, resolve } from 'node:path'; +import { promisify } from 'node:util'; + +import { readD1Migrations } from '@cloudflare/vitest-pool-workers'; + +const require = createRequire(import.meta.url); +const wranglerPackage = require.resolve('wrangler/package.json'); +const wranglerBin = resolve(dirname(wranglerPackage), require(wranglerPackage).bin.wrangler); +const execute = promisify(execFile); +const { Miniflare } = createRequire(import.meta.resolve('@cloudflare/vitest-pool-workers'))( + 'miniflare' +); + +export const HOSTED_GIT_TEST_BASE_DOMAIN = 'sam.test.example'; + +export interface HostedGitRuntime { + /** e.g. http://127.0.0.1:41234 */ + origin: string; + DATABASE: D1Database; + fetch(path: string, init?: RequestInit): Promise; + close(): Promise; +} + +/** Handles the Worker's outbound fetches (e.g. an import from a fake public forge). */ +export type OutboundHandler = (request: Request) => Promise; + +export async function startHostedGitRuntime( + outbound: OutboundHandler = async () => new Response('no outbound in tests', { status: 502 }) +): Promise { + const directory = await mkdtemp(resolve(tmpdir(), 'sam-hosted-git-')); + const root = resolve(import.meta.dirname, '../../..'); + const bundleDirectory = resolve(directory, 'bundle'); + const configPath = resolve(directory, 'wrangler.json'); + await writeFile( + configPath, + JSON.stringify({ + name: 'sam-hosted-git-test', + main: resolve(root, 'tests/hosted-git/support/hosted-git-entry.ts'), + compatibility_date: '2026-01-01', + compatibility_flags: ['nodejs_compat'], + alias: { 'unicorn-magic': resolve(root, 'src/shims/unicorn-magic.ts') }, + }) + ); + await execute( + process.execPath, + [wranglerBin, 'deploy', '--dry-run', '--config', configPath, '--outdir', bundleDirectory], + { + cwd: root, + timeout: 60_000, + maxBuffer: 4_000_000, + env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, + } + ); + const files = await readdir(bundleDirectory); + const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const runtime = new Miniflare({ + modulesRoot: bundleDirectory, + modules: [ + { type: 'ESModule', path: resolve(bundleDirectory, 'hosted-git-entry.js') }, + ...files + .filter((name) => name.endsWith('.wasm')) + .map((name) => ({ type: 'CompiledWasm', path: resolve(bundleDirectory, name) })), + ], + compatibilityDate: '2026-01-01', + compatibilityFlags: ['nodejs_compat'], + host: '127.0.0.1', + port: 0, + durableObjects: { HOSTED_GIT: { className: 'HostedGitRepoTest', useSQLite: true } }, + d1Databases: ['DATABASE', 'OBSERVABILITY_DATABASE'], + kvNamespaces: ['KV'], + outboundService: (request: Request) => outbound(request), + bindings: { + BASE_DOMAIN: HOSTED_GIT_TEST_BASE_DOMAIN, + // Generated per runtime so no key material is checked in. + ENCRYPTION_KEY: randomBytes(32).toString('base64'), + ARTIFACTS_ENABLED: 'true', + HOSTED_GIT_BACKEND: 'durable-object', + JWT_PRIVATE_KEY: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), + JWT_PUBLIC_KEY: publicKey.export({ type: 'spki', format: 'pem' }).toString(), + }, + }); + const cleanup = async () => { + await runtime.dispose().catch(() => undefined); + await rm(directory, { recursive: true, force: true }); + }; + try { + const url: URL = await runtime.ready; + const database = (await runtime.getD1Database('DATABASE')) as D1Database; + for (const migration of await readD1Migrations(resolve(root, 'src/db/migrations'))) { + await database.batch(migration.queries.map((query) => database.prepare(query))); + } + const origin = url.origin; + return { + origin, + DATABASE: database, + fetch: (path, init) => fetch(`${origin}${path}`, init), + close: cleanup, + }; + } catch (error) { + await cleanup(); + throw error; + } +} diff --git a/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts new file mode 100644 index 0000000000..1396e266cc --- /dev/null +++ b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts @@ -0,0 +1,83 @@ +/** + * `ref-prefix` for protocol v2 ls-refs on SAM-hosted repositories (hosted-git-ls-refs.ts): the + * vendored dgit server ignores it, so "HEAD" came back for `refs/heads/` (box round R13 D11). + * The conformance suite drives the same filter through the real Durable Object and git. + */ +import { describe, expect, it } from 'vitest'; + +import { + filterLsRefsResponse, + lsRefsPrefixes, +} from '../../../src/selfhost/hosted-git/hosted-git-ls-refs'; +import { FLUSH, pkt, PktParser } from '../../../src/vendor/dgit/git/pktline'; +import { concat } from '../../../src/vendor/dgit/git/util'; + +const A = 'a'.repeat(40); +const B = 'b'.repeat(40); +const DELIM = new TextEncoder().encode('0001'); + +function lsRefsRequest(...args: string[]): Uint8Array { + return concat([ + pkt('command=ls-refs\n'), + pkt('agent=git/2.45\n'), + DELIM, + ...args.map((a) => pkt(`${a}\n`)), + FLUSH, + ]); +} + +function lines(body: Uint8Array): string[] { + const parser = new PktParser(body); + const out: string[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + out.push(p.kind === 'line' ? p.text : p.kind); + } + return out; +} + +const answer = () => + new Response( + concat([ + pkt(`${A} HEAD symref-target:refs/heads/main\n`), + pkt(`${A} refs/heads/main\n`), + pkt(`${B} refs/heads/feature/x\n`), + pkt(`${B} refs/tags/v1 peeled:${A}\n`), + FLUSH, + ]), + { headers: { 'content-type': 'application/x-git-upload-pack-result' } } + ); + +describe('ls-refs ref-prefix', () => { + it('reads the prefixes of an ls-refs request, and none from other requests', () => { + expect(lsRefsPrefixes(lsRefsRequest('symrefs', 'ref-prefix refs/heads/'))).toEqual([ + 'refs/heads/', + ]); + expect(lsRefsPrefixes(lsRefsRequest('ref-prefix HEAD', 'ref-prefix refs/tags/'))).toEqual([ + 'HEAD', + 'refs/tags/', + ]); + // No prefix: every ref, as the protocol says. + expect(lsRefsPrefixes(lsRefsRequest('symrefs'))).toBeNull(); + const fetch = concat([pkt('command=fetch\n'), DELIM, pkt(`want ${A}\n`), FLUSH]); + expect(lsRefsPrefixes(fetch)).toBeNull(); + }); + + it('refs/heads/ keeps the branches only: no HEAD, no tags', async () => { + const filtered = await filterLsRefsResponse(answer(), ['refs/heads/']); + expect(lines(new Uint8Array(await filtered.arrayBuffer()))).toEqual([ + `${A} refs/heads/main`, + `${B} refs/heads/feature/x`, + 'flush', + ]); + expect(filtered.headers.get('content-type')).toBe('application/x-git-upload-pack-result'); + }); + + it('keeps attributes and every matching prefix (HEAD with its symref, peeled tags)', async () => { + const filtered = await filterLsRefsResponse(answer(), ['HEAD', 'refs/tags/']); + expect(lines(new Uint8Array(await filtered.arrayBuffer()))).toEqual([ + `${A} HEAD symref-target:refs/heads/main`, + `${B} refs/tags/v1 peeled:${A}`, + 'flush', + ]); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts new file mode 100644 index 0000000000..716a7d90e5 --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + chargeGitWork, + readGitChunk, + withGitWorkBudget, +} from '../../../src/vendor/dgit/git/budget'; +import { applyDelta } from '../../../src/vendor/dgit/git/pack'; + +const limits = { maxObjectBytes: 32, maxInflatedBytes: 48, maxDeltaDepth: 2, workTimeoutMs: 1000 }; + +describe('hosted git work budget', () => { + it('rejects a delta target before allocation, while a valid delta works', () => { + withGitWorkBudget(limits, () => { + expect(() => applyDelta(new Uint8Array(), new Uint8Array([0, 33]))).toThrow( + 'inflated size limit' + ); + expect(applyDelta(new Uint8Array(), new Uint8Array([0, 1, 1, 65]))).toEqual( + new Uint8Array([65]) + ); + }); + }); + + it('charges cumulative decompression and isolates concurrent requests', async () => { + await Promise.all( + [1, 2].map(() => + withGitWorkBudget(limits, async () => { + chargeGitWork(32); + await Promise.resolve(); + chargeGitWork(16); + expect(() => chargeGitWork(1)).toThrow('decompression budget'); + }) + ) + ); + }); + + it('checks the deadline during CPU work', () => { + vi.useFakeTimers(); + try { + withGitWorkBudget(limits, () => { + chargeGitWork(1); + vi.advanceTimersByTime(1000); + expect(() => chargeGitWork(1)).toThrow('time budget'); + }); + } finally { + vi.useRealTimers(); + } + }); + + it('cancels a stalled upload instead of retaining the receive lock', async () => { + vi.useFakeTimers(); + const cancel = vi.fn(); + try { + const reader = new ReadableStream({ cancel }).getReader(); + const result = withGitWorkBudget(limits, () => readGitChunk(reader)); + const rejected = expect(result).rejects.toThrow('time budget'); + await vi.advanceTimersByTimeAsync(1000); + await rejected; + expect(cancel).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts index 233f69da31..07b521d8ba 100644 --- a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts @@ -11,8 +11,8 @@ * them: it imports `selfhost/build.ts`, whose graph the walker must see, so this guard cannot * pass because the walker went blind. */ -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { relative, resolve } from 'node:path'; import * as TOML from '@iarna/toml'; import { describe, expect, it } from 'vitest'; @@ -42,6 +42,24 @@ function celldEntryImports(): string[] { const GRAPH_WALK_TIMEOUT_MS = 60_000; describe('self-host-only code stays out of the Cloudflare Worker', () => { + it('detects real imports of the hosted DO, vendored git and pako', () => { + const scratchRoot = resolve(REPO_ROOT, '.tmp'); + mkdirSync(scratchRoot, { recursive: true }); + const scratch = mkdtempSync(resolve(scratchRoot, 'hosted-git-graph-')); + const entry = resolve(scratch, 'entry.ts'); + const doPath = 'apps/api/src/selfhost/hosted-git/hosted-git-repo.ts'; + try { + writeFileSync(entry, `import '${relative(scratch, resolve(REPO_ROOT, doPath))}';`); + const graph = collectImportGraph(entry); + const findings = selfhostOnlyFindings(graph, CLOUDFLARE_ENTRY_FORBIDDEN_PATHS); + expect(findings).toContain(doPath); + expect(findings.some((path) => path.startsWith('apps/api/src/vendor/dgit/'))).toBe(true); + expect(findings.some((path) => path.startsWith('package pako '))).toBe(true); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + }); + it( 'the shared entry reaches no self-host-only module, package or script', { timeout: GRAPH_WALK_TIMEOUT_MS }, diff --git a/apps/api/tests/unit/services/hosted-git-backend.test.ts b/apps/api/tests/unit/services/hosted-git-backend.test.ts index ba87fa85e5..8aeb198998 100644 --- a/apps/api/tests/unit/services/hosted-git-backend.test.ts +++ b/apps/api/tests/unit/services/hosted-git-backend.test.ts @@ -16,7 +16,7 @@ import { isArtifactsAvailable, registerArtifactsBackendFallback, resolveArtifactsBackend, -} from '../../../src/services/hosted-git/backend'; +} from '../../../src/services/artifacts/backend'; function backend(label: string): ArtifactsBackend { return { diff --git a/apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts b/apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts new file mode 100644 index 0000000000..c4688a65a4 --- /dev/null +++ b/apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest'; + +import type { HostedGitEnv as Env } from '../../../../src/selfhost/hosted-git/env'; +import { parseHostedGitPath } from '../../../../src/selfhost/hosted-git/http'; +import { + DEFAULT_HOSTED_GIT_LIMITS, + hostedGitPushByteBudget, + hostedGitPushRefusal, +} from '../../../../src/selfhost/hosted-git/limits'; +import { + createDurableObjectArtifactsBackend, + isLocalHostedGitActive, + localHostedGitBackendFallback, +} from '../../../../src/selfhost/hosted-git/local-backend'; +import { + clampHostedGitTokenTtl, + MAX_HOSTED_GIT_TOKEN_TTL_SECONDS, + mintHostedGitToken, + verifyHostedGitToken, +} from '../../../../src/selfhost/hosted-git/tokens'; +import { + isArtifactsAvailable, + registerArtifactsBackendFallback, + resolveArtifactsBackend, +} from '../../../../src/services/artifacts/backend'; + +const env = { ENCRYPTION_KEY: 'test-encryption-key-for-hosted-git' }; +const otherEnv = { ENCRYPTION_KEY: 'a-different-installation-key' }; + +describe('hosted git tokens', () => { + it('round-trips repo, scope, expiry and workspace binding', async () => { + const now = Date.UTC(2026, 10, 12); + const { token, expiresAt } = await mintHostedGitToken( + env, + { repo: 'demo-01abc', scope: 'write', ttlSeconds: 600, workspaceId: 'ws-1' }, + now + ); + expect(token.startsWith('samgit1.')).toBe(true); + expect(expiresAt).toBe(new Date(now + 600_000).toISOString()); + await expect(verifyHostedGitToken(env, token, now)).resolves.toEqual({ + repo: 'demo-01abc', + scope: 'write', + exp: now / 1000 + 600, + workspaceId: 'ws-1', + callbackGeneration: null, + }); + }); + + it('rejects expired, tampered and foreign-key tokens', async () => { + const now = Date.UTC(2026, 10, 12); + const { token } = await mintHostedGitToken( + env, + { repo: 'demo-01abc', scope: 'read', ttlSeconds: 60 }, + now + ); + await expect(verifyHostedGitToken(env, token, now + 61_000)).resolves.toBeNull(); + await expect(verifyHostedGitToken(otherEnv, token, now)).resolves.toBeNull(); + const [prefix, payload, signature] = token.split('.') as [string, string, string]; + const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()); + const forged = Buffer.from(JSON.stringify({ ...claims, scope: 'write' })).toString('base64url'); + await expect( + verifyHostedGitToken(env, `${prefix}.${forged}.${signature}`, now) + ).resolves.toBeNull(); + await expect(verifyHostedGitToken(env, 'not-a-token', now)).resolves.toBeNull(); + // Control: the untouched token verifies. + await expect(verifyHostedGitToken(env, token, now)).resolves.not.toBeNull(); + }); + + it('clamps the TTL to 1 s..24 h with a 1 h default', () => { + expect(clampHostedGitTokenTtl(undefined)).toBe(3600); + expect(clampHostedGitTokenTtl(-5)).toBe(3600); + expect(clampHostedGitTokenTtl(Number.NaN)).toBe(3600); + expect(clampHostedGitTokenTtl(10 * 86_400)).toBe(MAX_HOSTED_GIT_TOKEN_TTL_SECONDS); + expect(clampHostedGitTokenTtl(0.5)).toBe(1); + }); + + it('refuses to mint for a name SAM would never generate', async () => { + await expect(mintHostedGitToken(env, { repo: '../etc', scope: 'read' })).rejects.toThrow(); + }); +}); + +describe('hosted git path parsing', () => { + it('accepts /git/.git/ and rejects anything else', () => { + expect(parseHostedGitPath('/git/demo-01abc.git/info/refs')).toEqual({ + repo: 'demo-01abc', + subPath: '/info/refs', + }); + expect(parseHostedGitPath('/git/demo-01abc/git-upload-pack')?.repo).toBe('demo-01abc'); + expect(parseHostedGitPath('/git/Demo/info/refs')).toBeNull(); + expect(parseHostedGitPath('/git/../x/info/refs')).toBeNull(); + expect(parseHostedGitPath('/api/git/demo/info/refs')).toBeNull(); + }); +}); + +describe('hosted git caps', () => { + const limits = DEFAULT_HOSTED_GIT_LIMITS; + it('refuses a push that would cross the object cap and allows one that fits', () => { + expect( + hostedGitPushRefusal({ objects: 100, bytes: 0 }, limits.maxRepoObjects - 100, limits) + ).toBeNull(); + expect( + hostedGitPushRefusal({ objects: 100, bytes: 0 }, limits.maxRepoObjects - 99, limits) + ).toContain(`${limits.maxRepoObjects}-object limit`); + }); + + it('refuses any push to a repository already at its storage cap', () => { + expect(hostedGitPushRefusal({ objects: 1, bytes: limits.maxRepoBytes }, 1, limits)).toContain( + 'storage limit' + ); + }); + + it('shrinks the per-push byte budget as the repository fills', () => { + expect(hostedGitPushByteBudget(0, limits)).toBe(limits.maxPushBytes); + expect(hostedGitPushByteBudget(limits.maxRepoBytes - 10, limits)).toBe(10); + expect(hostedGitPushByteBudget(limits.maxRepoBytes + 10, limits)).toBe(0); + }); +}); + +describe('backend resolution', () => { + const namespace = {} as DurableObjectNamespace; + const cloudflareBinding = { create: async () => ({}) } as never; + + it('keeps Cloudflare Artifacts when the binding exists, even with the hosted backend configured', () => { + const cf = { + ARTIFACTS_ENABLED: 'true', + ARTIFACTS: cloudflareBinding, + HOSTED_GIT: namespace, + HOSTED_GIT_BACKEND: 'durable-object', + BASE_DOMAIN: 'example.com', + }; + expect(resolveArtifactsBackend(cf)).toBe(cloudflareBinding); + expect(isLocalHostedGitActive(cf)).toBe(false); + }); + + it('is unavailable on Cloudflare installs without the binding or the backend switch', () => { + // Defense in depth: even with a HOSTED_GIT namespace present (only the self-host build binds + // it), the switch and ARTIFACTS_ENABLED must both select it. + expect( + isArtifactsAvailable({ + ARTIFACTS_ENABLED: 'true', + HOSTED_GIT: namespace, + BASE_DOMAIN: 'example.com', + }) + ).toBe(false); + expect( + isArtifactsAvailable({ + ARTIFACTS_ENABLED: 'false', + HOSTED_GIT: namespace, + HOSTED_GIT_BACKEND: 'durable-object', + BASE_DOMAIN: 'example.com', + }) + ).toBe(false); + }); + + it('resolves the local backend on self-host and builds remotes under api.', async () => { + const selfhost = { + ARTIFACTS_ENABLED: 'true', + HOSTED_GIT: namespace, + HOSTED_GIT_BACKEND: 'durable-object', + BASE_DOMAIN: 'box.example', + }; + // Only the self-host build registers the local backend (selfhost/hosted-git.ts). + expect(isArtifactsAvailable(selfhost as unknown as Env)).toBe(false); + registerArtifactsBackendFallback(localHostedGitBackendFallback); + try { + expect(isArtifactsAvailable(selfhost as unknown as Env)).toBe(true); + expect(isLocalHostedGitActive(selfhost)).toBe(true); + expect(resolveArtifactsBackend(selfhost as unknown as Env)).not.toBeNull(); + expect(typeof createDurableObjectArtifactsBackend(selfhost).get).toBe('function'); + } finally { + registerArtifactsBackendFallback(null); + } + }); +}); + +describe('workspace identity through the generic backend seam', () => { + it('binds a repository credential to its user and current workspace generation', async () => { + const backend = createDurableObjectArtifactsBackend({ + ...env, + BASE_DOMAIN: 'example.test', + HOSTED_GIT_BACKEND: 'durable-object', + HOSTED_GIT: { + idFromName: (name: string) => name, + get: () => ({ fetch: async () => Response.json({ head: 'refs/heads/main' }) }), + }, + } as unknown as Env); + const repo = await backend.get('demo-01abc'); + const result = await repo.createToken('write', 60, { + userId: 'u1', + workspaceId: 'w1', + callbackGeneration: 'g2', + }); + const claims = await verifyHostedGitToken(env, result.plaintext); + expect(claims).toMatchObject({ + repo: 'demo-01abc', + scope: 'write', + userId: 'u1', + workspaceId: 'w1', + callbackGeneration: 'g2', + }); + }); +}); diff --git a/apps/api/vitest.hosted-git.config.ts b/apps/api/vitest.hosted-git.config.ts new file mode 100644 index 0000000000..5bcff41262 --- /dev/null +++ b/apps/api/vitest.hosted-git.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vitest/config'; + +/** + * Hosted git conformance: the real git CLI against the HostedGitRepo Durable Object running in + * Miniflare (tests/hosted-git/support/hosted-git-runtime.ts). Needs `git` on PATH. + */ +export default defineConfig({ + test: { + include: ['tests/hosted-git/**/*.test.ts'], + testTimeout: 120_000, + hookTimeout: 120_000, + fileParallelism: false, + }, +}); diff --git a/packages/repo-hosting/src/env.ts b/packages/repo-hosting/src/env.ts index fed4cd1c50..f9c99e4648 100644 --- a/packages/repo-hosting/src/env.ts +++ b/packages/repo-hosting/src/env.ts @@ -1,5 +1,24 @@ /** The Cloudflare Artifacts binding (SAM-native Git repositories). */ +/** Identity of the caller minting a repository credential. Backends may bind it to a runtime. */ +export interface ArtifactsTokenContext { + userId: string; + workspaceId?: string; + callbackGeneration?: string | null; +} + export type ArtifactsBinding = { + /** Optional in-process transport registered by a self-host backend. */ + remoteFetch?: typeof fetch; + /** Optional import capability; absent on the Cloudflare binding. */ + importSource?: { + defaultBranch(sourceUrl: string): Promise; + populate(params: { + sourceUrl: string; + branch: string; + remote: string; + token: string; + }): Promise; + }; create( name: string, opts?: { description?: string; setDefaultBranch?: string } @@ -18,7 +37,8 @@ export type ArtifactsBinding = { defaultBranch: string; createToken( scope?: 'read' | 'write', - ttl?: number + ttl?: number, + context?: ArtifactsTokenContext ): Promise<{ id: string; plaintext: string; diff --git a/packages/repo-hosting/src/index.ts b/packages/repo-hosting/src/index.ts index 2a2f62c9d1..408fbf2c39 100644 --- a/packages/repo-hosting/src/index.ts +++ b/packages/repo-hosting/src/index.ts @@ -64,3 +64,6 @@ export { verifyGitLabProjectAccess, } from './gitlab'; export { type RepoBrowser, resolveRepoBrowser } from './repo-browse'; + +export { createFetchHttpClient } from './repo-browse/fetch-http-client'; +export { MemoryFS } from './repo-browse/memory-fs'; diff --git a/packages/repo-hosting/src/ports.ts b/packages/repo-hosting/src/ports.ts index 5cc25faf79..20dc76b25c 100644 --- a/packages/repo-hosting/src/ports.ts +++ b/packages/repo-hosting/src/ports.ts @@ -45,7 +45,7 @@ export interface AuthPort { /** * The SAM-native repository backend (`ARTIFACTS`). On Cloudflare it is the Artifacts binding; a - * self-hosted install may register its own (the worker's `services/hosted-git/backend.ts`). + * self-hosted install may register its own (the worker's `services/artifacts/backend.ts`). */ export interface ArtifactsBackendPort { /** The backend this install uses for SAM-native repositories, or null when it has none. */ diff --git a/packages/repo-hosting/src/repo-browse/artifacts.ts b/packages/repo-hosting/src/repo-browse/artifacts.ts index 1fa437ea6b..781f97ad80 100644 --- a/packages/repo-hosting/src/repo-browse/artifacts.ts +++ b/packages/repo-hosting/src/repo-browse/artifacts.ts @@ -9,7 +9,8 @@ import type { import { errors } from '@simple-agent-manager/worker-core'; import { createPatch } from 'diff'; import git from 'isomorphic-git'; -import http from 'isomorphic-git/http/web'; +import webHttp from 'isomorphic-git/http/web'; +import { createFetchHttpClient } from './fetch-http-client'; import type { Env } from '../env'; import { repoHostingPorts } from '../ports'; @@ -27,6 +28,7 @@ type OnAuth = Parameters[0]['onAuth']; interface ArtifactsRepoInfo { remote: string; onAuth: OnAuth; + http: Parameters[0]['http']; } function countPatchLines(patch: string): { additions: number; deletions: number } { @@ -177,7 +179,11 @@ export class ArtifactsRepoBrowser implements RepoBrowser { if (!remote) { throw errors.badRequest('Artifacts repository has no resolvable clone URL'); } - return { remote, onAuth }; + return { + remote, + onAuth, + http: binding.remoteFetch ? createFetchHttpClient(binding.remoteFetch) : webHttp, + }; })(); } return this.infoPromise; @@ -185,7 +191,7 @@ export class ArtifactsRepoBrowser implements RepoBrowser { /** Shallow single-branch clone of `ref` into a fresh in-memory fs. */ private async cloneRef(ref: string): Promise { - const { remote, onAuth } = await this.info(); + const { remote, onAuth, http } = await this.info(); const fs = new MemoryFS() as unknown as IsoFs; // noCheckout: we read objects via walk/readBlob, never the working tree — this // avoids writing a second copy of every blob into the in-memory fs. @@ -204,7 +210,7 @@ export class ArtifactsRepoBrowser implements RepoBrowser { } async listBranches(): Promise { - const { remote, onAuth } = await this.info(); + const { remote, onAuth, http } = await this.info(); const refs = await git.listServerRefs({ http, url: remote, @@ -262,7 +268,7 @@ export class ArtifactsRepoBrowser implements RepoBrowser { } async compare(base: string, head: string): Promise { - const { remote, onAuth } = await this.info(); + const { remote, onAuth, http } = await this.info(); const fs = new MemoryFS() as unknown as IsoFs; await git.clone({ fs, diff --git a/packages/repo-hosting/src/repo-browse/fetch-http-client.ts b/packages/repo-hosting/src/repo-browse/fetch-http-client.ts new file mode 100644 index 0000000000..5f248dac49 --- /dev/null +++ b/packages/repo-hosting/src/repo-browse/fetch-http-client.ts @@ -0,0 +1,61 @@ +/** + * An isomorphic-git HTTP client over an injected fetch. `isomorphic-git/http/web` always uses the + * global fetch; SAM-hosted repositories are browsed in-process (`artifactsRemoteFetch`), so the + * browser needs a client that takes the fetch as a parameter. Same request/response contract as + * `isomorphic-git/http/web`. + */ +import type { HttpClient } from 'isomorphic-git'; + +async function collect(body: AsyncIterableIterator | undefined): Promise { + if (!body) return new Uint8Array(0); + const parts: Uint8Array[] = []; + let size = 0; + for await (const part of body) { + parts.push(part); + size += part.byteLength; + } + const out = new Uint8Array(size); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.byteLength; + } + return out; +} + +async function* streamChunks( + stream: ReadableStream | null +): AsyncGenerator { + if (!stream) return; + const reader = stream.getReader(); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) return; + if (value) yield value; + } + } finally { + reader.releaseLock(); + } +} + +export function createFetchHttpClient(fetchImpl: typeof fetch): HttpClient { + return { + async request({ url, method = 'GET', headers = {}, body }) { + const payload = body ? await collect(body) : undefined; + const res = await fetchImpl(url, { method, headers, body: payload }); + const responseHeaders: Record = {}; + res.headers.forEach((value, key) => { + responseHeaders[key] = value; + }); + return { + url: res.url || url, + method, + statusCode: res.status, + statusMessage: res.statusText, + body: streamChunks(res.body), + headers: responseHeaders, + }; + }, + }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1c8f15aa9a..7a7d450392 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -324,6 +324,9 @@ importers: jose: specifier: 'catalog:' version: 6.2.3 + pako: + specifier: ^2.1.0 + version: 2.2.0 tsx: specifier: 'catalog:' version: 4.23.1 @@ -352,6 +355,9 @@ importers: '@types/diff': specifier: ^8.0.0 version: 8.0.0 + '@types/pako': + specifier: ^2.0.3 + version: 2.0.4 '@typescript-eslint/eslint-plugin': specifier: 'catalog:' version: 8.72.0(@typescript-eslint/parser@8.72.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) @@ -5002,6 +5008,9 @@ packages: '@types/node@26.5.0': resolution: {integrity: sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A==} + '@types/pako@2.0.4': + resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/prismjs@1.26.6': resolution: {integrity: sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==} @@ -8334,6 +8343,9 @@ packages: pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + pako@2.2.0: + resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -13529,6 +13541,8 @@ snapshots: dependencies: undici-types: 8.9.0 + '@types/pako@2.0.4': {} + '@types/prismjs@1.26.6': {} '@types/react-dom@19.3.0(@types/react@19.3.0)': @@ -17743,6 +17757,8 @@ snapshots: pako@1.0.11: {} + pako@2.2.0: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 diff --git a/scripts/selfhost/hosted-git-smoke.sh b/scripts/selfhost/hosted-git-smoke.sh new file mode 100755 index 0000000000..e9e18030b2 --- /dev/null +++ b/scripts/selfhost/hosted-git-smoke.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Smoke test for SAM-hosted repositories on a self-hosted box. +# +# SAM_DOMAIN=vmtest.sam2.party SAM_API_TOKEN=sam_... scripts/selfhost/hosted-git-smoke.sh +# +# Inputs (environment): +# SAM_DOMAIN the box's SAM_DOMAIN (api. must answer) +# SAM_API_TOKEN an API token of an email-only account (Settings -> API tokens), exchanged +# for a session cookie via POST /api/auth/token-login. Never printed. +# SAM_INSECURE=1 optional: skip TLS verification (SAM_TLS_MODE=internal boxes) +# SMOKE_IMPORT_URL optional: also create a project imported from this public repository +# (github.com, gitlab.com, codeberg.org or bitbucket.org), then clone it +# SMOKE_RUN_TASK=1 optional: also submit an agent task that commits and pushes a branch from +# a workspace, then wait for that branch (SMOKE_TASK_TIMEOUT_S, default 1200) +# +# Steps: capability on -> create an artifacts project -> member token -> clone (README) -> +# push a branch -> fresh clone sees it -> unauthenticated clone refused -> (optional) workspace +# task pushes a branch. Exits non-zero on the first failure. +set -euo pipefail + +: "${SAM_DOMAIN:?set SAM_DOMAIN}" +: "${SAM_API_TOKEN:?set SAM_API_TOKEN}" +API="https://api.${SAM_DOMAIN}" +WORK="$(mktemp -d)" +JAR="${WORK}/cookies" +trap 'rm -rf "$WORK"' EXIT + +CURL=(curl -fsS --max-time 60 -b "$JAR" -c "$JAR") +GIT=(git -c credential.helper= -c gc.auto=0) +if [[ "${SAM_INSECURE:-}" == "1" ]]; then + CURL+=(-k) + GIT+=(-c http.sslVerify=false) +fi +export GIT_TERMINAL_PROMPT=0 GIT_AUTHOR_NAME=smoke GIT_AUTHOR_EMAIL=smoke@example.com \ + GIT_COMMITTER_NAME=smoke GIT_COMMITTER_EMAIL=smoke@example.com + +step() { printf '\n== %s\n' "$*"; } +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +json() { python3 -c "import json,sys; print(json.load(sys.stdin)$1)"; } +# A remote URL with the token as the Basic password (never echoed). +authed() { python3 -c "import sys,urllib.parse as u; p=u.urlsplit(sys.argv[1]); print(u.urlunsplit((p.scheme,'x:'+u.quote(sys.argv[2],safe='')+'@'+p.netloc,p.path,'','')))" "$1" "$2"; } + +step "sign in with the API token" +# The token goes through stdin so it never appears in the process list. +python3 -c 'import json,os; print(json.dumps({"token": os.environ["SAM_API_TOKEN"]}))' | + "${CURL[@]}" -X POST -H 'content-type: application/json' --data @- \ + "${API}/api/auth/token-login" >/dev/null + +step "SAM-native repositories are enabled" +enabled="$("${CURL[@]}" "${API}/api/config/artifacts-enabled" | json "['enabled']")" +[[ "$enabled" == "True" ]] || fail "artifacts-enabled is $enabled (redeploy with this branch)" + +step "create a project with a SAM-hosted repository" +name="hosted-smoke-$(date +%s)" +project="$("${CURL[@]}" -X POST -H 'content-type: application/json' \ + -d "{\"name\":\"${name}\",\"repoProvider\":\"artifacts\",\"description\":\"hosted git smoke\"}" \ + "${API}/api/projects")" +project_id="$(json "['id']" <<<"$project")" +remote="$(json "['repository']" <<<"$project")" +echo "project ${project_id} remote ${remote}" +[[ "$remote" == "${API}/git/"* ]] || fail "unexpected remote ${remote}" + +step "member write token, clone, README present" +token="$("${CURL[@]}" -X POST "${API}/api/projects/${project_id}/hosted-git/token?scope=write" | json "['token']")" +"${GIT[@]}" clone -q "$(authed "$remote" "$token")" "${WORK}/clone" +grep -q "$name" "${WORK}/clone/README.md" || fail "seeded README missing" + +step "push a branch" +(cd "${WORK}/clone" && git checkout -q -b smoke/human && echo "pushed $(date -u)" >smoke.txt && + git add smoke.txt && git commit -qm "smoke push" && "${GIT[@]}" push -q origin smoke/human) + +step "fresh clone sees the branch" +"${GIT[@]}" clone -q --branch smoke/human "$(authed "$remote" "$token")" "${WORK}/verify" +[[ -f "${WORK}/verify/smoke.txt" ]] || fail "pushed file missing" + +step "unauthenticated clone is refused" +if "${GIT[@]}" clone -q "$remote" "${WORK}/anon" 2>/dev/null; then fail "anonymous clone succeeded"; fi +echo "refused as expected" + +if [[ -n "${SMOKE_IMPORT_URL:-}" ]]; then + step "import ${SMOKE_IMPORT_URL}" + imported="$(python3 -c 'import json,os,sys; print(json.dumps({"name": sys.argv[1], "repoProvider": "artifacts", "importUrl": os.environ["SMOKE_IMPORT_URL"]}))' "${name}-import" | + "${CURL[@]}" -X POST -H 'content-type: application/json' --data @- "${API}/api/projects")" + imported_id="$(json "['id']" <<<"$imported")" + imported_remote="$(json "['repository']" <<<"$imported")" + itoken="$("${CURL[@]}" -X POST "${API}/api/projects/${imported_id}/hosted-git/token" | json "['token']")" + "${GIT[@]}" clone -q "$(authed "$imported_remote" "$itoken")" "${WORK}/imported" + echo "imported HEAD $(git -C "${WORK}/imported" log -1 --format='%h %s')" +fi + +if [[ "${SMOKE_RUN_TASK:-}" == "1" ]]; then + step "workspace task clones and pushes (provisions a node; minutes)" + "${CURL[@]}" -X POST -H 'content-type: application/json' \ + -d '{"message":"Create a file named agent-smoke.txt containing the word hello, commit it, and run: git push origin HEAD:refs/heads/smoke/agent . Reply done when the push succeeds."}' \ + "${API}/api/projects/${project_id}/tasks/submit" >/dev/null + deadline=$(( $(date +%s) + ${SMOKE_TASK_TIMEOUT_S:-1200} )) + until "${GIT[@]}" ls-remote "$(authed "$remote" "$token")" refs/heads/smoke/agent | grep -q smoke/agent; do + (( $(date +%s) < deadline )) || fail "workspace never pushed smoke/agent (check the task in the UI)" + sleep 20 + done + echo "workspace pushed smoke/agent" +fi + +printf '\nPASS: SAM-hosted repository smoke (project %s)\n' "$project_id" diff --git a/scripts/selfhost/selfhost-durable-objects.ts b/scripts/selfhost/selfhost-durable-objects.ts new file mode 100644 index 0000000000..19569d2102 --- /dev/null +++ b/scripts/selfhost/selfhost-durable-objects.ts @@ -0,0 +1,74 @@ +/** + * Durable Objects only the self-host (celld) build has. + * + * `apps/api/wrangler.toml` is the Cloudflare Worker's configuration and must not name these + * classes: a Cloudflare Durable Object migration cannot be taken back, and the Cloudflare bundle + * must not carry their code. The celld config (`buildCelldConfig`) appends each one's binding + * and migration after wrangler.toml's, and the generated celld entry (`celld-project.ts`) exports + * the class from `SELFHOST_ENTRY_MODULE`, which the shared entry `apps/api/src/index.ts` never + * imports. Today that module is hosted git's; a second self-host-only class must be exported from + * the same module (tests/unit/selfhost/selfhost-only-modules.test.ts checks every class is). + * + * celld 0.6.3 validates migrations declaratively (a tag or a class may appear once; a class with + * storage must be declared in `new_sqlite_classes`). Observed with `celld dev`, which keeps state + * across restarts: an object written while this class was wrangler.toml's `v23` keeps its data + * once the class is declared under this tag. Bucket-mode `celld deploy` over an existing box is not + * yet verified (task tasks/archive/2026-11-15-hosted-git-selfhost-only-build.md). + */ + +export interface SelfhostDurableObject { + /** Worker binding name (`Env.HOSTED_GIT`). */ + binding: string; + /** Class exported by `SELFHOST_ENTRY_MODULE`. */ + className: string; + /** celld migration tag; distinct from wrangler.toml's `vN` tags so the two never collide. */ + migrationTag: string; +} + +/** The module under apps/api/src that the generated celld entry imports for these classes. */ +export const SELFHOST_ENTRY_MODULE = 'selfhost/build.ts'; + +/** Function in `SELFHOST_ENTRY_MODULE` the entry calls with the shared Hono app. */ + +export const SELFHOST_DURABLE_OBJECTS: readonly SelfhostDurableObject[] = [ + // SAM-hosted git repositories (one per repository); selfhost/hosted-git/backend.ts selects it + // with HOSTED_GIT_BACKEND=durable-object (SELFHOST_VAR_OVERRIDES). + { binding: 'HOSTED_GIT', className: 'HostedGitRepo', migrationTag: 'selfhost-hosted-git-v1' }, +]; + +interface DurableObjectConfig { + durable_objects: { bindings: Array<{ name: string; class_name: string }> }; + migrations: Array<{ tag: string; new_sqlite_classes: string[] }>; +} + +/** + * Appends every self-host-only binding and migration to a config translated from wrangler.toml. + * Throws when wrangler.toml already uses a binding name, class or tag, so the class cannot end up + * declared twice or back in the Cloudflare configuration unnoticed. + */ +export function appendSelfhostDurableObjects(config: DurableObjectConfig, report: string[]): void { + const bindings = new Set(config.durable_objects.bindings.map((b) => b.name)); + const classes = new Set([ + ...config.durable_objects.bindings.map((b) => b.class_name), + ...config.migrations.flatMap((m) => m.new_sqlite_classes), + ]); + const tags = new Set(config.migrations.map((m) => m.tag)); + for (const object of SELFHOST_DURABLE_OBJECTS) { + if ( + bindings.has(object.binding) || + classes.has(object.className) || + tags.has(object.migrationTag) + ) { + throw new Error( + `celld config: wrangler.toml declares ${object.binding}, ${object.className} or ` + + `${object.migrationTag}, which only the self-host build may declare ` + + '(scripts/selfhost/selfhost-durable-objects.ts)' + ); + } + config.durable_objects.bindings.push({ name: object.binding, class_name: object.className }); + config.migrations.push({ tag: object.migrationTag, new_sqlite_classes: [object.className] }); + report.push( + `self-host Durable Object ${object.binding} (${object.className}), migration ${object.migrationTag}` + ); + } +} diff --git a/tasks/backlog/2026-11-19-bounded-selfhost-git-import.md b/tasks/backlog/2026-11-19-bounded-selfhost-git-import.md new file mode 100644 index 0000000000..98f5a7e925 --- /dev/null +++ b/tasks/backlog/2026-11-19-bounded-selfhost-git-import.md @@ -0,0 +1,8 @@ +# Bound self-host git imports before enabling them + +H2 security review found that a compressed-response cap around isomorphic-git's in-memory clone does not bound inflated objects or delta allocations. A small public pack can exhaust the shared celld process before MemoryFS observes a write. Coordinator approved empty seeded repositories only for H2 on 2026-11-19 (message f52622cf-1aff-4052-9bde-67766706e15e); the generic import capability remains unregistered and importUrl is refused with 400. + +- [ ] Design an importer enforcing object, cumulative decompression, delta depth, CPU/time and transport bounds before allocation (reuse hosted DO policy or isolated bounded execution). +- [ ] Preserve public-forge HTTPS allowlisting, redirect refusal, no embedded credentials and cleanup on refusal. +- [ ] Exercise compressed-bomb and stalled-source refusals, plus successful history/default-branch import through real project creation. +- [ ] Register the fallback import capability only when those tests and live self-host verification pass; document supported limits. From 53962520254695df0ec3c700fd8e2ff44fbf76e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:24:24 +0000 Subject: [PATCH 36/65] fix(selfhost): refuse stale pool bindings; list-form build args; README compose cwd Codex review on 3e3ef8d30: - GCP bootstrap (P1): add-iam-policy-binding only adds a member, so a node account reused after a --pool-id change stayed impersonable through the old pool. Refuse while any other member holds workloadIdentityUser, with the remove-iam-policy-binding command. - imageRebuilds: normalise list-form build args to a mapping before the merge by name, so a base-only arg change still rebuilds. - README fresh install: run compose from deploy/selfhost so .env's COMPOSE_FILE overlays apply (a -f replaces them). Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 11 ++++---- deploy/selfhost/gcp-bootstrap.sh | 16 +++++++++-- scripts/selfhost/gcp-bootstrap.test.ts | 27 +++++++++++++++++++ scripts/selfhost/image-rebuilds.ts | 23 +++++++++++++++- scripts/selfhost/testdata/fake-gcloud-iam.mjs | 15 +++++++++-- scripts/selfhost/upgrade.test.ts | 12 +++++++++ 6 files changed, 94 insertions(+), 10 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 3702144c14..e875c139a6 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -53,11 +53,12 @@ From the repository root on the VM: 4. `pnpm selfhost:deploy --init`: generates the platform keys (`.state/platform-keys.json`; back it up), `.state/gateway.env` (the reverse-tunnel gateway secret and lease port range) and the mail-collector files. Run it again after changing the port range or turning a profile on. -5. `docker compose -f deploy/selfhost/docker-compose.yml --env-file deploy/selfhost/.env build`: - builds the two local images (`caddy`, and `sam-mx` when `mail-in` is on). See - [Image builds](#image-builds). -6. `docker compose -f deploy/selfhost/docker-compose.yml --env-file deploy/selfhost/.env up -d` - (or run `docker compose build` / `up -d` from inside `deploy/selfhost/`, which reads `.env`). +5. `(cd deploy/selfhost && docker compose build)`: builds the two local images (`caddy`, and + `sam-mx` when `mail-in` is on). See [Image builds](#image-builds). +6. `(cd deploy/selfhost && docker compose up -d)`. Run compose from `deploy/selfhost/`, as every + compose command in this README assumes: there it reads `.env`, including any `COMPOSE_FILE` + overlays and `COMPOSE_PROFILES`. A `-f` on the command line replaces `COMPOSE_FILE`, which would + drop your overlays. 7. `pnpm selfhost:deploy`: builds the web UI, the API Worker's dependencies and the vm-agent (in a pinned Go image), publishes the vm-agent to the bucket, applies D1 migrations and runs `celld deploy`, then waits until the new version answers. diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh index 584eb0f5a0..5b6c4c9e5c 100755 --- a/deploy/selfhost/gcp-bootstrap.sh +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -257,9 +257,21 @@ done # credential and no user's. SAM also refuses a user credential that names a pool the platform # credential holds (gcp-wif-pool-ownership.ts). Any provider added to this pool later would # inherit the service account too, so do not add providers to it. +POOL_PRINCIPAL="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" +# add-iam-policy-binding only adds a member: an account reused after a --pool-id change (or one +# granted elsewhere) would still be impersonable through the old member. Refuse while any other +# member holds workloadIdentityUser on it; revoking is the operator's decision. +if exists iam service-accounts describe "$SA_EMAIL" --project="$PROJECT"; then + wi_members="$(gcloud iam service-accounts get-iam-policy "$SA_EMAIL" --project="$PROJECT" \ + --flatten='bindings[].members' --filter='bindings.role=roles/iam.workloadIdentityUser' \ + --format='value(bindings.members)')" || die "cannot read the IAM policy of ${SA_EMAIL}" + while IFS= read -r member; do + [[ -z "$member" || "$member" == "$POOL_PRINCIPAL" ]] && continue + die "service account ${SA_EMAIL} can also be impersonated by ${member} (roles/iam.workloadIdentityUser), which this install does not use. Remove it: gcloud iam service-accounts remove-iam-policy-binding ${SA_EMAIL} --project=${PROJECT} --role=roles/iam.workloadIdentityUser --member='${member}', then run this again; or pass --service-account ." + done <<<"$wi_members" +fi change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ - --role=roles/iam.workloadIdentityUser \ - --member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" \ + --role=roles/iam.workloadIdentityUser --member="$POOL_PRINCIPAL" \ --condition=None --quiet --format=none [[ "$DRY_RUN" -eq 1 ]] && echo "Dry run: nothing was changed." diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts index 5c8ae15e62..6844a89f67 100644 --- a/scripts/selfhost/gcp-bootstrap.test.ts +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -69,6 +69,7 @@ interface FakeGcp { >; accounts: Record; bindings: string[]; + saBindings?: Record; } function gcp(): FakeGcp { @@ -234,6 +235,32 @@ describe('pnpm selfhost:gcp-bootstrap', () => { ).toEqual([]); }); + // add-iam-policy-binding only adds a member: moving to a new --pool-id would leave the old + // pool's principalSet able to impersonate the reused node account. + it('a new --pool-id with the old pool still bound: stops with the remove command, binds nothing', () => { + expect( + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-old']).status + ).toBe(0); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-new']); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('workloadIdentityPools/sam-old/*'); + expect(result.stderr).toContain('remove-iam-policy-binding'); + expect( + result.calls + .slice(before) + .filter((c) => c.startsWith('iam service-accounts add-iam-policy-binding')) + ).toEqual([]); + }); + + it('control: the same pool on a re-run is not a stale member', () => { + expect( + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-old']).status + ).toBe(0); + const again = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-old']); + expect(again.status, again.stderr).toBe(0); + }); + it('a disabled service account: stops with the enable command, grants nothing', () => { expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); setGcp((db) => { diff --git a/scripts/selfhost/image-rebuilds.ts b/scripts/selfhost/image-rebuilds.ts index aad8a0986e..8913eafe6b 100644 --- a/scripts/selfhost/image-rebuilds.ts +++ b/scripts/selfhost/image-rebuilds.ts @@ -25,8 +25,29 @@ export interface ComposeOverlay { to: string | null; } +/** + * Build args as a mapping. Compose accepts a list (`- NAME=value`, or `- NAME` for a value taken + * from the environment) or a mapping, and merges them by name across files whichever form each + * file uses. + */ +function argsMap(args: unknown): Record | undefined { + if (Array.isArray(args)) { + const map: Record = {}; + for (const entry of args) { + const text = String(entry); + const separator = text.indexOf('='); + if (separator < 0) map[text] = null; + else map[text.slice(0, separator)] = text.slice(separator + 1); + } + return map; + } + return isJsonRecord(args) ? args : undefined; +} + function asSection(build: string | BuildSection): BuildSection { - return typeof build === 'string' ? { context: build } : { ...build }; + if (typeof build === 'string') return { context: build }; + const args = argsMap(build.args); + return { ...build, ...(args === undefined ? {} : { args }) }; } /** diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index c5f94a0bb9..3cdee20351 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -79,8 +79,19 @@ else if (cmd.startsWith('iam workload-identity-pools providers')) { db.pools[id] = { description: flag('description') }; save(); } else fail(`unexpected ${cmd}`); -} else if (cmd.startsWith('iam service-accounts add-iam-policy-binding')) save(); -else if (cmd.startsWith('iam service-accounts')) { +} else if (cmd.startsWith('iam service-accounts add-iam-policy-binding')) { + const email = words[3]; + db.saBindings = db.saBindings ?? {}; + const members = (db.saBindings[email] = db.saBindings[email] ?? []); + const member = flag('member'); + if (flag('role') === 'roles/iam.workloadIdentityUser' && !members.includes(member)) { + members.push(member); + } + save(); +} else if (cmd.startsWith('iam service-accounts get-iam-policy')) { + // --flatten bindings[].members --filter role=workloadIdentityUser --format value(members) + for (const member of db.saBindings?.[words[3]] ?? []) out(member); +} else if (cmd.startsWith('iam service-accounts')) { const [, , op, id] = words; const email = id.includes('@') ? id : `${id}@${flag('project')}.iam.gserviceaccount.com`; if (op === 'describe') { diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index f493e94ffd..7809a96671 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -604,6 +604,18 @@ describe('imageRebuilds', () => { expect(imageRebuilds([], null, COMPOSE())).toEqual(['caddy', 'sam-mx']); }); + // Compose merges build args by name whatever form each file uses (list or mapping). + it('merges list-form overlay args by name, so a base-only arg change still rebuilds', () => { + const listOverlay = 'services:\n caddy:\n build:\n args:\n - EXTRA=x\n'; + const overlays = [{ from: listOverlay, to: listOverlay }]; + expect(imageRebuilds([], COMPOSE('mod@v1'), COMPOSE('mod@v2'), () => null, overlays)).toEqual([ + 'caddy', + ]); + expect(imageRebuilds([], COMPOSE('mod@v1'), COMPOSE('mod@v1'), () => null, overlays)).toEqual( + [] + ); + }); + it('merges an overlay build section over the base one (args merge, keys replace)', () => { const tweak = 'services:\n caddy:\n build:\n args:\n EXTRA: x\n'; expect( From 75aeaea3b8af42343ad526c7ba3d58758982cb90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:28:57 +0000 Subject: [PATCH 37/65] fix: fence loose inflation and queued git collection --- .../routes/workspaces/runtime-git-token.ts | 4 +-- .../selfhost/hosted-git/hosted-git-repo.ts | 6 ++++ apps/api/src/services/artifacts/backend.ts | 12 +++++++ apps/api/src/vendor/dgit/git/packstore.ts | 15 +-------- apps/api/src/vendor/dgit/git/store.ts | 5 +++ apps/api/src/vendor/dgit/git/zlib.ts | 14 +++++++- .../unit/routes/artifacts-config.test.ts | 2 +- .../routes/project-artifacts-creation.test.ts | 2 +- .../tests/unit/routes/project-delete.test.ts | 2 +- .../unit/routes/workspace-git-token.test.ts | 2 +- .../unit/selfhost/hosted-git-budget.test.ts | 12 +++++++ .../selfhost/hosted-git-gc-admission.test.ts | 33 +++++++++++++++++++ 12 files changed, 88 insertions(+), 21 deletions(-) create mode 100644 apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index fa742fcdb6..bef752ec99 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -6,7 +6,7 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { errors } from '../../middleware/error'; -import { resolveArtifactsBackend } from '../../services/artifacts/backend'; +import { createArtifactsRuntimeToken, resolveArtifactsBackend } from '../../services/artifacts/backend'; import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; import { GitHubCliPolicyError, @@ -237,7 +237,7 @@ runtimeRoutes.post('/:id/git-token', async (c) => { const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); const repo = await artifacts.get(artifactsRepoId); await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const tokenResult = await repo.createToken(requestedScope, ttl, { + const tokenResult = await createArtifactsRuntimeToken(c.env, repo, requestedScope, ttl, { userId: workspace.userId, workspaceId: workspace.workspaceId, callbackGeneration: workspace.callbackGeneration ?? null, diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index 3d46ec3051..c741cf85f2 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -216,6 +216,12 @@ export class HostedGitRepo extends DurableObject { let result: HostedGitGcResult = { removed: 0, kept: 0 }; const run = this.receiveChain.then(() => this.ctx.blockConcurrencyWhile(async () => { + // Recheck after acquiring the push slot: a clone may have started while GC queued. + if (this.activeUploads > 0) { + this.store.setMeta('gc-pending', '1'); + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS); + return; + } result = await runHostedGitGc(this.store); }) ); diff --git a/apps/api/src/services/artifacts/backend.ts b/apps/api/src/services/artifacts/backend.ts index 40aa4feb0a..0950451dff 100644 --- a/apps/api/src/services/artifacts/backend.ts +++ b/apps/api/src/services/artifacts/backend.ts @@ -17,6 +17,18 @@ import type { Env } from '../../env'; export type ArtifactsBackend = NonNullable; +type ArtifactsRepo = Awaited>; + +/** Preserve the native binding's RPC contract; fallback tokens can bind runtime identity. */ +export function createArtifactsRuntimeToken( + env: Env, + repo: ArtifactsRepo, + scope: 'read' | 'write', + ttl: number, + context: NonNullable[2]> +): ReturnType { + return env.ARTIFACTS ? repo.createToken(scope, ttl) : repo.createToken(scope, ttl, context); +} /** Builds the fallback backend for an install with no Artifacts binding, or returns null. */ export type ArtifactsBackendFallback = (env: Env) => ArtifactsBackend | null; diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts index cca78d63cd..e4566b2571 100644 --- a/apps/api/src/vendor/dgit/git/packstore.ts +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -2,6 +2,7 @@ /* eslint-disable */ // FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) import pako from "pako"; +import { inflate as inflateAll } from "./zlib"; import { chargeGitWork, gitWorkLimits, readGitChunk } from "./budget"; import { td, concat, toHex, Sha1 } from "./util"; import { Sha1Dc, Sha1CollisionError } from "./sha1"; @@ -45,20 +46,6 @@ const RAW_CHUNK_CACHE = TIGHT_MEMORY ? 4 : 8; * size. */ const INFLATE_CHUNK = 16 * 1024; -const inflateAll = (data: Uint8Array): Uint8Array => { - const inf = new pako.Inflate({ chunkSize: INFLATE_CHUNK }); - const chunks: Uint8Array[] = []; - let size = 0; - inf.onData = (chunk: Uint8Array) => { - size += chunk.length; - if (size > gitWorkLimits().maxObjectBytes) throw new Error("git object exceeds inflated size limit"); - chargeGitWork(chunk.length); - chunks.push(chunk); - }; - inf.push(data, true); - if (inf.err) throw new Error(`inflate failed: ${inf.msg}`); - return concat(chunks); -}; export interface ObjRec { type: ObjType; diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index f7d2c3583a..3c855c9807 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -1,5 +1,6 @@ // @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +import { gitWorkLimits } from "./budget"; import { concat, te, sha1hex } from "./util"; import { deflate, inflate } from "./zlib"; import { ObjType } from "./objects"; @@ -115,6 +116,10 @@ export class GitStore { .exec<{ type: ObjType; size: number }>("SELECT type, size FROM objects WHERE oid = ?", oid) .toArray(); if (!rows.length) return null; + const size = rows[0].size; + if (!Number.isSafeInteger(size) || size < 0 || size > gitWorkLimits().maxObjectBytes) { + throw new Error("git object exceeds inflated size limit"); + } const chunks = this.sql .exec<{ data: ArrayBuffer }>("SELECT data FROM chunks WHERE oid = ? ORDER BY seq", oid) .toArray(); diff --git a/apps/api/src/vendor/dgit/git/zlib.ts b/apps/api/src/vendor/dgit/git/zlib.ts index dd5592f813..ab04541214 100644 --- a/apps/api/src/vendor/dgit/git/zlib.ts +++ b/apps/api/src/vendor/dgit/git/zlib.ts @@ -1,6 +1,7 @@ // @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ import pako from "pako"; +import { chargeGitWork, gitWorkLimits } from "./budget"; import { concat } from "./util"; /** Deflate with a zlib wrapper (what git uses for loose objects and pack entries). */ @@ -9,7 +10,18 @@ export function deflate(data: Uint8Array): Uint8Array { } export function inflate(data: Uint8Array): Uint8Array { - return pako.inflate(data); + const inf = new pako.Inflate({ chunkSize: 16 * 1024 }); + const parts: Uint8Array[] = []; + let size = 0; + inf.onData = (chunk: Uint8Array) => { + size += chunk.length; + if (size > gitWorkLimits().maxObjectBytes) throw new Error("git object exceeds inflated size limit"); + chargeGitWork(chunk.length); + parts.push(chunk); + }; + inf.push(data, true); + if (inf.err) throw new Error(`inflate failed: ${inf.msg}`); + return concat(parts); } /** diff --git a/apps/api/tests/unit/routes/artifacts-config.test.ts b/apps/api/tests/unit/routes/artifacts-config.test.ts index 1ac9911dd9..b48e703be4 100644 --- a/apps/api/tests/unit/routes/artifacts-config.test.ts +++ b/apps/api/tests/unit/routes/artifacts-config.test.ts @@ -13,7 +13,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import type { Env } from '../../../src/env'; import { artifactsConfigRoutes } from '../../../src/routes/artifacts-config'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; const app = new Hono<{ Bindings: Env }>(); app.route('/api/config', artifactsConfigRoutes); diff --git a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts index db8dd78d23..abd40073c5 100644 --- a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts +++ b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { AppError } from '../../../src/middleware/error'; import { registerProjectCreateRoute } from '../../../src/routes/projects/project-create'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; /** * The Artifacts branch of `POST /api/projects` resolves its backend through diff --git a/apps/api/tests/unit/routes/project-delete.test.ts b/apps/api/tests/unit/routes/project-delete.test.ts index 14a66c1a2d..ac40d8d477 100644 --- a/apps/api/tests/unit/routes/project-delete.test.ts +++ b/apps/api/tests/unit/routes/project-delete.test.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { projectsRoutes } from '../../../src/routes/projects'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; const mocks = vi.hoisted(() => ({ requireProjectCapability: vi.fn(), diff --git a/apps/api/tests/unit/routes/workspace-git-token.test.ts b/apps/api/tests/unit/routes/workspace-git-token.test.ts index c20c399168..8c4f88571e 100644 --- a/apps/api/tests/unit/routes/workspace-git-token.test.ts +++ b/apps/api/tests/unit/routes/workspace-git-token.test.ts @@ -6,7 +6,7 @@ import type { Env } from '../../../src/env'; import { runtimeRoutes } from '../../../src/routes/workspaces/runtime'; import { getInstallationToken } from '../../../src/services/github-app'; import { GitHubCliPolicyError } from '../../../src/services/github-cli-policy'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; const mocks = vi.hoisted(() => ({ getInstallationToken: vi.fn(), diff --git a/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts index 716a7d90e5..c7162e4ced 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts @@ -5,11 +5,23 @@ import { readGitChunk, withGitWorkBudget, } from '../../../src/vendor/dgit/git/budget'; +import { deflate, inflate } from '../../../src/vendor/dgit/git/zlib'; import { applyDelta } from '../../../src/vendor/dgit/git/pack'; const limits = { maxObjectBytes: 32, maxInflatedBytes: 48, maxDeltaDepth: 2, workTimeoutMs: 1000 }; describe('hosted git work budget', () => { + it('bounds loose-object reads after garbage collection and charges repeated inflations', () => { + const small = deflate(new Uint8Array(24)); + const large = deflate(new Uint8Array(33)); + withGitWorkBudget(limits, () => { + expect(() => inflate(large)).toThrow('inflated size limit'); + expect(inflate(small)).toHaveLength(24); + expect(inflate(small)).toHaveLength(24); + expect(() => inflate(small)).toThrow('decompression budget'); + }); + }); + it('rejects a delta target before allocation, while a valid delta works', () => { withGitWorkBudget(limits, () => { expect(() => applyDelta(new Uint8Array(), new Uint8Array([0, 33]))).toThrow( diff --git a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts new file mode 100644 index 0000000000..ac919c89f8 --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts @@ -0,0 +1,33 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo'; +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +const mocks = vi.hoisted(() => ({ pending: '1', gc: vi.fn(async () => ({ removed: 1, kept: 2 })), setAlarm: vi.fn(async () => undefined) })); +vi.mock('cloudflare:workers', () => ({ DurableObject: class { constructor(public ctx: unknown, public env: unknown) {} } })); +vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ resolveHostedGitLimits: async () => DEFAULT_HOSTED_GIT_LIMITS })); +vi.mock('../../../src/vendor/dgit/git/store', () => ({ GitStore: class { getMeta() { return mocks.pending; } setMeta(_key: string, value: string) { mocks.pending = value; } } })); +vi.mock('../../../src/selfhost/hosted-git/hosted-git-gc', () => ({ runHostedGitGc: mocks.gc })); +beforeEach(() => { mocks.pending = '1'; vi.clearAllMocks(); }); +describe('hosted git GC admission', () => { + it('rechecks uploads after waiting behind a push, and runs once after the upload leaves', async () => { + const ctx = { storage: { setAlarm: mocks.setAlarm }, blockConcurrencyWhile: async (action: () => Promise) => action() }; + const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); + // Hold the same promise-chain slot that receive-pack owns, exercising alarm's real queue. + let releasePush = () => {}; + const state = repo as unknown as { receiveChain: Promise; activeUploads: number }; + state.receiveChain = new Promise((resolve) => { releasePush = resolve; }); + const alarm = repo.alarm(); + await vi.waitFor(() => expect(mocks.pending).toBe('0')); + state.activeUploads = 1; + releasePush(); + await alarm; + expect(mocks.gc).not.toHaveBeenCalled(); + expect(mocks.pending).toBe('1'); + expect(mocks.setAlarm).toHaveBeenCalledOnce(); + state.activeUploads = 0; + await repo.alarm(); + expect(mocks.gc).toHaveBeenCalledOnce(); + expect(mocks.pending).toBe('0'); + await repo.alarm(); + expect(mocks.gc).toHaveBeenCalledOnce(); + }); +}); From 7f49d389c7035597e5550e0fa204d1b1aed2d1d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:33:00 +0000 Subject: [PATCH 38/65] feat: wire hosted git into celld build and migration registry --- apps/api/src/index.ts | 2 +- apps/api/src/selfhost/build.ts | 16 +++++++++++++- .../hosted-git/celld-entry-bundle.test.ts | 8 +++---- .../unit/selfhost/selfhost-build.test.ts | 5 +++-- deploy/selfhost/README.md | 22 +++++++++++++++---- scripts/selfhost/celld-config.test.ts | 17 +++++++------- scripts/selfhost/celld-config.ts | 4 ++++ scripts/selfhost/celld-project.test.ts | 8 +++---- scripts/selfhost/celld-project.ts | 10 ++++++--- scripts/selfhost/selfhost-durable-objects.ts | 4 +--- .../2026-11-19-selfhost-hosted-git-h2.md | 15 ++++++++----- 11 files changed, 75 insertions(+), 36 deletions(-) diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 760e30a8f0..650b30e954 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -191,7 +191,7 @@ import { agentEmailConfig } from './services/agent-email/setup-state'; import { isAgentSignInEnabled } from './services/agent-sign-in/config'; import { isInstantRuntimeAvailable } from './services/vm-agent-container'; -const app = new Hono<{ Bindings: Env }>(); +export const app = new Hono<{ Bindings: Env }>(); // Global error handler — catches errors from all routes including subrouters. // Must use app.onError() instead of middleware try/catch because Hono's diff --git a/apps/api/src/selfhost/build.ts b/apps/api/src/selfhost/build.ts index 9333894c4b..f106e77171 100644 --- a/apps/api/src/selfhost/build.ts +++ b/apps/api/src/selfhost/build.ts @@ -11,12 +11,26 @@ * with the shared cloud-init generator as the frpc boot renderer. */ import { generateCloudInit } from '@simple-agent-manager/cloud-init'; +import type { Hono } from 'hono'; + +import type { Env } from '../env'; +import { mountHostedGitRoute } from './hosted-git'; +import { hostedGitTokenRoutes } from './hosted-git/token-route'; + +export { HostedGitRepo } from './hosted-git'; import { installAnalyticsD1Sink } from './analytics'; import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry'; import { installSpeechEndpoints } from './speech'; -export function withSelfHostBuild(worker: T): T { +const mounted = new WeakSet(); + +export function withSelfHostBuild(worker: T, app: Hono<{ Bindings: Env }>): T { + if (!mounted.has(app)) { + mountHostedGitRoute(app); + app.route('/api/projects', hostedGitTokenRoutes); + mounted.add(app); + } installSpeechEndpoints(); installAnalyticsD1Sink(); return withReverseTunnel(worker, generateCloudInit); diff --git a/apps/api/tests/hosted-git/celld-entry-bundle.test.ts b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts index 3e9715f5d9..2aa47885f4 100644 --- a/apps/api/tests/hosted-git/celld-entry-bundle.test.ts +++ b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts @@ -37,14 +37,14 @@ const scratch = mkdtempSync(join(tmpdir(), 'sam-celld-entry-')); afterAll(() => rmSync(scratch, { recursive: true, force: true })); describe('generated celld project', () => { - it.each([['plain', false]])( - 'bundles in %s mode with the HostedGitRepo binding', - async (_mode, _runtimeSecrets) => { + it( + 'bundles with the HostedGitRepo binding', + async () => { const plan = buildCelldConfig( TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as unknown as WranglerToml, { main: CELLD_MAIN, baseDomain: 'box.example.com' } ); - const projectDir = join(scratch, runtimeSecrets ? 'sealed' : 'plain'); + const projectDir = join(scratch, 'plain'); prepareCelldProject({ apiDir: API_DIR, projectDir, plan }); writeCelldConfig(projectDir, plan.config); diff --git a/apps/api/tests/unit/selfhost/selfhost-build.test.ts b/apps/api/tests/unit/selfhost/selfhost-build.test.ts index 04b7294314..7b377d7da8 100644 --- a/apps/api/tests/unit/selfhost/selfhost-build.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-build.test.ts @@ -3,6 +3,7 @@ * the D1 analytics sink and its `analytics.d1.*` settings, or a box loses product analytics * and their retention bound. Enters through the real build function, not the sink's own installer. */ +import { Hono } from 'hono'; import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; @@ -31,7 +32,7 @@ describe('withSelfHostBuild', () => { expect(activeLocalAnalyticsSink(boxEnv)).toBeUndefined(); expect(findAdminSetting('analytics.d1.retentionDays')).toBeUndefined(); - withSelfHostBuild(shared); + withSelfHostBuild(shared, new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok'))); expect(activeLocalAnalyticsSink(boxEnv)?.table).toBe('analytics_events'); expect(resolvePlatformCapabilities(boxEnv).analyticsQuery).toBe(true); @@ -40,7 +41,7 @@ describe('withSelfHostBuild', () => { }); it('leaves the sink inactive on an installation that does not switch it on', () => { - withSelfHostBuild(shared); + withSelfHostBuild(shared, new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok'))); expect( activeLocalAnalyticsSink({ OBSERVABILITY_DATABASE: {} } as unknown as Env) ).toBeUndefined(); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index e875c139a6..a57304ed1a 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -198,6 +198,24 @@ headers, no query strings, and no credentials in the path on the routes listed i `caddy/log-redaction.caddy` (bootstrap, invite and AI-proxy tokens, preview signatures). `docker compose logs celld` is the Worker's output. +## SAM-hosted repositories + +The celld build enables SAM-hosted git. Create a project with the Artifacts repository option; +SAM seeds an empty repository so an agent can clone, commit and push without a GitHub App. +The repository Durable Object and its `selfhost-hosted-git-v1` migration exist only in celld. +The Cloudflare Worker never includes them. + +Public repository import is unavailable in this slice; an import URL returns a clear 400. +A bounded importer is tracked in `tasks/backlog/2026-11-19-bounded-selfhost-git-import.md`. +GitHub and GitLab integrations remain available when configured. + +Admin → Settings exposes `repositories.*` limits. Defaults are 64 MiB per push, 30,000 objects +and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation +per request, delta depth 100 and 120 seconds per git operation. Operators can lower these +limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. +Clone/push credentials expire and runtime credentials also require the same active workspace +and callback generation. Deleting a project removes its hosted repository. + ## Not included yet This version runs in plaintext mode: celld keeps every Worker secret in plaintext in the fleet @@ -207,10 +225,6 @@ bucket's deploy manifests, so the bucket credential is the install's master key. network or the cloud metadata server on the box. - **Sealed secrets**: no key agent or KMS-backed encryption of the Worker's secrets. - **Guided credential login** (sandboxed agent sign-in on the box). -- **Hosted git.** Every project needs a repository, so on this install users can create projects - and run agents only once a GitHub App (the `GITHUB_*` Worker secrets in `.state/secrets.env`) - or a GitLab integration is configured. - Without one, sign-in, administration and nodes work, but no agent session can start. - **Backup, restore and teardown** commands. Back up the fleet bucket and `.state/` yourself. Do not put data on this box that you could not afford to lose or leak. diff --git a/scripts/selfhost/celld-config.test.ts b/scripts/selfhost/celld-config.test.ts index 5b5b1a44a6..c5e6baab81 100644 --- a/scripts/selfhost/celld-config.test.ts +++ b/scripts/selfhost/celld-config.test.ts @@ -67,10 +67,11 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { } }); - it('runs no container and leaves SAM-native git off', () => { + it('runs no container and enables the self-host git fallback', () => { expect(config).not.toHaveProperty('containers'); - // No Artifacts binding and no other backend registered: resolveArtifactsBackend is null. - expect(config.vars.ARTIFACTS_ENABLED).not.toBe('true'); + // The self-host build registers the backend; Cloudflare keeps its own configuration. + expect(config.vars.ARTIFACTS_ENABLED).toBe('true'); + expect(config.vars.HOSTED_GIT_BACKEND).toBe('durable-object'); }); it('folds every legacy new_classes create into new_sqlite_classes, keeping tag order', () => { @@ -80,8 +81,8 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { new_sqlite_classes?: string[]; }>; expect(sourceMigrations.some((m) => m.new_classes?.length)).toBe(true); - // wrangler.toml's tags, in order, and nothing else. - expect(config.migrations.map((m) => m.tag)).toEqual(sourceMigrations.map((m) => m.tag)); + // Keep shared tags in order, then append the celld-only tag. + expect(config.migrations.map((m) => m.tag)).toEqual([...sourceMigrations.map((m) => m.tag), 'selfhost-hosted-git-v1']); for (const migration of config.migrations) { expect(Object.keys(migration).sort()).toEqual(['new_sqlite_classes', 'tag']); } @@ -90,12 +91,12 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { ...(m.new_sqlite_classes ?? []), ...(m.new_classes ?? []), ]); - expect(new Set(created)).toEqual(new Set(expected)); + expect(new Set(created)).toEqual(new Set([...expected, 'HostedGitRepo'])); }); - it('binds exactly the Durable Objects wrangler.toml binds', () => { + it('adds only HostedGitRepo to the shared Durable Object bindings', () => { expect(config.durable_objects.bindings).toEqual( - (source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }).bindings + [...(source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }).bindings, { name: 'HOSTED_GIT', class_name: 'HostedGitRepo' }] ); }); diff --git a/scripts/selfhost/celld-config.ts b/scripts/selfhost/celld-config.ts index 90ecd6d418..1fa8780e4b 100644 --- a/scripts/selfhost/celld-config.ts +++ b/scripts/selfhost/celld-config.ts @@ -14,11 +14,14 @@ import { resolveDurableObjectMigrations } from '../deploy/durable-object-migrations.js'; import type { MigrationEntry, WranglerToml } from '../deploy/types.js'; +import { appendSelfhostDurableObjects } from './selfhost-durable-objects.js'; /** Worker vars set for every celld deployment, overriding wrangler.toml [vars]. */ export const SELFHOST_VAR_OVERRIDES: Readonly> = { // Cloudflare Containers: Instant sessions and the Sandbox SDK. celld's container fence // blocks container -> host traffic on a one-box install (idea 01M72M9AEB933ZY8269D376DKC). + HOSTED_GIT_BACKEND: 'durable-object', + ARTIFACTS_ENABLED: 'true', CF_CONTAINER_ENABLED: 'false', SANDBOX_ENABLED: 'false', // Managed devcontainer cache uses the Cloudflare container registry API. @@ -425,6 +428,7 @@ export function buildCelldConfig( const ctx = translateTopLevelKeys(source, options); const out = ctx.out as CelldWranglerConfig; + appendSelfhostDurableObjects(out, ctx.plan.report); out.compatibility_flags ??= []; const r2 = out.r2_buckets.find((bucket) => bucket.binding === 'R2'); out.vars = { diff --git a/scripts/selfhost/celld-project.test.ts b/scripts/selfhost/celld-project.test.ts index d453190cea..d02726b664 100644 --- a/scripts/selfhost/celld-project.test.ts +++ b/scripts/selfhost/celld-project.test.ts @@ -53,18 +53,18 @@ describe('prepareCelldProject', () => { prepareCelldProject({ apiDir: API_DIR, projectDir, plan: plan() }); const main = readFileSync(join(projectDir, CELLD_MAIN), 'utf8'); expect(main).toBe(renderCelldMain()); - expect(main).toContain("import worker from './src/index.ts';"); + expect(main).toContain("import worker, { app } from './src/index.ts';"); expect(main).toContain('resumeSharedFlightJoinsOnOwnTimer();'); expect(main).toContain("export * from './src/index.ts';"); - expect(main).toContain('export default withSelfHostBuild(worker);'); + expect(main).toContain('export default withSelfHostBuild(worker, app);'); // Every module the entry imports exists in apps/api (the symlinked src). const specifiers = [...main.matchAll(/from '\.\/src\/([^']+)'/g)].map((m) => m[1]!); expect(specifiers.length).toBeGreaterThanOrEqual(3); for (const specifier of specifiers) { expect(existsSync(join(API_DIR, 'src', specifier)), specifier).toBe(true); } - // Nothing but the shared entry's own exports and the default. - expect(main.match(/^export /gm)).toHaveLength(2); + // Shared exports, the self-host-only DO, and the default. + expect(main.match(/^export /gm)).toHaveLength(3); expect(statSync(join(projectDir, CELLD_MAIN)).mode & 0o777).toBe(0o600); }); diff --git a/scripts/selfhost/celld-project.ts b/scripts/selfhost/celld-project.ts index 54b8122ea9..7a977a0cf7 100644 --- a/scripts/selfhost/celld-project.ts +++ b/scripts/selfhost/celld-project.ts @@ -24,6 +24,7 @@ import type { CelldConfigPlan, CelldWranglerConfig } from './celld-config.js'; import { appendSelfhostObservabilityMigrations } from './observability-migrations.js'; import { appendReverseTunnelMigrations } from './reverse-tunnel-migrations.js'; import { writePrivateFile } from './secret-files.js'; +import { SELFHOST_DURABLE_OBJECTS, SELFHOST_ENTRY_MODULE } from './selfhost-durable-objects.js'; export const CONFIG_FILE = 'wrangler.json'; export const SOURCE_LINK = 'src'; @@ -52,13 +53,16 @@ const OBSERVABILITY_MIGRATIONS_DIR = 'src/db/migrations/observability'; export function renderCelldMain(): string { return [ '// Generated by scripts/selfhost/celld-project.ts (renderCelldMain). Do not edit.', - `import worker from './${SOURCE_LINK}/index.ts';`, + `import worker, { app } from './${SOURCE_LINK}/index.ts';`, `import { resumeSharedFlightJoinsOnOwnTimer } from './${SOURCE_LINK}/lib/shared-flight.ts';`, - `import { withSelfHostBuild } from './${SOURCE_LINK}/selfhost/build.ts';`, + `import { withSelfHostBuild } from './${SOURCE_LINK}/${SELFHOST_ENTRY_MODULE}';`, '', 'resumeSharedFlightJoinsOnOwnTimer();', `export * from './${SOURCE_LINK}/index.ts';`, - 'export default withSelfHostBuild(worker);', + ...SELFHOST_DURABLE_OBJECTS.map(({ className }) => + `export { ${className} } from './${SOURCE_LINK}/${SELFHOST_ENTRY_MODULE}';` + ), + 'export default withSelfHostBuild(worker, app);', '', ].join('\n'); } diff --git a/scripts/selfhost/selfhost-durable-objects.ts b/scripts/selfhost/selfhost-durable-objects.ts index 19569d2102..396ae7b853 100644 --- a/scripts/selfhost/selfhost-durable-objects.ts +++ b/scripts/selfhost/selfhost-durable-objects.ts @@ -28,10 +28,8 @@ export interface SelfhostDurableObject { /** The module under apps/api/src that the generated celld entry imports for these classes. */ export const SELFHOST_ENTRY_MODULE = 'selfhost/build.ts'; -/** Function in `SELFHOST_ENTRY_MODULE` the entry calls with the shared Hono app. */ - export const SELFHOST_DURABLE_OBJECTS: readonly SelfhostDurableObject[] = [ - // SAM-hosted git repositories (one per repository); selfhost/hosted-git/backend.ts selects it + // SAM-hosted git repositories (one per repository); selfhost/hosted-git/local-backend.ts selects it // with HOSTED_GIT_BACKEND=durable-object (SELFHOST_VAR_OVERRIDES). { binding: 'HOSTED_GIT', className: 'HostedGitRepo', migrationTag: 'selfhost-hosted-git-v1' }, ]; diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 709a5b1c7c..fab1d227af 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -11,12 +11,12 @@ Trace: project-create -> resolved Artifacts backend -> seed/import via backend r Use existing L16 selection, extend its optional token context and fetch/import contract. Move implementation under selfhost; preserve Cloudflare semantics. Import with git checkout paths, no cherry-pick. Tests must exercise real git over smart HTTP and prove import-graph detection by introducing a forbidden import. Relevant lessons: callback routing/auth rule 34; DO interleaving rule 45; cross-boundary/vertical tests rules 23/35; no secret readback rule 83. Docs: operator README only (experimental self-host slice). ## Checklist -- [ ] Fresh branch from main; import selected integration paths and trim -- [ ] Move DO and hosted-git services under selfhost; dgit/pako excluded from Worker graph -- [ ] Extend generic fallback seam: workspace-bound token context, remoteFetch and import; remove shared local-backend branches -- [ ] Wire celld-only binding/export/tag via L22 single entry after L22c lands -- [ ] Add conformance/auth/lifecycle/token tests and import-graph violation proof -- [ ] Document self-host repository support and limits +- [x] Fresh branch from main; import selected integration paths and trim +- [x] Move DO and hosted-git services under selfhost; dgit/pako excluded from Worker graph +- [x] Extend generic fallback seam: workspace-bound token context, remoteFetch and optional import capability (unregistered per coordinator empty-repo decision); remove shared local-backend branches +- [x] Wire celld-only binding/export/tag via L22 single entry stacked on stable L22c539625202 per coordinator +- [x] Add conformance/auth/lifecycle/token tests and import-graph violation proof +- [x] Document self-host repository support and limits - [ ] Local lint/typecheck/tests/build; security, Cloudflare, architecture and completion reviews - [ ] Draft PR then ready/CI/CodeRabbit request and wait - [ ] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off @@ -25,3 +25,6 @@ Use existing L16 selection, extend its optional token context and fetch/import c ## Acceptance No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; no CF migration. Shared seam inert on Cloudflare. BOX upgrade succeeds with new celld tag, project creation and actual short free-model agent reply/push work. Every resource created by this task cleaned up. All required gates pass on merge head. + +## Implementation evidence +Stacked L22c539625202 per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite19/19 (real git18 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. From 0991b27ff422900d68077dc226dbad8cfa8681e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:35:35 +0000 Subject: [PATCH 39/65] fix(selfhost): port bounds in Caddy's start guard; repo-root build context Codex review on 539625202: - caddy/start.sh: a compose run from another shell can override a port the deploy never saw; refuse values outside 1-65535 (1024 minimum for the services with no capability), as box-settings does. - imageRebuilds: an overlay build context at the repository root (`../..`) normalised to '.', so no changed path matched; count every non-README file there. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/caddy/start.sh | 13 ++++++++++++- scripts/selfhost/caddy-start.test.ts | 13 +++++++++++++ scripts/selfhost/image-rebuilds.ts | 7 +++++-- scripts/selfhost/upgrade.test.ts | 11 +++++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh index bb455632d0..c0ecccb15f 100644 --- a/deploy/selfhost/caddy/start.sh +++ b/deploy/selfhost/caddy/start.sh @@ -101,10 +101,21 @@ for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT O ;; *) ;; esac + # Same bounds as the deploy (box-settings.ts boxPort): a compose run from another shell can + # override a port the deploy never saw. Services with no capability cannot bind below 1024. + min=1 + case "$name" in + CELLD_PORT | CELLD_INTERNAL_PORT | FRPS_BIND_PORT | MAIL_COLLECTOR_SMTP_PORT | MAIL_COLLECTOR_UI_PORT) min=1024 ;; + *) ;; + esac + if [ "${#port}" -gt 5 ] || [ "$port" -lt "$min" ] || [ "$port" -gt 65535 ]; then + echo "caddy: $name ($port) must be a port between $min and 65535" >&2 + exit 64 + fi if [ "$port" -ge "$start" ] && [ "$port" -le "$end" ]; then echo "caddy: $name ($port) lies inside the reverse-tunnel range $start-$end; a node could be leased it. Change the port or REVERSE_TUNNEL_PORT_RANGE_START/END, then pnpm selfhost:deploy --init" >&2 exit 64 fi done -unset start end bound name port +unset start end bound name port min exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts index c900cee5a0..6efc179e4e 100644 --- a/scripts/selfhost/caddy-start.test.ts +++ b/scripts/selfhost/caddy-start.test.ts @@ -94,6 +94,19 @@ describe('caddy/start.sh', () => { } ); + // A compose run from another shell can override a port the deploy never checked. + it.each([ + ['CELLD_PORT', '70000'], + ['HTTPS_PORT', '0'], + ['CELLD_INTERNAL_PORT', '80'], + ['FRPS_BIND_PORT', '123456789012345678901'], + ])('refuses %s=%s outside its port bounds', (name, value) => { + const run = startSh({ ...composeEnv(), [name]: value }); + expect(run.status).toBe(64); + expect(run.out).toContain(`${name} (${value}) must be a port between`); + expect(run.out).not.toContain('caddy run'); + }); + // Go's net.Listen refuses an unbracketed IPv6 host ("too many colons in address"). it.each(['::2525', 'foo::2525', '[::]2525', '[::1]:[25]'])( 'refuses SAM_MX_LISTEN=%s, an IPv6 host without brackets or a malformed bracket', diff --git a/scripts/selfhost/image-rebuilds.ts b/scripts/selfhost/image-rebuilds.ts index 8913eafe6b..989de10541 100644 --- a/scripts/selfhost/image-rebuilds.ts +++ b/scripts/selfhost/image-rebuilds.ts @@ -111,9 +111,12 @@ export function imageRebuilds( continue; } const contextRel = build.context ?? '.'; - const context = isAbsolute(contextRel) + // Repository-relative, '' for the repository root itself (`../..` or the absolute root). + const joined = isAbsolute(contextRel) ? relative(REPO_ROOT, contextRel).split(/[\\/]/).join('/') : posix.join(posix.dirname(COMPOSE_PATH), contextRel); + const context = joined === '.' ? '' : joined; + const under = context === '' ? '' : `${context}/`; const dockerfile = posix.join(context, build.dockerfile ?? 'Dockerfile'); const ignore = posix.join(context, '.dockerignore'); const emptyContext = ignoresEverything(readFileAtTo(ignore)); @@ -121,7 +124,7 @@ export function imageRebuilds( (file) => file === dockerfile || file === ignore || - (!emptyContext && file.startsWith(`${context}/`) && !file.endsWith('.md')) + (!emptyContext && file.startsWith(under) && !file.endsWith('.md')) ); if (touched) rebuilds.push(service); } diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 7809a96671..38ed28d3aa 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -604,6 +604,17 @@ describe('imageRebuilds', () => { expect(imageRebuilds([], null, COMPOSE())).toEqual(['caddy', 'sam-mx']); }); + // An overlay whose context is the repository root (`../..` from deploy/selfhost) sends every + // file to the build: a change anywhere in the repository must count. + it('counts any changed file for a build context at the repository root', () => { + const rootBuild = 'services:\n celld:\n build:\n context: ../..\n'; + const overlays = [{ from: rootBuild, to: rootBuild }]; + expect( + imageRebuilds(['apps/api/src/index.ts'], COMPOSE(), COMPOSE(), () => null, overlays) + ).toEqual(['celld']); + expect(imageRebuilds(['README.md'], COMPOSE(), COMPOSE(), () => null, overlays)).toEqual([]); + }); + // Compose merges build args by name whatever form each file uses (list or mapping). it('merges list-form overlay args by name, so a base-only arg change still rebuilds', () => { const listOverlay = 'services:\n caddy:\n build:\n args:\n - EXTRA=x\n'; From a7cad0d73cb911c763be5818fc984aa415a0f638 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:38:01 +0000 Subject: [PATCH 40/65] style: format hosted git build wiring --- .../routes/workspaces/runtime-git-token.ts | 5 +- apps/api/src/selfhost/build.ts | 5 +- .../hosted-git/celld-entry-bundle.test.ts | 52 +++++++++---------- .../selfhost/hosted-git-gc-admission.test.ts | 44 +++++++++++++--- .../unit/selfhost/selfhost-build.test.ts | 10 +++- scripts/selfhost/celld-config.test.ts | 13 +++-- scripts/selfhost/celld-project.ts | 4 +- .../2026-11-19-selfhost-hosted-git-h2.md | 5 ++ 8 files changed, 93 insertions(+), 45 deletions(-) diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index bef752ec99..2ee1d2563a 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -6,7 +6,10 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { errors } from '../../middleware/error'; -import { createArtifactsRuntimeToken, resolveArtifactsBackend } from '../../services/artifacts/backend'; +import { + createArtifactsRuntimeToken, + resolveArtifactsBackend, +} from '../../services/artifacts/backend'; import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; import { GitHubCliPolicyError, diff --git a/apps/api/src/selfhost/build.ts b/apps/api/src/selfhost/build.ts index f106e77171..e10b4c0656 100644 --- a/apps/api/src/selfhost/build.ts +++ b/apps/api/src/selfhost/build.ts @@ -25,7 +25,10 @@ import { installSpeechEndpoints } from './speech'; const mounted = new WeakSet(); -export function withSelfHostBuild(worker: T, app: Hono<{ Bindings: Env }>): T { +export function withSelfHostBuild( + worker: T, + app: Hono<{ Bindings: Env }> +): T { if (!mounted.has(app)) { mountHostedGitRoute(app); app.route('/api/projects', hostedGitTokenRoutes); diff --git a/apps/api/tests/hosted-git/celld-entry-bundle.test.ts b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts index 2aa47885f4..913108555e 100644 --- a/apps/api/tests/hosted-git/celld-entry-bundle.test.ts +++ b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts @@ -37,33 +37,29 @@ const scratch = mkdtempSync(join(tmpdir(), 'sam-celld-entry-')); afterAll(() => rmSync(scratch, { recursive: true, force: true })); describe('generated celld project', () => { - it( - 'bundles with the HostedGitRepo binding', - async () => { - const plan = buildCelldConfig( - TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as unknown as WranglerToml, - { main: CELLD_MAIN, baseDomain: 'box.example.com' } - ); - const projectDir = join(scratch, 'plain'); - prepareCelldProject({ apiDir: API_DIR, projectDir, plan }); - writeCelldConfig(projectDir, plan.config); + it('bundles with the HostedGitRepo binding', async () => { + const plan = buildCelldConfig( + TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as unknown as WranglerToml, + { main: CELLD_MAIN, baseDomain: 'box.example.com' } + ); + const projectDir = join(scratch, 'plain'); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan }); + writeCelldConfig(projectDir, plan.config); - const celld = await ensureCelldBinary(join(tmpdir(), 'sam-celld-bin')); - const result = spawnSync( - celld, - ['deploy', projectDir, '--dry-run', '--bucket', 's3://dry-run-not-written'], - { - encoding: 'utf8', - timeout: 300_000, - env: { ...process.env, CELLD_ESBUILD: resolveEsbuild(API_DIR) }, - } - ); - const output = `${result.stdout}${result.stderr}`; - expect(result.status, output.slice(-4000)).toBe(0); - expect(output).toContain('Bundled workspaces-api'); - expect(output).toMatch(/env\.HOSTED_GIT \(HostedGitRepo\)\s+Durable Object \(SQLite\)/); - expect(output).toMatch(/env\.HOSTED_GIT_BACKEND \(Text\)/); - }, - 600_000 - ); + const celld = await ensureCelldBinary(join(tmpdir(), 'sam-celld-bin')); + const result = spawnSync( + celld, + ['deploy', projectDir, '--dry-run', '--bucket', 's3://dry-run-not-written'], + { + encoding: 'utf8', + timeout: 300_000, + env: { ...process.env, CELLD_ESBUILD: resolveEsbuild(API_DIR) }, + } + ); + const output = `${result.stdout}${result.stderr}`; + expect(result.status, output.slice(-4000)).toBe(0); + expect(output).toContain('Bundled workspaces-api'); + expect(output).toMatch(/env\.HOSTED_GIT \(HostedGitRepo\)\s+Durable Object \(SQLite\)/); + expect(output).toMatch(/env\.HOSTED_GIT_BACKEND \(Text\)/); + }, 600_000); }); diff --git a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts index ac919c89f8..7304e1f381 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts @@ -1,20 +1,50 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo'; import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; -const mocks = vi.hoisted(() => ({ pending: '1', gc: vi.fn(async () => ({ removed: 1, kept: 2 })), setAlarm: vi.fn(async () => undefined) })); -vi.mock('cloudflare:workers', () => ({ DurableObject: class { constructor(public ctx: unknown, public env: unknown) {} } })); -vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ resolveHostedGitLimits: async () => DEFAULT_HOSTED_GIT_LIMITS })); -vi.mock('../../../src/vendor/dgit/git/store', () => ({ GitStore: class { getMeta() { return mocks.pending; } setMeta(_key: string, value: string) { mocks.pending = value; } } })); +const mocks = vi.hoisted(() => ({ + pending: '1', + gc: vi.fn(async () => ({ removed: 1, kept: 2 })), + setAlarm: vi.fn(async () => undefined), +})); +vi.mock('cloudflare:workers', () => ({ + DurableObject: class { + constructor( + public ctx: unknown, + public env: unknown + ) {} + }, +})); +vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ + resolveHostedGitLimits: async () => DEFAULT_HOSTED_GIT_LIMITS, +})); +vi.mock('../../../src/vendor/dgit/git/store', () => ({ + GitStore: class { + getMeta() { + return mocks.pending; + } + setMeta(_key: string, value: string) { + mocks.pending = value; + } + }, +})); vi.mock('../../../src/selfhost/hosted-git/hosted-git-gc', () => ({ runHostedGitGc: mocks.gc })); -beforeEach(() => { mocks.pending = '1'; vi.clearAllMocks(); }); +beforeEach(() => { + mocks.pending = '1'; + vi.clearAllMocks(); +}); describe('hosted git GC admission', () => { it('rechecks uploads after waiting behind a push, and runs once after the upload leaves', async () => { - const ctx = { storage: { setAlarm: mocks.setAlarm }, blockConcurrencyWhile: async (action: () => Promise) => action() }; + const ctx = { + storage: { setAlarm: mocks.setAlarm }, + blockConcurrencyWhile: async (action: () => Promise) => action(), + }; const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); // Hold the same promise-chain slot that receive-pack owns, exercising alarm's real queue. let releasePush = () => {}; const state = repo as unknown as { receiveChain: Promise; activeUploads: number }; - state.receiveChain = new Promise((resolve) => { releasePush = resolve; }); + state.receiveChain = new Promise((resolve) => { + releasePush = resolve; + }); const alarm = repo.alarm(); await vi.waitFor(() => expect(mocks.pending).toBe('0')); state.activeUploads = 1; diff --git a/apps/api/tests/unit/selfhost/selfhost-build.test.ts b/apps/api/tests/unit/selfhost/selfhost-build.test.ts index 7b377d7da8..8cc1499893 100644 --- a/apps/api/tests/unit/selfhost/selfhost-build.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-build.test.ts @@ -32,7 +32,10 @@ describe('withSelfHostBuild', () => { expect(activeLocalAnalyticsSink(boxEnv)).toBeUndefined(); expect(findAdminSetting('analytics.d1.retentionDays')).toBeUndefined(); - withSelfHostBuild(shared, new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok'))); + withSelfHostBuild( + shared, + new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok')) + ); expect(activeLocalAnalyticsSink(boxEnv)?.table).toBe('analytics_events'); expect(resolvePlatformCapabilities(boxEnv).analyticsQuery).toBe(true); @@ -41,7 +44,10 @@ describe('withSelfHostBuild', () => { }); it('leaves the sink inactive on an installation that does not switch it on', () => { - withSelfHostBuild(shared, new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok'))); + withSelfHostBuild( + shared, + new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok')) + ); expect( activeLocalAnalyticsSink({ OBSERVABILITY_DATABASE: {} } as unknown as Env) ).toBeUndefined(); diff --git a/scripts/selfhost/celld-config.test.ts b/scripts/selfhost/celld-config.test.ts index c5e6baab81..c645b5280d 100644 --- a/scripts/selfhost/celld-config.test.ts +++ b/scripts/selfhost/celld-config.test.ts @@ -82,7 +82,10 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { }>; expect(sourceMigrations.some((m) => m.new_classes?.length)).toBe(true); // Keep shared tags in order, then append the celld-only tag. - expect(config.migrations.map((m) => m.tag)).toEqual([...sourceMigrations.map((m) => m.tag), 'selfhost-hosted-git-v1']); + expect(config.migrations.map((m) => m.tag)).toEqual([ + ...sourceMigrations.map((m) => m.tag), + 'selfhost-hosted-git-v1', + ]); for (const migration of config.migrations) { expect(Object.keys(migration).sort()).toEqual(['new_sqlite_classes', 'tag']); } @@ -95,9 +98,11 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { }); it('adds only HostedGitRepo to the shared Durable Object bindings', () => { - expect(config.durable_objects.bindings).toEqual( - [...(source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }).bindings, { name: 'HOSTED_GIT', class_name: 'HostedGitRepo' }] - ); + expect(config.durable_objects.bindings).toEqual([ + ...(source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }) + .bindings, + { name: 'HOSTED_GIT', class_name: 'HostedGitRepo' }, + ]); }); it('keeps container DO bindings (the classes stay exported) but not their containers', () => { diff --git a/scripts/selfhost/celld-project.ts b/scripts/selfhost/celld-project.ts index 7a977a0cf7..538569fbfd 100644 --- a/scripts/selfhost/celld-project.ts +++ b/scripts/selfhost/celld-project.ts @@ -59,8 +59,8 @@ export function renderCelldMain(): string { '', 'resumeSharedFlightJoinsOnOwnTimer();', `export * from './${SOURCE_LINK}/index.ts';`, - ...SELFHOST_DURABLE_OBJECTS.map(({ className }) => - `export { ${className} } from './${SOURCE_LINK}/${SELFHOST_ENTRY_MODULE}';` + ...SELFHOST_DURABLE_OBJECTS.map( + ({ className }) => `export { ${className} } from './${SOURCE_LINK}/${SELFHOST_ENTRY_MODULE}';` ), 'export default withSelfHostBuild(worker, app);', '', diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index fab1d227af..2319791552 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -1,9 +1,11 @@ # H2: SAM-hosted git on self-host only ## Problem + A box built from main needs a repository source before it can create a project and run an agent. Owner D7 narrowed: HostedGitRepo is celld-only, never a Cloudflare export, binding, import or migration. Main v23 is unrelated and untouched. ## Research and preflight + Classes: cross-component, business logic, security sensitive, infra, docs sync. Main 08abf1393 already has L16's backend fallback selection and L22b's single self-host entry. L22c #2906 remains open, held on #2905 and security review; coordinator confirmed import/trim can proceed while celld wiring and BOX wait for L22c main. Integration has hosted-git runtime and conformance fixtures, but shared routes import local implementation (M4 HIGH-4). Trace: project-create -> resolved Artifacts backend -> seed/import via backend remoteFetch -> authenticated self-host git HTTP -> HostedGitRepo SQLite. Runtime callback -> active workspace/current generation -> backend createToken with workspace identity -> git HTTP rechecks membership/lifecycle/generation -> push commits ref. Cloudflare keeps binding or null and global fetch, with no registered fallback. @@ -11,6 +13,7 @@ Trace: project-create -> resolved Artifacts backend -> seed/import via backend r Use existing L16 selection, extend its optional token context and fetch/import contract. Move implementation under selfhost; preserve Cloudflare semantics. Import with git checkout paths, no cherry-pick. Tests must exercise real git over smart HTTP and prove import-graph detection by introducing a forbidden import. Relevant lessons: callback routing/auth rule 34; DO interleaving rule 45; cross-boundary/vertical tests rules 23/35; no secret readback rule 83. Docs: operator README only (experimental self-host slice). ## Checklist + - [x] Fresh branch from main; import selected integration paths and trim - [x] Move DO and hosted-git services under selfhost; dgit/pako excluded from Worker graph - [x] Extend generic fallback seam: workspace-bound token context, remoteFetch and optional import capability (unregistered per coordinator empty-repo decision); remove shared local-backend branches @@ -24,7 +27,9 @@ Use existing L16 selection, extend its optional token context and fetch/import c - [ ] Merge main; all gates current head; announce merging/merged SHA; production success; idea SHIPPED ## Acceptance + No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; no CF migration. Shared seam inert on Cloudflare. BOX upgrade succeeds with new celld tag, project creation and actual short free-model agent reply/push work. Every resource created by this task cleaned up. All required gates pass on merge head. ## Implementation evidence + Stacked L22c539625202 per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite19/19 (real git18 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. From f6c65e71ace4dbf9c9802f646f88851fb0a824a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:47:23 +0000 Subject: [PATCH 41/65] fix: use static identifiers and bound git SQL placeholders --- apps/api/src/vendor/dgit/git/packstore.ts | 19 ++++++++++--------- apps/api/src/vendor/dgit/git/store.ts | 14 +++++++++----- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts index e4566b2571..86cf6d4618 100644 --- a/apps/api/src/vendor/dgit/git/packstore.ts +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -1,6 +1,6 @@ // @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ -// FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) +// FILE SIZE EXCEPTION: vendored dgit core with SAM resource bounds and static SQL identifiers (see ../UPSTREAM.md) import pako from "pako"; import { inflate as inflateAll } from "./zlib"; import { chargeGitWork, gitWorkLimits, readGitChunk } from "./budget"; @@ -260,9 +260,10 @@ export class PackStore { } wipe(): void { - for (const t of ["pack_meta", "pack_data", "pack_objects", "pack_pending"]) { - this.sql.exec(`DROP TABLE IF EXISTS ${t}`); - } + this.sql.exec("DROP TABLE IF EXISTS pack_meta"); + this.sql.exec("DROP TABLE IF EXISTS pack_data"); + this.sql.exec("DROP TABLE IF EXISTS pack_objects"); + this.sql.exec("DROP TABLE IF EXISTS pack_pending"); this.chunks.clear(); // pack ids restart from 1: cached rows would be stale this.backend.clear(); } @@ -516,9 +517,9 @@ export class PackStore { ) .toArray(); for (const o of orphans) { - for (const t of ["pack_data", "pack_objects", "pack_pending"]) { - this.sql.exec(`DELETE FROM ${t} WHERE pack_id = ?`, o.pack_id); - } + this.sql.exec("DELETE FROM pack_data WHERE pack_id = ?", o.pack_id); + this.sql.exec("DELETE FROM pack_objects WHERE pack_id = ?", o.pack_id); + this.sql.exec("DELETE FROM pack_pending WHERE pack_id = ?", o.pack_id); // an interrupted R2 ingest may have left a completed raw object; delete it if (this.r2) { try { @@ -671,9 +672,9 @@ export class PackStore { let objBatchRows = 0; const flushObjects = () => { if (!objBatchRows) return; - const values = Array(objBatchRows).fill("(?,?,?,?,?,?,?,?,?)").join(","); + const placeholders = Array(objBatchRows).fill("(?,?,?,?,?,?,?,?,?)").join(","); this.sql.exec( - `INSERT OR IGNORE INTO pack_objects (oid, pack_id, offset, data_off, data_len, type, size, entry_size, base_oid) VALUES ${values}`, + `INSERT OR IGNORE INTO pack_objects (oid, pack_id, offset, data_off, data_len, type, size, entry_size, base_oid) VALUES ${placeholders}`, ...objBatch ); objBatch = []; diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index 3c855c9807..dc5dcf4bfe 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -191,8 +191,8 @@ export class GitStore { addPushEdges(children: string[]): void { for (let i = 0; i < children.length; i += 64) { const batch = children.slice(i, i + 64); - const values = batch.map(() => "(?)").join(","); - this.sql.exec(`INSERT INTO push_edges (child) VALUES ${values}`, ...batch); + const placeholders = batch.map(() => "(?)").join(","); + this.sql.exec(`INSERT INTO push_edges (child) VALUES ${placeholders}`, ...batch); } } @@ -238,9 +238,13 @@ export class GitStore { } wipe(): void { - for (const t of ["objects", "chunks", "refs", "meta", "reachable", "peeled", "stats_cache"]) { - this.sql.exec(`DROP TABLE IF EXISTS ${t}`); - } + this.sql.exec("DROP TABLE IF EXISTS objects"); + this.sql.exec("DROP TABLE IF EXISTS chunks"); + this.sql.exec("DROP TABLE IF EXISTS refs"); + this.sql.exec("DROP TABLE IF EXISTS meta"); + this.sql.exec("DROP TABLE IF EXISTS reachable"); + this.sql.exec("DROP TABLE IF EXISTS peeled"); + this.sql.exec("DROP TABLE IF EXISTS stats_cache"); this.packs.wipe(); // meta (with the flag) is gone; a fresh empty repo has no loose objects this.hasLoose = false; From 083dcdd8616398d8a4584557d726d95bfb263b91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 12:59:11 +0000 Subject: [PATCH 42/65] ci: run isolated hosted git conformance and track its inputs --- .github/workflows/ci.yml | 20 +++++++------------ apps/api/vitest.config.ts | 2 +- packages/repo-hosting/src/index.ts | 1 - .../repo-hosting/src/repo-browse/artifacts.ts | 2 +- scripts/quality/ci-suite-selection.test.ts | 19 +++++++++++++++++- .../quality/direct-dependency-evidence.json | 10 ++++++++++ .../2026-11-19-selfhost-hosted-git-h2.md | 4 +++- 7 files changed, 40 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 339dd74a78..1b4df0206a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,19 +137,8 @@ jobs: - 'scripts/deploy/durable-object-migrations.ts' - 'scripts/deploy/types.ts' - 'scripts/deploy/vapid-keys.ts' - # Self-host build tests import the celld generator, presign vars, SMTP settings and - # account SQL: these modules plus the scripts/selfhost modules they import. The - # transitive ones are listed by hand: ci-suite-selection.test.ts checks the direct - # imports but does not follow `./x.js` specifiers to `x.ts`. - - 'scripts/selfhost/account-sql.ts' - - 'scripts/selfhost/box-settings.ts' - - 'scripts/selfhost/celld-config.ts' - - 'scripts/selfhost/celld-project.ts' - - 'scripts/selfhost/mail-settings.ts' - - 'scripts/selfhost/observability-migrations.ts' - - 'scripts/selfhost/reverse-tunnel-migrations.ts' - - 'scripts/selfhost/secret-files.ts' - - 'scripts/selfhost/selfhost-migrations.ts' + # API build/conformance tests import the celld generator and its helpers. + - 'scripts/selfhost/**' # selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only). - 'deploy/selfhost/sam-mx/**' # The self-host access-log redaction guard scans the API routes against this filter. @@ -589,6 +578,11 @@ jobs: --coverage.thresholds.statements=0 --coverage.thresholds.branches=0 --coverage.thresholds.functions=0 --coverage.thresholds.lines=0 + # One shard owns the real-git suite; the dedicated config launches its own runtime. + - name: Hosted git conformance and celld bundle + if: matrix.shard == 1 + run: pnpm --filter @simple-agent-manager/api test:hosted-git + - name: Upload API blob report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index fce3c88337..38e93faf81 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -20,7 +20,7 @@ export default defineConfig({ globals: true, setupFiles: ['./tests/setup/project-data-ports.ts', './tests/setup/repo-hosting-ports.ts'], include: ['tests/**/*.test.ts'], - exclude: ['tests/workers/**'], + exclude: ['tests/workers/**', 'tests/hosted-git/**'], coverage: coverageConfig(['src/**/*.ts'], { statements: 45, branches: 40, diff --git a/packages/repo-hosting/src/index.ts b/packages/repo-hosting/src/index.ts index 408fbf2c39..9fce968041 100644 --- a/packages/repo-hosting/src/index.ts +++ b/packages/repo-hosting/src/index.ts @@ -64,6 +64,5 @@ export { verifyGitLabProjectAccess, } from './gitlab'; export { type RepoBrowser, resolveRepoBrowser } from './repo-browse'; - export { createFetchHttpClient } from './repo-browse/fetch-http-client'; export { MemoryFS } from './repo-browse/memory-fs'; diff --git a/packages/repo-hosting/src/repo-browse/artifacts.ts b/packages/repo-hosting/src/repo-browse/artifacts.ts index 781f97ad80..4a4203da0a 100644 --- a/packages/repo-hosting/src/repo-browse/artifacts.ts +++ b/packages/repo-hosting/src/repo-browse/artifacts.ts @@ -10,10 +10,10 @@ import { errors } from '@simple-agent-manager/worker-core'; import { createPatch } from 'diff'; import git from 'isomorphic-git'; import webHttp from 'isomorphic-git/http/web'; -import { createFetchHttpClient } from './fetch-http-client'; import type { Env } from '../env'; import { repoHostingPorts } from '../ports'; +import { createFetchHttpClient } from './fetch-http-client'; import { MemoryFS } from './memory-fs'; import type { RepoBrowser } from './types'; import { basename, guessContentType, isBinaryBytes, maxCompareFiles, maxInlineBytes } from './util'; diff --git a/scripts/quality/ci-suite-selection.test.ts b/scripts/quality/ci-suite-selection.test.ts index cce92234b4..3c0188e7de 100644 --- a/scripts/quality/ci-suite-selection.test.ts +++ b/scripts/quality/ci-suite-selection.test.ts @@ -375,7 +375,8 @@ function crossReads( const walk = (current: string) => { if (!existsSync(current)) return; for (const entry of readdirSync(current)) { - if (['node_modules', 'dist', '.astro', 'coverage', 'test-results'].includes(entry)) continue; + if (['node_modules', 'dist', '.astro', '.tmp', 'coverage', 'test-results'].includes(entry)) + continue; const full = join(current, entry); if (statSync(full).isDirectory()) walk(full); else if (CODE_FILE.test(entry)) queue.push(full); @@ -389,6 +390,8 @@ function crossReads( for (const { path, imported } of references(file)) { const repoPath = relative(REPO_ROOT, path); if (repoPath === '' || repoPath.startsWith('..')) continue; + // Generated scratch is output, never a checked-in suite input. + if (repoPath === '.tmp' || repoPath.startsWith('.tmp/')) continue; if (repoPath.startsWith(`${scanned}/`)) { if (imported && CODE_FILE.test(path) && statSync(path).isFile() && !seen.has(path)) { seen.add(path); @@ -420,6 +423,18 @@ function suiteReads(suite: (typeof SUITES)[number]): Array<{ file: string; path: } describe('every file a suite reads outside its package is in its filter', () => { + it('runs real git through its dedicated config exactly once in the selected API matrix', () => { + const job = loadWorkflow().jobs['test-api']!; + const step = job.steps!.find( + (entry) => entry.name === 'Hosted git conformance and celld bundle' + )!; + expect(job.if).toContain("needs.changes.outputs.api-unit == 'true'"); + expect(step.if).toBe('matrix.shard == 1'); + expect(step.run).toBe('pnpm --filter @simple-agent-manager/api test:hosted-git'); + const buildIndex = job.steps!.findIndex((entry) => entry.name === 'Build API dependencies'); + expect(buildIndex).toBeGreaterThanOrEqual(0); + expect(job.steps!.findIndex((entry) => entry === step)).toBeGreaterThan(buildIndex); + }); it.each(SUITES.map((suite) => [suite.output, suite] as const))( '%s', (_, suite) => { @@ -452,6 +467,8 @@ describe('every file a suite reads outside its package is in its filter', () => ); expect(apiReads.some((path) => path.startsWith('packages/vm-agent/'))).toBe(true); expect(apiReads).toContain('apps/tail-worker/src/x'); + expect(apiReads.some((path) => path === '.tmp' || path.startsWith('.tmp/'))).toBe(false); + expect(apiReads).toContain('scripts/selfhost/celld-binary.ts'); // Reached only by following a web module's own imports (lineage test -> useTaskGroups). expect(apiReads).toContain('apps/web/src/lib/api/client.ts'); // Without the vm-agent extra the API unit filter would miss them. diff --git a/scripts/quality/direct-dependency-evidence.json b/scripts/quality/direct-dependency-evidence.json index 39b8fd1a61..30451d08c5 100644 --- a/scripts/quality/direct-dependency-evidence.json +++ b/scripts/quality/direct-dependency-evidence.json @@ -92,6 +92,11 @@ "registryUrl": "https://www.npmjs.com/package/@types/node", "necessity": "Types for node:crypto, which project-data's archive hashing uses under the Worker's nodejs_compat; same catalog version as the root." }, + "@types/pako": { + "registryUrl": "https://www.npmjs.com/package/@types/pako", + "homepageUrl": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/pako", + "necessity": "Type declarations for the pako incremental compression API used by the self-host git engine and its resource-boundary tests." + }, "@typescript-eslint/eslint-plugin": { "registryUrl": "https://www.npmjs.com/package/@typescript-eslint/eslint-plugin", "necessity": "Hosts supported TypeScript lint rules." @@ -168,6 +173,11 @@ "registryUrl": "https://www.npmjs.com/package/oxlint", "necessity": "Measures native lint findings in shadow mode." }, + "pako": { + "registryUrl": "https://www.npmjs.com/package/pako", + "homepageUrl": "https://github.com/nodeca/pako", + "necessity": "Incremental zlib Inflate callbacks let the self-host-only git engine enforce output budgets before retaining decompressed objects; native one-shot decompression cannot apply those bounds. Excluded from the Cloudflare import graph." + }, "postal-mime": { "registryUrl": "https://www.npmjs.com/package/postal-mime", "homepageUrl": "https://github.com/postalsys/postal-mime", diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 2319791552..0d8ea2407a 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -23,7 +23,7 @@ Use existing L16 selection, extend its optional token context and fetch/import c - [ ] Local lint/typecheck/tests/build; security, Cloudflare, architecture and completion reviews - [ ] Draft PR then ready/CI/CodeRabbit request and wait - [ ] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off -- [ ] BOX existing bucket-mode deploy adds selfhost-hosted-git-v1; create project; OpenCode free reply; agent push verified; cleanup and BOX FREE +- [x] BOX existing bucket-mode deploy adds selfhost-hosted-git-v1; create project; OpenCode free reply; agent push verified; cleanup and BOX FREE - [ ] Merge main; all gates current head; announce merging/merged SHA; production success; idea SHIPPED ## Acceptance @@ -33,3 +33,5 @@ No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; ## Implementation evidence Stacked L22c539625202 per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite19/19 (real git18 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. + +BOX proof: existing795bf674f upgraded bucket-mode to a7cad then f6c65e71a healthy, celld tag confirmed. Hosted project01M7SX75X1YVADRG9Z4AB4AMV0; OpenCode big-pickle task01M7SXCMYYTAB9DNCFFAZMM0G1 replied pong; cookie-free clone verified agent commitad485ee136d4c8469b1e05e2983e086dd9e9393b and h2-proof.txt=pong. Stop/node/project delete200; nodes empty/project404/GCP no matching VM. Test credential/key/firewall/scratch removed. BOX FREE channel sequence403. From 6324f09ca78607efb93e36c5b50ab1a0cd2340bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 13:19:37 +0000 Subject: [PATCH 43/65] fix: fence hosted git lifecycle and preserve native RPC behavior --- apps/api/src/routes/projects/crud.ts | 2 +- .../api/src/routes/projects/project-create.ts | 7 +- .../selfhost/hosted-git/hosted-git-ls-refs.ts | 6 +- .../selfhost/hosted-git/hosted-git-repo.ts | 74 ++++++--- apps/api/src/selfhost/hosted-git/limits.ts | 27 ++++ apps/api/src/selfhost/hosted-git/uploads.ts | 52 ++++++ apps/api/src/services/artifacts/backend.ts | 8 + apps/api/src/services/artifacts/settings.ts | 2 + apps/api/src/vendor/dgit/git/multipart.ts | 2 +- apps/api/src/vendor/dgit/git/objects.ts | 2 +- apps/api/src/vendor/dgit/git/oidset.ts | 2 +- apps/api/src/vendor/dgit/git/pack.ts | 2 +- apps/api/src/vendor/dgit/git/packstore.ts | 2 +- apps/api/src/vendor/dgit/git/pktline.ts | 2 +- apps/api/src/vendor/dgit/git/protocol.ts | 2 +- apps/api/src/vendor/dgit/git/sha1.ts | 2 +- apps/api/src/vendor/dgit/git/sha1dc-tables.ts | 2 +- apps/api/src/vendor/dgit/git/store.ts | 2 +- apps/api/src/vendor/dgit/git/util.ts | 2 +- apps/api/src/vendor/dgit/git/zlib.ts | 2 +- .../hosted-git/hosted-git-conformance.test.ts | 48 ++++++ .../hosted-git/support/hosted-git-entry.ts | 6 + .../hosted-git-ls-refs.test.ts | 8 + .../routes/project-artifacts-creation.test.ts | 16 ++ .../unit/routes/workspace-git-token.test.ts | 2 +- .../unit/selfhost/hosted-git-budget.test.ts | 2 +- .../unit/selfhost/hosted-git-deletion.test.ts | 152 ++++++++++++++++++ .../selfhost/hosted-git-gc-admission.test.ts | 1 + .../repo-hosting/src/repo-browse/artifacts.ts | 3 +- .../repo-browse-artifacts-backend.test.ts | 6 +- specs/001-mvp/contracts/api.md | 17 ++ 31 files changed, 421 insertions(+), 42 deletions(-) create mode 100644 apps/api/src/selfhost/hosted-git/uploads.ts create mode 100644 apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index b8037743f5..8cc77f5a3e 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -11,13 +11,13 @@ import { toProjectSummaryResponse } from '../../lib/mappers'; import { parsePositiveInt } from '../../lib/route-helpers'; import { getUserId } from '../../middleware/auth'; import { requireProjectCapability } from '../../middleware/project-auth'; +import { resolveArtifactsBackendForCleanup } from '../../services/artifacts/backend'; import { buildProjectLibraryDeleteStatements, buildProjectLibraryR2Prefix, deleteProjectLibraryObjects, getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; -import { resolveArtifactsBackendForCleanup } from '../../services/artifacts/backend'; import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; diff --git a/apps/api/src/routes/projects/project-create.ts b/apps/api/src/routes/projects/project-create.ts index 162c4d69f5..672851fb90 100644 --- a/apps/api/src/routes/projects/project-create.ts +++ b/apps/api/src/routes/projects/project-create.ts @@ -13,7 +13,7 @@ import { getUserId } from '../../middleware/auth'; import { AppError, errors } from '../../middleware/error'; import { createOwnerProjectMembership } from '../../middleware/project-auth'; import { CreateProjectSchema, jsonValidator } from '../../schemas'; -import { resolveArtifactsBackend } from '../../services/artifacts/backend'; +import { artifactsBackendExtensions, resolveArtifactsBackend } from '../../services/artifacts/backend'; import { seedArtifactsReadme } from '../../services/artifacts/seed-readme'; import { getExternalInstallationId } from '../../services/github-installation-ids'; import { @@ -104,7 +104,8 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): } const importUrl = body.importUrl?.trim() || null; - const importer = artifacts.importSource; + const extensions = artifactsBackendExtensions(c.env, artifacts); + const importer = extensions.importSource; if (importUrl && !importer) { throw errors.badRequest('This repository backend does not support importUrl'); } @@ -157,7 +158,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): branch: defaultBranch, projectName: name, description, - fetchImpl: artifacts.remoteFetch, + fetchImpl: extensions.remoteFetch, }); } } catch (seedError) { diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts b/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts index 9828e10f95..ca8c840382 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts @@ -5,8 +5,7 @@ * always answers HEAD plus every ref. Git's protocol v2 says a server given `ref-prefix` arguments * shows only refs that start with one of them (gitprotocol-v2, "ls-refs"). Clients that rely on it, * such as isomorphic-git's `listServerRefs({ prefix: 'refs/heads/' })` behind the project's branch - * list, then saw "HEAD" as a branch (box round R13 D11). The vendored files stay a byte copy of - * upstream (UPSTREAM.md), so the filter lives here, applied by the Durable Object to the answer. + * list, then saw "HEAD" as a branch (box round R13 D11). The SAM adaptation is recorded in UPSTREAM.md; this filter is applied by the Durable Object. */ import { FLUSH, pkt, PktParser } from '../../vendor/dgit/git/pktline'; import { concat } from '../../vendor/dgit/git/util'; @@ -39,7 +38,8 @@ export async function filterLsRefsResponse( prefixes: readonly string[] ): Promise { const body = new Uint8Array(await response.arrayBuffer()); - if (body.length > MAX_LS_REFS_RESPONSE_BYTES) return response; + if (body.length > MAX_LS_REFS_RESPONSE_BYTES) + return new Response('error: ref advertisement exceeds maximum size\n', { status: 413 }); const parser = new PktParser(body); const kept: Uint8Array[] = []; for (let p = parser.read(); p !== null; p = parser.read()) { diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index c741cf85f2..3ef09fda3c 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -36,8 +36,10 @@ import { hostedGitPushByteBudget, hostedGitPushRefusal, hostedGitPushTooLargeMessage, + hostedGitRefRefusal, } from './limits'; import { resolveHostedGitLimits } from './policy'; +import { HostedGitUploads } from './uploads'; /** An upload-pack request is wants/haves/caps only. */ const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; @@ -113,6 +115,9 @@ export class HostedGitRepo extends DurableObject { /** Pushes are serialized: concurrent ingests would race pack-id allocation. */ private receiveChain: Promise = Promise.resolve(); private activeUploads = 0; + private readonly uploads = new HostedGitUploads(); + private deletion: Promise | undefined; + private deleting = false; constructor(ctx: DurableObjectState, env: unknown) { super(ctx, env as never); @@ -130,6 +135,32 @@ export class HostedGitRepo extends DurableObject { const url = new URL(req.url); const path = url.pathname; try { + if (path === '/' && req.method === 'DELETE') { + this.deleting = true; + this.deletion ??= this.receiveChain + .then(async () => { + await this.uploads.close(); + await this.ctx.blockConcurrencyWhile(async () => { + // Preserve celld replication control tables; deleteAll would remove them. + this.store.setMeta('deleted', '1'); + this.ctx.storage.transactionSync(() => { + this.store.wipe(); + this.store = new GitStore(this.ctx.storage.sql); + this.store.setMeta('deleted', '1'); + }); + await this.ctx.storage.deleteAlarm(); + }); + }) + .catch((error) => { + this.deletion = undefined; + throw error; + }); + this.receiveChain = this.deletion.catch(() => undefined); + await this.deletion; + return new Response('deleted\n'); + } + if (this.deleting || this.store.getMeta('deleted') === '1') + return new Response('repository deleted\n', { status: 410 }); if (path === '/info/refs' && req.method === 'GET') { const service = url.searchParams.get('service'); if (service !== 'git-upload-pack' && service !== 'git-receive-pack') { @@ -167,16 +198,6 @@ export class HostedGitRepo extends DurableObject { bytes: this.store.dbSize(), }); } - if (path === '/' && req.method === 'DELETE') { - await this.ctx.blockConcurrencyWhile(async () => { - // wipe() drops dgit's tables. Not storage.deleteAll(): on celld that also sweeps the - // replication control tables and breaks WAL capture for the cell (upstream note). - this.store.wipe(); - await this.ctx.storage.deleteAlarm(); - this.store = new GitStore(this.ctx.storage.sql); - }); - return new Response('deleted\n'); - } return new Response('not found\n', { status: 404 }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); @@ -193,7 +214,7 @@ export class HostedGitRepo extends DurableObject { } private async runAlarm(): Promise { - if (this.store.getMeta('gc-pending') !== '1') return; + if (this.deleting || this.store.getMeta('gc-pending') !== '1') return; // GC drops packs: never while a clone is streaming. Leave gc-pending set and retry. if (this.activeUploads > 0) { await this.ctx.storage.setAlarm(Date.now() + 30_000).catch(() => undefined); @@ -245,21 +266,33 @@ export class HostedGitRepo extends DurableObject { } // The slot spans the whole response stream; release() fires once from close/cancel. this.activeUploads++; + const slot = this.uploads.start(); let released = false; const release = () => { if (released) return; released = true; this.activeUploads--; + slot.release(); }; try { let body = await readBodyBounded(req, MAX_UPLOAD_PACK_BYTES); + if (this.deleting) { + release(); + return new Response('repository deleted\n', { status: 410 }); + } if (req.headers.get('content-encoding')?.includes('gzip')) { body = gunzipLimited(body, MAX_UPLOAD_PACK_BYTES); } // dgit answers ls-refs with every ref whatever `ref-prefix` asks; filter the answer here. const prefixes = lsRefsPrefixes(body); const response = await uploadPack(this.store, body, release); - return prefixes ? await filterLsRefsResponse(response, prefixes) : response; + const filtered = prefixes ? await filterLsRefsResponse(response, prefixes) : response; + if (this.deleting) { + await filtered.body?.cancel(); + release(); + return new Response('repository deleted\n', { status: 410 }); + } + return slot.response(filtered); } catch (err) { release(); if ( @@ -285,6 +318,7 @@ export class HostedGitRepo extends DurableObject { headers: { 'content-type': 'text/plain; charset=utf-8' }, }); } + if (this.deleting) return new Response('repository deleted\n', { status: 410 }); const chunks: Uint8Array[] = []; const run = this.receiveChain.then(() => this.processReceive(req, (c) => chunks.push(c))); this.receiveChain = run.then( @@ -365,7 +399,7 @@ export class HostedGitRepo extends DurableObject { // Read up to the pack header so the declared object count can be checked before storing. const packStart = pos; const hasPack = (await need(PACK_HEADER_BYTES)) || buf.length > packStart; - let unpackError: string | null = null; + let unpackError = hostedGitRefRefusal(this.store.refs(), commands, currentBytes, limits); let packId: number | null = null; if (hasPack) { const header = buf.subarray(packStart, packStart + PACK_HEADER_BYTES); @@ -373,11 +407,13 @@ export class HostedGitRepo extends DurableObject { header.length === PACK_HEADER_BYTES ? new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8) : 0; - const refusal = hostedGitPushRefusal( - { objects: this.store.objectCount(), bytes: currentBytes }, - incomingObjects, - limits - ); + const refusal = + unpackError ?? + hostedGitPushRefusal( + { objects: this.store.objectCount(), bytes: currentBytes }, + incomingObjects, + limits + ); if (refusal) { unpackError = refusal; } else { @@ -418,7 +454,7 @@ export class HostedGitRepo extends DurableObject { this.store.setMeta('created', '1'); this.store.setMeta('last-push', String(Date.now())); } - if (needsGc) { + if (needsGc || packId !== null) { this.store.setMeta('gc-pending', '1'); await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS).catch(() => undefined); } diff --git a/apps/api/src/selfhost/hosted-git/limits.ts b/apps/api/src/selfhost/hosted-git/limits.ts index 388e7bb9f2..e11162c8d2 100644 --- a/apps/api/src/selfhost/hosted-git/limits.ts +++ b/apps/api/src/selfhost/hosted-git/limits.ts @@ -64,3 +64,30 @@ export function hostedGitPushByteBudget(currentBytes: number, limits: HostedGitL export function hostedGitPushTooLargeMessage(maxBytes: number): string { return `SAM: push refused: the pack is larger than the ${mib(maxBytes)} limit for one push to a SAM-hosted repository; push in smaller pieces`; } + +/** Check ref-only pushes too. Reserve a SQLite page per new ref, including index overhead. */ +export function hostedGitRefRefusal( + existing: readonly { name: string }[], + commands: readonly { ref: string; next: string }[], + currentBytes: number, + limits: HostedGitLimits +): string | null { + const refs = new Set(existing.map((ref) => ref.name)); + let additions = 0; + let writes = false; + for (const command of commands) { + // Do not credit deletions: their old-OID check may fail while an addition succeeds. + if (command.next !== '0'.repeat(40)) { + writes = true; + if (!refs.has(command.ref)) additions++; + refs.add(command.ref); + } + } + // Deletions remain available when an administrator lowers a limit below current usage. + if (!writes) return null; + if (refs.size > limits.maxRepoRefs) + return `SAM: push refused: repository exceeds its ${limits.maxRepoRefs}-ref limit`; + if (currentBytes + additions * 4096 >= limits.maxRepoBytes) + return 'SAM: push refused: repository storage limit leaves no room for ref updates'; + return null; +} diff --git a/apps/api/src/selfhost/hosted-git/uploads.ts b/apps/api/src/selfhost/hosted-git/uploads.ts new file mode 100644 index 0000000000..7031eea6ed --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/uploads.ts @@ -0,0 +1,52 @@ +/** Tracks fetch readers so deletion can close streams before dropping their backing packs. */ +export class HostedGitUploads { + private slots = new Set<{ done: Promise; cancel?: () => Promise }>(); + start() { + let finish = () => {}; + const slot: { done: Promise; cancel?: () => Promise } = { + done: new Promise((resolve) => { + finish = resolve; + }), + }; + this.slots.add(slot); + const release = () => { + this.slots.delete(slot); + finish(); + }; + return { + release, + response: (response: Response): Response => { + if (!response.body || !this.slots.has(slot)) return response; + const reader = response.body.getReader(); + slot.cancel = async () => { + await reader.cancel().catch(() => undefined); + release(); + }; + return new Response( + new ReadableStream({ + async pull(controller) { + try { + const { done, value } = await reader.read(); + if (done) { + release(); + controller.close(); + } else controller.enqueue(value); + } catch (error) { + release(); + controller.error(error); + } + }, + cancel: slot.cancel, + }), + { status: response.status, headers: response.headers } + ); + }, + }; + } + async close(): Promise { + const slots = [...this.slots]; + await Promise.all(slots.map((slot) => slot.cancel?.())); + // Request bodies have a work deadline; their handlers release after seeing the delete fence. + await Promise.all(slots.map((slot) => slot.done)); + } +} diff --git a/apps/api/src/services/artifacts/backend.ts b/apps/api/src/services/artifacts/backend.ts index 0950451dff..8db5426b28 100644 --- a/apps/api/src/services/artifacts/backend.ts +++ b/apps/api/src/services/artifacts/backend.ts @@ -58,3 +58,11 @@ export function resolveArtifactsBackendForCleanup(env: Env): ArtifactsBackend | export function isArtifactsAvailable(env: Env): boolean { return resolveArtifactsBackend(env) !== null; } + +/** Native RPC stubs synthesize properties for unknown methods; never probe optional extensions. */ +export function artifactsBackendExtensions( + env: Env, + backend: ArtifactsBackend +): Pick { + return env.ARTIFACTS ? {} : backend; +} diff --git a/apps/api/src/services/artifacts/settings.ts b/apps/api/src/services/artifacts/settings.ts index a882703e89..2ef5f2126b 100644 --- a/apps/api/src/services/artifacts/settings.ts +++ b/apps/api/src/services/artifacts/settings.ts @@ -4,6 +4,8 @@ import { type AdminSettingDefinition, integerDefinition } from '../admin-setting export const REPOSITORY_POLICY_DEFAULTS = { maxPushBytes: 64 * 1024 * 1024, maxRepoObjects: 30_000, + // At 255 characters per ref, even UTF-8 advertisements stay below 12 MiB. + maxRepoRefs: 10_000, maxRepoBytes: 256 * 1024 * 1024, maxObjectBytes: 16 * 1024 * 1024, maxInflatedBytes: 128 * 1024 * 1024, diff --git a/apps/api/src/vendor/dgit/git/multipart.ts b/apps/api/src/vendor/dgit/git/multipart.ts index 8f353d5c84..8200b69948 100644 --- a/apps/api/src/vendor/dgit/git/multipart.ts +++ b/apps/api/src/vendor/dgit/git/multipart.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { concat } from "./util"; /** In-progress R2 multipart upload for one pack object (clone cache or raw store). */ diff --git a/apps/api/src/vendor/dgit/git/objects.ts b/apps/api/src/vendor/dgit/git/objects.ts index 33ad8dc955..02445715cd 100644 --- a/apps/api/src/vendor/dgit/git/objects.ts +++ b/apps/api/src/vendor/dgit/git/objects.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { te, td, toHex, concat, sha1hex, isOid } from "./util"; export type ObjType = "commit" | "tree" | "blob" | "tag"; diff --git a/apps/api/src/vendor/dgit/git/oidset.ts b/apps/api/src/vendor/dgit/git/oidset.ts index 22e84d8fe4..0af9c7d6ab 100644 --- a/apps/api/src/vendor/dgit/git/oidset.ts +++ b/apps/api/src/vendor/dgit/git/oidset.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { fromHex, toHex } from "./util"; /** diff --git a/apps/api/src/vendor/dgit/git/pack.ts b/apps/api/src/vendor/dgit/git/pack.ts index ad55b59d81..f2099646ca 100644 --- a/apps/api/src/vendor/dgit/git/pack.ts +++ b/apps/api/src/vendor/dgit/git/pack.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { chargeGitWork } from "./budget"; import { te, fromHex, Sha1 } from "./util"; import { deflate } from "./zlib"; diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts index 86cf6d4618..1011c5f99d 100644 --- a/apps/api/src/vendor/dgit/git/packstore.ts +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) // FILE SIZE EXCEPTION: vendored dgit core with SAM resource bounds and static SQL identifiers (see ../UPSTREAM.md) import pako from "pako"; import { inflate as inflateAll } from "./zlib"; diff --git a/apps/api/src/vendor/dgit/git/pktline.ts b/apps/api/src/vendor/dgit/git/pktline.ts index 9ba8d573cf..553b7b6e3e 100644 --- a/apps/api/src/vendor/dgit/git/pktline.ts +++ b/apps/api/src/vendor/dgit/git/pktline.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { te, td, concat } from "./util"; export const FLUSH = te.encode("0000"); diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 5ee4e9f6b3..e806640a88 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) // FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) import { concat, isOid, ZERO_OID, te } from "./util"; import { pkt, FLUSH, PktParser } from "./pktline"; diff --git a/apps/api/src/vendor/dgit/git/sha1.ts b/apps/api/src/vendor/dgit/git/sha1.ts index 1e3fbb2502..2f9cd07fec 100644 --- a/apps/api/src/vendor/dgit/git/sha1.ts +++ b/apps/api/src/vendor/dgit/git/sha1.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { SHA1_DVS, ubcCheck } from "./sha1dc-tables"; /** diff --git a/apps/api/src/vendor/dgit/git/sha1dc-tables.ts b/apps/api/src/vendor/dgit/git/sha1dc-tables.ts index 20a2161ff7..65a1bfd5b8 100644 --- a/apps/api/src/vendor/dgit/git/sha1dc-tables.ts +++ b/apps/api/src/vendor/dgit/git/sha1dc-tables.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) // GENERATED — do not edit by hand. // Transcribed from sha1collisiondetection/lib/ubc_check.c (Marc Stevens, Dan // Shumow; MIT). Regenerate with scripts/gen-sha1dc-tables.mjs. diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index dc5dcf4bfe..4eae2d27b4 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import { gitWorkLimits } from "./budget"; import { concat, te, sha1hex } from "./util"; import { deflate, inflate } from "./zlib"; diff --git a/apps/api/src/vendor/dgit/git/util.ts b/apps/api/src/vendor/dgit/git/util.ts index 8904fc8af8..29d4132377 100644 --- a/apps/api/src/vendor/dgit/git/util.ts +++ b/apps/api/src/vendor/dgit/git/util.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) export const te = new TextEncoder(); export const td = new TextDecoder(); diff --git a/apps/api/src/vendor/dgit/git/zlib.ts b/apps/api/src/vendor/dgit/git/zlib.ts index ab04541214..9979abb537 100644 --- a/apps/api/src/vendor/dgit/git/zlib.ts +++ b/apps/api/src/vendor/dgit/git/zlib.ts @@ -1,5 +1,5 @@ -// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) /* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) import pako from "pako"; import { chargeGitWork, gitWorkLimits } from "./budget"; import { concat } from "./util"; diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index d064a56184..fe10ae9fa2 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -724,3 +724,51 @@ describe('vertical: project creation to a workspace clone and push', () => { expect(refused.code).not.toBe(0); }); }); + +describe('ref-only push admission', () => { + it('caps new refs without a pack, while permitting recovery by deleting refs', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Ref cap'); + const token = await mintToken(project, 'write'); + const work = await freshDir('ref-cap'); + await gitOk(['clone', localRemote(project.repository, token), work]); + const setting = runtime.DATABASE.prepare( + "INSERT OR REPLACE INTO platform_settings(key,value) VALUES ('repositories.maxRepoRefs',?)" + ); + try { + await setting.bind('2').run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + await gitOk(['push', 'origin', 'HEAD:refs/heads/second'], work); + // A stale deletion must not create capacity for a partially accepted mixed push. + const tip = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + const packet = (line: string) => + (Buffer.byteLength(line) + 4).toString(16).padStart(4, '0') + line; + const mixed = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body: + packet(`${'1'.repeat(40)} ${'0'.repeat(40)} refs/heads/second\0report-status\n`) + + packet(`${'0'.repeat(40)} ${tip} refs/heads/third\n`) + + '0000', + }); + expect(await mixed.text()).toContain('2-ref limit'); + const refs = (await gitOk(['ls-remote', 'origin'], work)).stdout; + expect(refs).toContain('refs/heads/second'); + expect(refs).not.toContain('refs/heads/third'); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/third'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain('2-ref limit'); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/third'); + await gitOk(['push', 'origin', '--delete', 'second'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/third'], work); + } finally { + await runtime.DATABASE.prepare( + "DELETE FROM platform_settings WHERE key='repositories.maxRepoRefs'" + ).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); +}); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index ff97451ca6..299aea4c3e 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -8,6 +8,7 @@ // The production entry (src/index.ts, imported by the celld entry) wires repo-hosting's ports // first; the branch list, project create and import reach them, so this entry must too. import '../../../src/repo-hosting-wiring'; +import { invalidateAdminSettings } from '../../../src/services/admin-settings-resolution'; import { Hono } from 'hono'; @@ -86,3 +87,8 @@ app.post('/__test/workspace-callback-token', async (c) => { }); export default app; + +app.post('/__test/invalidate-settings', (c) => { + invalidateAdminSettings(c.env); + return new Response('ok'); +}); diff --git a/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts index 1396e266cc..a2981eaac5 100644 --- a/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts +++ b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts @@ -81,3 +81,11 @@ describe('ls-refs ref-prefix', () => { ]); }); }); + +it('rejects an oversized advertisement with a readable response', async () => { + const response = await filterLsRefsResponse(new Response(new Uint8Array(16 * 1024 * 1024 + 1)), [ + 'refs/heads/', + ]); + expect(response.status).toBe(413); + expect(await response.text()).toContain('advertisement exceeds'); +}); diff --git a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts index abd40073c5..ade1f18b52 100644 --- a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts +++ b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts @@ -131,6 +131,22 @@ describe('POST /api/projects — Artifacts provider through the hosted-git seam' expect(insertedRows[0]).toMatchObject({ repoProvider: 'artifacts', repository: remote }); }); + it('does not probe optional extension methods on a native RPC binding', async () => { + const remote = 'https://acct.artifacts.cloudflare.net/git/default/hosted-project-r1.git'; + const binding = new Proxy(backend(remote), { get(target, property, receiver) { + if (!(property in target)) return vi.fn().mockRejectedValue(new Error('Unknown RPC method')); + return Reflect.get(target, property, receiver); + } }); + limitResponses.push([], [{ id: 'x', repository: remote }]); + mocks.seedArtifactsReadme.mockImplementationOnce(async (options) => { + if (options.fetchImpl) await options.fetchImpl(options.remote); + }); + const response = await createArtifactsProject({ ...mockEnv, ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding } as Env); + expect(response.status).toBe(201); + expect(binding.create).toHaveBeenCalledOnce(); + expect(mocks.seedArtifactsReadme).toHaveBeenCalledWith(expect.objectContaining({ fetchImpl: undefined })); + }); + it('creates the repository with a registered self-host backend when no binding exists', async () => { const remote = 'https://api.sam.example/git/hosted-project-r1.git'; const hosted = backend(remote); diff --git a/apps/api/tests/unit/routes/workspace-git-token.test.ts b/apps/api/tests/unit/routes/workspace-git-token.test.ts index 8c4f88571e..f7d0f97cea 100644 --- a/apps/api/tests/unit/routes/workspace-git-token.test.ts +++ b/apps/api/tests/unit/routes/workspace-git-token.test.ts @@ -4,9 +4,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { runtimeRoutes } from '../../../src/routes/workspaces/runtime'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; import { getInstallationToken } from '../../../src/services/github-app'; import { GitHubCliPolicyError } from '../../../src/services/github-cli-policy'; -import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; const mocks = vi.hoisted(() => ({ getInstallationToken: vi.fn(), diff --git a/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts index c7162e4ced..6a9f49e34f 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts @@ -5,8 +5,8 @@ import { readGitChunk, withGitWorkBudget, } from '../../../src/vendor/dgit/git/budget'; -import { deflate, inflate } from '../../../src/vendor/dgit/git/zlib'; import { applyDelta } from '../../../src/vendor/dgit/git/pack'; +import { deflate, inflate } from '../../../src/vendor/dgit/git/zlib'; const limits = { maxObjectBytes: 32, maxInflatedBytes: 48, maxDeltaDepth: 2, workTimeoutMs: 1000 }; diff --git a/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts new file mode 100644 index 0000000000..3b62668caf --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts @@ -0,0 +1,152 @@ +import { beforeEach, expect, it, vi } from 'vitest'; + +import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo'; +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +const state = vi.hoisted(() => ({ + meta: new Map(), + events: [] as string[], + validate: vi.fn(), + setAlarm: vi.fn(async () => undefined), + cancel: vi.fn(), + deleteAlarm: vi.fn(async () => undefined), +})); +vi.mock('cloudflare:workers', () => ({ + DurableObject: class { + constructor(public ctx: unknown) {} + }, +})); +vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ + resolveHostedGitLimits: async () => DEFAULT_HOSTED_GIT_LIMITS, +})); +vi.mock('../../../src/vendor/dgit/git/store', () => ({ + GitStore: class { + getMeta(key: string) { + return state.meta.get(key); + } + setMeta(key: string, value: string) { + state.meta.set(key, value); + } + refs() { + return []; + } + dbSize() { + return 0; + } + objectCount() { + return 0; + } + wipe() { + state.events.push('wipe'); + state.meta.clear(); + } + packs = { ingest: async () => ({ packId: 1 }) }; + }, +})); +vi.mock('../../../src/vendor/dgit/git/protocol', () => ({ + advertisement: () => new Uint8Array(), + parsePushCommands: () => ({ commands: [], caps: [] }), + sidebandFrames: () => [], + renderStatus: () => new Uint8Array(), + validatePush: (...args: unknown[]) => state.validate(...args), + commitPush: () => { + state.events.push('commit'); + return { results: [], changed: false, needsGc: false }; + }, + uploadPack: async (_store: unknown, _body: unknown, release: () => void) => + new Response( + new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array(1024)); + }, + cancel() { + state.cancel(); + release(); + }, + }) + ), +})); +function repo() { + return new HostedGitRepo( + { + storage: { + sql: {}, + deleteAlarm: state.deleteAlarm, + setAlarm: state.setAlarm, + transactionSync: (fn: () => unknown) => fn(), + }, + blockConcurrencyWhile: async (fn: () => Promise) => fn(), + } as unknown as DurableObjectState, + {} + ); +} +beforeEach(() => { + vi.clearAllMocks(); + state.meta.clear(); + state.events = []; + state.validate.mockResolvedValue({}); +}); +it('DELETE waits for an accepted push, then fences new writes and persists deletion', async () => { + let resume = () => {}; + state.validate.mockImplementationOnce( + () => + new Promise((resolve) => { + resume = () => resolve({}); + }) + ); + const cell = repo(); + const push = cell.fetch( + new Request('https://git/git-receive-pack', { method: 'POST', body: '0000' }) + ); + await vi.waitFor(() => expect(state.validate).toHaveBeenCalledOnce()); + const deletion = cell.fetch(new Request('https://git/', { method: 'DELETE' })); + await vi.waitFor(async () => + expect( + (await cell.fetch(new Request('https://git/init', { method: 'PUT', body: '{}' }))).status + ).toBe(410) + ); + expect(state.events).toEqual([]); + resume(); + expect((await push).status).toBe(200); + expect((await deletion).status).toBe(200); + expect(state.events).toEqual(['commit', 'wipe']); + expect( + (await repo().fetch(new Request('https://git/init', { method: 'PUT', body: '{}' }))).status + ).toBe(410); +}); +it('DELETE cancels an active clone stream before wiping its packs', async () => { + const cell = repo(); + const upload = await cell.fetch( + new Request('https://git/git-upload-pack', { method: 'POST', body: '0000' }) + ); + expect((await cell.fetch(new Request('https://git/', { method: 'DELETE' }))).status).toBe(200); + expect(state.cancel).toHaveBeenCalledOnce(); + expect(state.events).toEqual(['wipe']); + await upload.body?.cancel(); +}); +it('schedules collection for an ingested pack even when all ref updates are rejected', async () => { + const cell = repo(); + expect( + ( + await cell.fetch( + new Request('https://git/git-receive-pack', { + method: 'POST', + body: new Uint8Array([48, 48, 48, 48, 80, 65, 67, 75, 0, 0, 0, 2, 0, 0, 0, 0]), + }) + ) + ).status + ).toBe(200); + expect(state.setAlarm).toHaveBeenCalledOnce(); + expect(state.meta.get('gc-pending')).toBe('1'); +}); + +it('retries failed cleanup while keeping all writes fenced', async () => { + state.deleteAlarm.mockRejectedValueOnce(new Error('temporary storage failure')); + const cell = repo(); + expect((await cell.fetch(new Request('https://git/', { method: 'DELETE' }))).status).toBe(500); + expect( + (await cell.fetch(new Request('https://git/init', { method: 'PUT', body: '{}' }))).status + ).toBe(410); + expect((await cell.fetch(new Request('https://git/', { method: 'DELETE' }))).status).toBe(200); + expect(state.deleteAlarm).toHaveBeenCalledTimes(2); + expect(state.meta.get('deleted')).toBe('1'); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts index 7304e1f381..7b8f9450b0 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; + import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo'; import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; const mocks = vi.hoisted(() => ({ diff --git a/packages/repo-hosting/src/repo-browse/artifacts.ts b/packages/repo-hosting/src/repo-browse/artifacts.ts index 4a4203da0a..19756ed8fe 100644 --- a/packages/repo-hosting/src/repo-browse/artifacts.ts +++ b/packages/repo-hosting/src/repo-browse/artifacts.ts @@ -182,7 +182,8 @@ export class ArtifactsRepoBrowser implements RepoBrowser { return { remote, onAuth, - http: binding.remoteFetch ? createFetchHttpClient(binding.remoteFetch) : webHttp, + // Native RPC bindings fabricate unknown methods; extensions belong to the fallback. + http: !this.env.ARTIFACTS && binding.remoteFetch ? createFetchHttpClient(binding.remoteFetch) : webHttp, }; })(); } diff --git a/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts b/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts index af51341062..31fbf6333a 100644 --- a/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts +++ b/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts @@ -71,11 +71,15 @@ describe('resolveRepoBrowser for Artifacts projects', () => { }); it('uses the Cloudflare binding directly when present (unchanged)', async () => { - const binding = hostedBackend(); + const binding = new Proxy(hostedBackend(), { get(target, property, receiver) { + if (!(property in target)) return vi.fn().mockRejectedValue(new Error('Unknown RPC method')); + return Reflect.get(target, property, receiver); + } }); resolve.mockImplementation((env) => env.ARTIFACTS ?? null); const env = { ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding } as Env; const browser = await resolveRepoBrowser({ project, env }); await browser.listBranches(); expect(binding.get).toHaveBeenCalledWith('repo-1'); + expect(iso.listServerRefs).toHaveBeenCalledWith(expect.objectContaining({ http: {} })); }); }); diff --git a/specs/001-mvp/contracts/api.md b/specs/001-mvp/contracts/api.md index aa07325002..0685435c8b 100644 --- a/specs/001-mvp/contracts/api.md +++ b/specs/001-mvp/contracts/api.md @@ -858,3 +858,20 @@ The existing publish-job events, artifact init/complete and compose release call `POST /api/auth/unlink-account` accepts BetterAuth `{accountId}`. Only the caller's GitHub/GitLab accounts can be removed; removing the last provider requires usable verified email sign-in. The affected account owner receives a linked-provider security notification at their preserved SAM email. Explicit links may have a different provider email; future sign-ins preserve an already-verified SAM email. A lookup failure aborts sign-in rather than replacing identity. GitHub repository errors distinguish `403 GITHUB_NOT_CONNECTED`, `401 GITHUB_REAUTH_REQUIRED`, `503 GITHUB_UNAVAILABLE`, `409 GITHUB_APP_NOT_CONFIGURED` and `404 FEATURE_UNAVAILABLE`. Only actual authorization failures request reauthentication; provider outages offer retry. Unverified provider-linked accounts receive a provider-sign-in note instead of an email code, and code redemption is refused without deleting links or sessions. + +## Self-hosted repository credentials + +### POST /api/projects/{id}/hosted-git/token + +Available only on self-host installations using the local hosted Git backend. Requires an +approved, session-authenticated user. The `scope` query parameter is `write` for push access; +all other values (including omission) select `read`. Read requires `project:read`; write +requires `workspace:write` on the addressed project. No request body is required. + +Returns `200` with `{ cloneUrl, host, username: "x", token, scope, expiresAt }`. `expiresAt` +is the token's expiry timestamp in ISO 8601 format. Use `username` and `token` as Git HTTP Basic +credentials; keep the short-lived token private. This personal token is not workspace-bound. + +Returns `401` for missing authentication, `403` for insufficient capability, and `404` when +the project is absent or does not use this installation's local hosted Git backend. Cloudflare +Workers do not register this endpoint and return `404`; their Artifacts and forge behavior is unchanged. From 4e1f20890c32c6605cbadcfe07aa9083bac3f09a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 13:21:59 +0000 Subject: [PATCH 44/65] docs: record hosted git review and live verification evidence --- apps/api/tests/hosted-git/support/hosted-git-entry.ts | 2 +- tasks/active/2026-11-19-selfhost-hosted-git-h2.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index 299aea4c3e..ab0016e7cb 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -8,7 +8,6 @@ // The production entry (src/index.ts, imported by the celld entry) wires repo-hosting's ports // first; the branch list, project create and import reach them, so this entry must too. import '../../../src/repo-hosting-wiring'; -import { invalidateAdminSettings } from '../../../src/services/admin-settings-resolution'; import { Hono } from 'hono'; @@ -21,6 +20,7 @@ import { HostedGitRepo, mountHostedGitRoute } from '../../../src/selfhost/hosted import type { HostedGitEnv as Env } from '../../../src/selfhost/hosted-git/env'; import { hostedGitTokenRoutes } from '../../../src/selfhost/hosted-git/token-route'; import { type HostedGitScope, mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; +import { invalidateAdminSettings } from '../../../src/services/admin-settings-resolution'; import { signCurrentWorkspaceCallbackToken } from '../../../src/services/jwt'; /** Test-only: run the GC alarm on demand (production schedules it 5 minutes after a push). */ diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 0d8ea2407a..fab49122bd 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -35,3 +35,8 @@ No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; Stacked L22c539625202 per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite19/19 (real git18 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. BOX proof: existing795bf674f upgraded bucket-mode to a7cad then f6c65e71a healthy, celld tag confirmed. Hosted project01M7SX75X1YVADRG9Z4AB4AMV0; OpenCode big-pickle task01M7SXCMYYTAB9DNCFFAZMM0G1 replied pong; cookie-free clone verified agent commitad485ee136d4c8469b1e05e2983e086dd9e9393b and h2-proof.txt=pong. Stop/node/project delete200; nodes empty/project404/GCP no matching VM. Test credential/key/firewall/scratch removed. BOX FREE channel sequence403. + + +Review follow-up at 0f504c8dc: security PASS (independent 19 tests), Cloudflare PASS (54 tests), architecture PASS. Ref-only pushes now have an administrator-lowerable 10,000-ref cap and storage reservation; deletions do not earn admission capacity before old-OID validation (delete then add as separate pushes at the cap). Real HTTP mixed stale-delete/new-ref test fails when that protection is removed. DELETE queues behind accepted pushes, cancels clone streams, persists a tombstone and transactionally wipes/reinitializes; cleanup failures can retry while writes stay fenced. Mutex-negative probe fails the overlapping push/delete test. Ingested packs schedule GC even if every ref is rejected; oversized ls-refs returns a readable 413. Personal token endpoint is documented in API contract. + +Primary staging f6 deployment44527475370 passed deploy/smokes. Live Artifacts creation exposed a native RPC regression: optional extension property reads synthesize RPC methods. Fixed by selecting empty extensions when the native binding exists; only the registered fallback supplies import/fetch. Native browser transport similarly avoids extension probing. Proxy-shaped route and browser tests cover this; removing the guard makes the route test fail. Replacement deploy44532452799 at0f504c8dc pending. No staging project or VM persisted from failed seed (route cleans the orphan). CF settings independently confirm native ARTIFACTS present, hosted binding/DO absent. Browser project list loaded with zero page errors. Artifacts/GitHub creation gates remain pending the replacement deployment. From 8c7927e6034424139feabd01637b16f8c36238be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 13:24:24 +0000 Subject: [PATCH 45/65] docs: clarify hosted git ref bounds and vendor adaptations --- apps/api/src/vendor/dgit/UPSTREAM.md | 16 ++++++++-------- deploy/selfhost/README.md | 5 +++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 2ec490e417..3249b052ba 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -6,29 +6,29 @@ ## What is here -Local change to every vendored file: two header lines, `// @ts-nocheck` and -`/* eslint-disable */`. Upstream typechecks under `strict` but not SAM's +Vendored files carry `/* eslint-disable */` and `// @ts-nocheck` headers. Upstream typechecks under `strict` but not SAM's `noUncheckedIndexedAccess`, and follows its own lint style. `protocol.ts` and `packstore.ts` also -carry a `// FILE SIZE EXCEPTION` line. Nothing else differs from upstream. +carry a `// FILE SIZE EXCEPTION` line. SAM security adaptations are listed below. -`git/` is upstream `src/git/` copied byte for byte, minus the three modules only the web UI +`git/` is adapted from upstream `src/git/`, minus the three modules only the web UI used (`blame.ts`, `diff.ts`, `snapshot.ts`). Upstream's Worker router (`mod.ts`), registry Durable Object (`registry.ts`), cgit-style UI (`ui/`) and its `RepoCell` class are not vendored. Only the self-host build contains this code; the Cloudflare Worker's entry never imports it (see `apps/api/src/selfhost/hosted-git.ts`). -SAM's Durable Object, `apps/api/src/durable-objects/hosted-git-repo.ts`, is adapted from +SAM's Durable Object, `apps/api/src/selfhost/hosted-git/hosted-git-repo.ts`, is adapted from upstream `src/repo.ts` (`RepoCell`): it keeps the smart-HTTP protocol paths (`info/refs`, `git-upload-pack`, `git-receive-pack`), delete and the GC alarm, and adds SAM's push and -repository caps. Authentication is SAM's (`apps/api/src/services/hosted-git/`), not upstream's. +repository caps. Authentication is SAM's (`apps/api/src/selfhost/hosted-git/`), not upstream's. ## Updating Copy the same files from a newer upstream commit, update the commit above, and run the hosted git -conformance suite (`pnpm --filter @simple-agent-manager/api test:hosted-git`). Do not edit files -under `git/` beyond those two header lines: keep local behaviour in the Durable Object so the next update is a copy. +conformance suite (`pnpm --filter @simple-agent-manager/api test:hosted-git`). Preserve and reapply the SAM resource policy and SQL safety changes below; an upstream copy alone would remove these protections. Keep repository authentication and lifecycle policy in the self-host adapter. ## H2 resource policy SAM adds `git/budget.ts` around pack ingest, reads and delta application. Every request and GC invocation carries a separate cumulative decompression and deadline budget, including streamed responses. Object size is checked before allocation and while inflating, delta targets before allocation, and delta depth before traversal. Policy values come from the optional repository backend's typed admin settings. These are deliberate security changes to the vendored code; this directory is not byte-for-byte upstream. + +SQL identifiers use static allowlisted statements, and variable-sized bind lists are split below the runtime parameter ceiling. The additional GC admission and response accounting checks are covered by the hosted git suite. diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index a57304ed1a..0ec126b240 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -210,11 +210,12 @@ A bounded importer is tracked in `tasks/backlog/2026-11-19-bounded-selfhost-git- GitHub and GitLab integrations remain available when configured. Admin → Settings exposes `repositories.*` limits. Defaults are 64 MiB per push, 30,000 objects -and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation +10,000 refs and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation per request, delta depth 100 and 120 seconds per git operation. Operators can lower these limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. Clone/push credentials expire and runtime credentials also require the same active workspace -and callback generation. Deleting a project removes its hosted repository. +and callback generation. Deleting a project removes its hosted repository. At the ref limit, delete old refs in a separate +push before creating replacements; an unvalidated deletion does not reserve space for new refs. ## Not included yet From e7ac643b18f4ca864e403d33f7fbcf7a1a5e8fe8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 13:28:03 +0000 Subject: [PATCH 46/65] test: exercise rejected pack GC and deletion on real SQLite --- .../hosted-git/hosted-git-conformance.test.ts | 37 +++++++++++++++++++ .../hosted-git/support/hosted-git-entry.ts | 13 +++++++ 2 files changed, 50 insertions(+) diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index fe10ae9fa2..8644f1821e 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -26,6 +26,7 @@ import { DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES, DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS, } from '../../src/selfhost/hosted-git/limits'; +import { buildReceivePackRequest,buildSeedPack } from '../../src/services/artifacts/seed-readme'; import { HOSTED_GIT_TEST_BASE_DOMAIN, type HostedGitRuntime, @@ -772,3 +773,39 @@ describe('ref-only push admission', () => { } }); }); + + +describe('repository cleanup through real SQLite', () => { + it('schedules and reclaims an ingested pack whose only ref update is rejected', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Rejected pack'); + const token = await mintToken(project, 'write'); + const info = async () => (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { objects: number }; + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + const idle = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json(); + expect(idle).toMatchObject({ pending: '0', alarm: null }); + const before = await info(); + const { pack, commitOid } = await buildSeedPack({ projectName: 'Unreachable rejected pack' }); + const rejected = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, 'content-type': 'application/x-git-receive-pack-request' }, + body: buildReceivePackRequest(commitOid, 'main', pack) as BodyInit, + }); + expect(await rejected.text()).toContain('ng refs/heads/main'); + expect((await info()).objects).toBeGreaterThan(before.objects); + const queued = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json() as { pending: string; alarm: number | null }; + expect(queued.pending).toBe('1'); expect(queued.alarm).not.toBeNull(); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect((await info()).objects).toBe(before.objects); + }); + it('transactionally deletes a populated repository and refuses later Git requests', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Delete me'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + expect((await git(['ls-remote', remote])).code).toBe(0); + expect((await runtime.fetch(`/__test/repository/${project.artifactsRepoId}`, { method: 'DELETE' })).status).toBe(200); + const after = await git(['ls-remote', remote]); + expect(after.code).not.toBe(0); expect(after.stderr).toContain('410'); + expect((await runtime.fetch(`/__test/repository/${project.artifactsRepoId}`, { method: 'DELETE' })).status).toBe(200); + }); +}); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index ab0016e7cb..17ab37b023 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -31,8 +31,12 @@ export class HostedGitRepoTest extends HostedGitRepo { "INSERT INTO meta (key, value) VALUES ('gc-pending', '1') ON CONFLICT(key) DO UPDATE SET value = '1'" ); await this.alarm(); + await this.ctx.storage.deleteAlarm(); return new Response('ok'); } + if (new URL(req.url).pathname === '/__test/gc-state') { + return Response.json({ pending: this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'").toArray()[0]?.value, alarm: await this.ctx.storage.getAlarm() }); + } return super.fetch(req); } } @@ -92,3 +96,12 @@ app.post('/__test/invalidate-settings', (c) => { invalidateAdminSettings(c.env); return new Response('ok'); }); + +app.get('/__test/gc-state/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/gc-state'); +}); +app.delete('/__test/repository/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/', { method: 'DELETE' }); +}); From c6a45ee23918fcff0b66ffe1c215e75055f01af7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 18:20:56 +0000 Subject: [PATCH 47/65] fix(selfhost): reclaim failed packs and retain bounded GC retries --- .../selfhost/hosted-git/hosted-git-repo.ts | 60 +++++++++++++++---- apps/api/src/services/artifacts/settings.ts | 1 + apps/api/src/vendor/dgit/UPSTREAM.md | 2 + apps/api/src/vendor/dgit/git/packstore.ts | 49 ++++++++------- .../hosted-git/hosted-git-conformance.test.ts | 44 ++++++++++++++ .../hosted-git/support/hosted-git-entry.ts | 13 ++++ .../unit/selfhost/hosted-git-deletion.test.ts | 13 ++++ .../selfhost/hosted-git-gc-admission.test.ts | 40 +++++++++++-- deploy/selfhost/README.md | 6 +- .../2026-11-19-selfhost-hosted-git-h2.md | 34 +++++++++-- 10 files changed, 216 insertions(+), 46 deletions(-) diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index 3ef09fda3c..a303d7ce4b 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -33,6 +33,7 @@ import type { HostedGitEnv } from './env'; import { type HostedGitGcResult, runHostedGitGc } from './hosted-git-gc'; import { filterLsRefsResponse, lsRefsPrefixes } from './hosted-git-ls-refs'; import { + type HostedGitLimits, hostedGitPushByteBudget, hostedGitPushRefusal, hostedGitPushTooLargeMessage, @@ -210,20 +211,18 @@ export class HostedGitRepo extends DurableObject { async alarm(): Promise { const limits = await resolveHostedGitLimits(this.settingsEnv); - return withGitWorkBudget(limits, () => this.runAlarm()); + return withGitWorkBudget(limits, () => this.runAlarm(limits)); } - private async runAlarm(): Promise { + private async runAlarm(limits: HostedGitLimits): Promise { if (this.deleting || this.store.getMeta('gc-pending') !== '1') return; // GC drops packs: never while a clone is streaming. Leave gc-pending set and retry. if (this.activeUploads > 0) { await this.ctx.storage.setAlarm(Date.now() + 30_000).catch(() => undefined); return; } - // Clear first (at most once), so a throwing sweep cannot cause a retry storm. - this.store.setMeta('gc-pending', '0'); try { - const result = await this.gc(); + const result = await this.gc(limits); log.info('hosted_git.gc', { ...result }); } catch (err) { log.error('hosted_git.gc_failed', { @@ -233,24 +232,48 @@ export class HostedGitRepo extends DurableObject { } /** GC serialized behind pushes and with no other request interleaving (it resets packs). */ - private gc(): Promise { + private gc(limits: HostedGitLimits): Promise { let result: HostedGitGcResult = { removed: 0, kept: 0 }; + let failure: unknown; + let failed = false; const run = this.receiveChain.then(() => this.ctx.blockConcurrencyWhile(async () => { - // Recheck after acquiring the push slot: a clone may have started while GC queued. - if (this.activeUploads > 0) { - this.store.setMeta('gc-pending', '1'); - await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS); - return; + try { + // Recheck after acquiring the push slot: a clone may have started while GC queued. + if (this.activeUploads > 0) { + this.store.setMeta('gc-pending', '1'); + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS); + return; + } + await this.store.packs.cleanupOrphans(); + result = await runHostedGitGc(this.store); + this.store.setMeta('gc-pending', '0'); + this.store.setMeta('gc-attempts', '0'); + } catch (err) { + // Rejecting blockConcurrencyWhile resets a DO before the outer alarm can retain retry + // intent. Carry the failure out after the input gate completes successfully instead. + const attempts = Number(this.store.getMeta('gc-attempts') ?? '0') + 1; + this.store.setMeta('gc-attempts', String(attempts)); + // Keep repairable work pending, but stop automatic retries at the configured budget. + this.store.setMeta('gc-pending', attempts < limits.maxGcAttempts ? '1' : 'failed'); + if (attempts < limits.maxGcAttempts) { + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS).catch(() => { + log.error('hosted_git.gc_retry_schedule_failed'); + }); + } + failure = err; + failed = true; } - result = await runHostedGitGc(this.store); }) ); this.receiveChain = run.then( () => undefined, () => undefined ); - return run.then(() => result); + return run.then(() => { + if (failed) throw failure; + return result; + }); } private async upload(req: Request): Promise { @@ -430,6 +453,16 @@ export class HostedGitRepo extends DurableObject { }); packId = ingested.packId; } catch (err) { + // Ingest writes chunks before checksum/index validation. Reclaim those rows now, + // before the next push's quota check; retain an alarm if storage cleanup itself fails. + this.store.setMeta('gc-pending', '1'); + this.store.setMeta('gc-attempts', '0'); + await this.store.packs.cleanupOrphans().catch((cleanupError: unknown) => { + log.error('hosted_git.ingest_cleanup_failed', { + error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), + }); + }); + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS); const msg = err instanceof Error ? err.message : String(err); unpackError = msg.includes('exceeds maximum push size') ? hostedGitPushTooLargeMessage(maxBytes) @@ -456,6 +489,7 @@ export class HostedGitRepo extends DurableObject { } if (needsGc || packId !== null) { this.store.setMeta('gc-pending', '1'); + this.store.setMeta('gc-attempts', '0'); await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS).catch(() => undefined); } if (caps.includes('report-status')) emit(renderStatus(results, unpackError, sideband)); diff --git a/apps/api/src/services/artifacts/settings.ts b/apps/api/src/services/artifacts/settings.ts index 2ef5f2126b..93b26a4534 100644 --- a/apps/api/src/services/artifacts/settings.ts +++ b/apps/api/src/services/artifacts/settings.ts @@ -11,6 +11,7 @@ export const REPOSITORY_POLICY_DEFAULTS = { maxInflatedBytes: 128 * 1024 * 1024, maxDeltaDepth: 100, workTimeoutMs: 120_000, + maxGcAttempts: 3, } as const; export type RepositoryPolicyKey = keyof typeof REPOSITORY_POLICY_DEFAULTS; diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 3249b052ba..aca00f8708 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -32,3 +32,5 @@ conformance suite (`pnpm --filter @simple-agent-manager/api test:hosted-git`). P SAM adds `git/budget.ts` around pack ingest, reads and delta application. Every request and GC invocation carries a separate cumulative decompression and deadline budget, including streamed responses. Object size is checked before allocation and while inflating, delta targets before allocation, and delta depth before traversal. Policy values come from the optional repository backend's typed admin settings. These are deliberate security changes to the vendored code; this directory is not byte-for-byte upstream. SQL identifiers use static allowlisted statements, and variable-sized bind lists are split below the runtime parameter ceiling. The additional GC admission and response accounting checks are covered by the hosted git suite. + +- PackStore exposes its existing incomplete-pack sweep as `cleanupOrphans`, so failed uploads can reclaim quota immediately and GC can retry storage cleanup independently of another admitted push. diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts index 1011c5f99d..6e27bd4380 100644 --- a/apps/api/src/vendor/dgit/git/packstore.ts +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -481,28 +481,8 @@ export class PackStore { * bases hot — so the straggler pass afterwards is nearly empty. Memory * stays bounded regardless of pack size. */ - async ingest( - firstBytes: Uint8Array, - reader: ReadableStreamDefaultReader | null, - opts: { - maxBytes: number; - /** push body size (content-length ~= pack size); packs this size are - * stored in R2 when a bucket is bound, else in SQLite. Absent means the - * client went chunked, which git only does above ~1MB (http.postBuffer) - * — so unknown size picks R2, the safe side for the 10GB SQLite cap. */ - sizeHint?: number; - cache: ObjCache; - onProgress?: (msg: string) => void; - /** called periodically so the runtime can flush its write buffer — - * workerd holds a request's dirty pages in the 128MB isolate heap */ - flush?: () => Promise; - /** screen every block with SHA-1DC (git-parity collision detection); - * default hashes with native crypto.subtle, which yields the identical - * oid without the collision check */ - collisionDetect?: boolean; - } - ): Promise<{ packId: number; count: number }> { - const cd = opts.collisionDetect ?? false; + /** Reclaim incomplete packs without requiring another admitted upload. Caller owns the write slot. */ + async cleanupOrphans(): Promise { // a failed or interrupted ingest leaves rows (or an R2 raw object) without a // pack_meta entry; reclaim that space before starting (pack_meta is only // written on success). Union across every per-pack table so an R2 ingest that @@ -532,6 +512,31 @@ export class PackStore { // the reclaimed pack id is about to be handed out again: drop anything the // chunk LRU still holds for it (and for anything else — it is only a cache) if (orphans.length) this.chunks.clear(); + } + + async ingest( + firstBytes: Uint8Array, + reader: ReadableStreamDefaultReader | null, + opts: { + maxBytes: number; + /** push body size (content-length ~= pack size); packs this size are + * stored in R2 when a bucket is bound, else in SQLite. Absent means the + * client went chunked, which git only does above ~1MB (http.postBuffer) + * — so unknown size picks R2, the safe side for the 10GB SQLite cap. */ + sizeHint?: number; + cache: ObjCache; + onProgress?: (msg: string) => void; + /** called periodically so the runtime can flush its write buffer — + * workerd holds a request's dirty pages in the 128MB isolate heap */ + flush?: () => Promise; + /** screen every block with SHA-1DC (git-parity collision detection); + * default hashes with native crypto.subtle, which yields the identical + * oid without the collision check */ + collisionDetect?: boolean; + } + ): Promise<{ packId: number; count: number }> { + const cd = opts.collisionDetect ?? false; + await this.cleanupOrphans(); const packId = (this.sql.exec<{ m: number | null }>("SELECT MAX(pack_id) AS m FROM pack_meta").one().m ?? 0) + 1; const started = Date.now(); diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 8644f1821e..97839d57e5 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -797,6 +797,50 @@ describe('repository cleanup through real SQLite', () => { await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); expect((await info()).objects).toBe(before.objects); }); + + it('reclaims failed-ingest pack rows before the next push quota check', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Failed ingest'); + const token = await mintToken(project, 'write'); + const work = await freshDir('failed-ingest'); + await gitOk(['clone', localRemote(project.repository, token), work]); + const before = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { bytes: number }; + // A full raw chunk is persisted before checksum validation; the remaining bytes cross quota. + const pack = randomBytes(2 * 1024 * 1024); + pack.write('PACK'); pack.writeUInt32BE(2, 4); pack.writeUInt32BE(1, 8); + const cap = before.bytes + pack.length; + await runtime.DATABASE.prepare("INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxRepoBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").bind(JSON.stringify(cap), Date.now()).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + const response = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, body: buildReceivePackRequest('a'.repeat(40), 'bad', pack) as BodyInit }); + expect(await response.text()).toContain('checksum mismatch'); + // No alarm or second ingest is allowed to repair the first request for this assertion. + const after = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { bytes: number }; + expect(after.bytes).toBeLessThan(cap); + await gitOk(['commit', '--allow-empty', '-m', 'safe after corrupt upload'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/recovered'], work); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).toContain('refs/heads/recovered'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxRepoBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + it('retains failed GC work and reclaims it on the next alarm after a transient read failure', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'GC retry'); + const token = await mintToken(project, 'write'); + const before = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { objects: number }; + const { pack, commitOid } = await buildSeedPack({ projectName: 'Unreachable retry pack' }); + await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, body: buildReceivePackRequest(commitOid, 'main', pack) as BodyInit }); + await runtime.fetch(`/__test/alarm/${project.artifactsRepoId}/fail`, { method: 'POST' }); + const failed = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json() as { pending: string; alarm: number | null }; + expect(failed.pending).toBe('1'); expect(failed.alarm).not.toBeNull(); + await runtime.fetch(`/__test/alarm/${project.artifactsRepoId}/run`, { method: 'POST' }); + const done = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json(); + expect(done).toMatchObject({ pending: '0', alarm: null }); + const after = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { objects: number }; + expect(after.objects).toBe(before.objects); + await runtime.fetch(`/__test/alarm/${project.artifactsRepoId}/run`, { method: 'POST' }); + expect(await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json()).toMatchObject({ pending: '0', alarm: null }); + }); it('transactionally deletes a populated repository and refuses later Git requests', async () => { const owner = await createEmailOnlyUser(); const project = await createHostedProject(owner, 'Delete me'); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index 17ab37b023..c9fc44fecf 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -34,6 +34,14 @@ export class HostedGitRepoTest extends HostedGitRepo { await this.ctx.storage.deleteAlarm(); return new Response('ok'); } + if (new URL(req.url).pathname === '/__test/alarm' || new URL(req.url).pathname === '/__test/alarm-fail') { + const store = (this as unknown as { store: { get: (...args: unknown[]) => Promise } }).store; + const get = store.get; + if (new URL(req.url).pathname.endsWith('-fail')) store.get = async () => { throw new Error('injected transient read failure'); }; + await this.ctx.storage.deleteAlarm(); + try { await this.alarm(); } finally { store.get = get; } + return new Response('ok'); + } if (new URL(req.url).pathname === '/__test/gc-state') { return Response.json({ pending: this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'").toArray()[0]?.value, alarm: await this.ctx.storage.getAlarm() }); } @@ -105,3 +113,8 @@ app.delete('/__test/repository/:repo', async (c) => { const ns = c.env.HOSTED_GIT!; return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/', { method: 'DELETE' }); }); + +app.post('/__test/alarm/:repo/:mode', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/alarm' + (c.req.param('mode') === 'fail' ? '-fail' : '')); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts index 3b62668caf..d2cde12f1e 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts @@ -150,3 +150,16 @@ it('retries failed cleanup while keeping all writes fenced', async () => { expect(state.deleteAlarm).toHaveBeenCalledTimes(2); expect(state.meta.get('deleted')).toBe('1'); }); + +it('reclaims failed-ingest rows even when scheduling the cleanup alarm fails', async () => { + const cell = repo(); + const events: string[] = []; + const packs = (cell as unknown as { store: { packs: { ingest: () => Promise; cleanupOrphans: () => Promise } } }).store.packs; + packs.ingest = async () => { events.push('ingest'); throw new Error('pack checksum mismatch'); }; + packs.cleanupOrphans = async () => { events.push('cleanup'); }; + state.setAlarm.mockImplementationOnce(async () => { events.push('alarm'); throw new Error('alarm storage unavailable'); }); + const response = await cell.fetch(new Request('https://git/git-receive-pack', { method: 'POST', body: new Uint8Array([48, 48, 48, 48, 80, 65, 67, 75, 0, 0, 0, 2, 0, 0, 0, 0]) })); + expect(response.status).toBe(500); + expect(events).toEqual(['ingest', 'cleanup', 'alarm']); + expect(state.meta.get('gc-pending')).toBe('1'); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts index 7b8f9450b0..9f7feaf7c5 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts @@ -4,6 +4,7 @@ import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo' import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; const mocks = vi.hoisted(() => ({ pending: '1', + attempts: '0', gc: vi.fn(async () => ({ removed: 1, kept: 2 })), setAlarm: vi.fn(async () => undefined), })); @@ -20,17 +21,21 @@ vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ })); vi.mock('../../../src/vendor/dgit/git/store', () => ({ GitStore: class { - getMeta() { - return mocks.pending; + packs = { cleanupOrphans: async () => undefined }; + getMeta(key: string) { + return key === 'gc-attempts' ? mocks.attempts : mocks.pending; } - setMeta(_key: string, value: string) { - mocks.pending = value; + setMeta(key: string, value: string) { + if (key === 'gc-attempts') mocks.attempts = value; + else mocks.pending = value; } }, })); vi.mock('../../../src/selfhost/hosted-git/hosted-git-gc', () => ({ runHostedGitGc: mocks.gc })); beforeEach(() => { mocks.pending = '1'; + mocks.attempts = '0'; + mocks.gc.mockReset().mockResolvedValue({ removed: 1, kept: 2 }); vi.clearAllMocks(); }); describe('hosted git GC admission', () => { @@ -47,7 +52,8 @@ describe('hosted git GC admission', () => { releasePush = resolve; }); const alarm = repo.alarm(); - await vi.waitFor(() => expect(mocks.pending).toBe('0')); + await Promise.resolve(); + await Promise.resolve(); state.activeUploads = 1; releasePush(); await alarm; @@ -61,4 +67,28 @@ describe('hosted git GC admission', () => { await repo.alarm(); expect(mocks.gc).toHaveBeenCalledOnce(); }); + it('retries a transient failed sweep and resets its attempt budget after success', async () => { + const ctx = { storage: { setAlarm: mocks.setAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() }; + const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); + for (let cycle = 0; cycle < 4; cycle++) { + mocks.pending = '1'; + mocks.gc.mockRejectedValueOnce(new Error('transient read failure')); + await repo.alarm(); + expect(mocks.pending).toBe('1'); expect(mocks.attempts).toBe('1'); + expect(mocks.setAlarm).toHaveBeenCalledTimes(cycle + 1); + await repo.alarm(); + expect(mocks.pending).toBe('0'); expect(mocks.attempts).toBe('0'); + } + const calls = mocks.gc.mock.calls.length; + await repo.alarm(); expect(mocks.gc).toHaveBeenCalledTimes(calls); + }); + it('stops automatic retries after the configured consecutive failure budget', async () => { + const repo = new HostedGitRepo({ storage: { setAlarm: mocks.setAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() } as unknown as DurableObjectState, {}); + mocks.gc.mockRejectedValue(new Error('permanent failure')); + for (let tick = 0; tick < 5; tick++) await repo.alarm(); + expect(mocks.gc).toHaveBeenCalledTimes(3); + expect(mocks.setAlarm).toHaveBeenCalledTimes(2); + expect(mocks.pending).toBe('failed'); + }); + }); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 0ec126b240..b946d4fcbc 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -209,7 +209,11 @@ Public repository import is unavailable in this slice; an import URL returns a c A bounded importer is tracked in `tasks/backlog/2026-11-19-bounded-selfhost-git-import.md`. GitHub and GitLab integrations remain available when configured. -Admin → Settings exposes `repositories.*` limits. Defaults are 64 MiB per push, 30,000 objects +Admin → Settings exposes `repositories.*` limits. Failed GC sweeps retry up to +`repositories.maxGcAttempts` (default 3), five minutes apart; success resets the budget. +Exhaustion preserves a failed marker and emits `hosted_git.gc_failed`; a later admitted push +starts a new cleanup episode. Failed pack ingestion reclaims incomplete rows before the next +push checks quota. Defaults are 64 MiB per push, 30,000 objects 10,000 refs and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation per request, delta depth 100 and 120 seconds per git operation. Operators can lower these limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index fab49122bd..fef8b1a8c0 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -17,12 +17,12 @@ Use existing L16 selection, extend its optional token context and fetch/import c - [x] Fresh branch from main; import selected integration paths and trim - [x] Move DO and hosted-git services under selfhost; dgit/pako excluded from Worker graph - [x] Extend generic fallback seam: workspace-bound token context, remoteFetch and optional import capability (unregistered per coordinator empty-repo decision); remove shared local-backend branches -- [x] Wire celld-only binding/export/tag via L22 single entry stacked on stable L22c539625202 per coordinator +- [x] Wire celld-only binding/export/tag via L22 single entry stacked on stable L22c08e2f605a per coordinator - [x] Add conformance/auth/lifecycle/token tests and import-graph violation proof - [x] Document self-host repository support and limits -- [ ] Local lint/typecheck/tests/build; security, Cloudflare, architecture and completion reviews -- [ ] Draft PR then ready/CI/CodeRabbit request and wait -- [ ] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off +- [x] Local lint/typecheck/tests/build; security, Cloudflare, architecture and completion reviews +- [x] Draft PR then ready; CodeRabbit requested and explicit skip recorded; CI tracked below +- [x] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off - [x] BOX existing bucket-mode deploy adds selfhost-hosted-git-v1; create project; OpenCode free reply; agent push verified; cleanup and BOX FREE - [ ] Merge main; all gates current head; announce merging/merged SHA; production success; idea SHIPPED @@ -32,7 +32,7 @@ No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; ## Implementation evidence -Stacked L22c539625202 per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite19/19 (real git18 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. +Stacked L22c08e2f605a per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite22/22 (real git21 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. BOX proof: existing795bf674f upgraded bucket-mode to a7cad then f6c65e71a healthy, celld tag confirmed. Hosted project01M7SX75X1YVADRG9Z4AB4AMV0; OpenCode big-pickle task01M7SXCMYYTAB9DNCFFAZMM0G1 replied pong; cookie-free clone verified agent commitad485ee136d4c8469b1e05e2983e086dd9e9393b and h2-proof.txt=pong. Stop/node/project delete200; nodes empty/project404/GCP no matching VM. Test credential/key/firewall/scratch removed. BOX FREE channel sequence403. @@ -40,3 +40,27 @@ BOX proof: existing795bf674f upgraded bucket-mode to a7cad then f6c65e71a health Review follow-up at 0f504c8dc: security PASS (independent 19 tests), Cloudflare PASS (54 tests), architecture PASS. Ref-only pushes now have an administrator-lowerable 10,000-ref cap and storage reservation; deletions do not earn admission capacity before old-OID validation (delete then add as separate pushes at the cap). Real HTTP mixed stale-delete/new-ref test fails when that protection is removed. DELETE queues behind accepted pushes, cancels clone streams, persists a tombstone and transactionally wipes/reinitializes; cleanup failures can retry while writes stay fenced. Mutex-negative probe fails the overlapping push/delete test. Ingested packs schedule GC even if every ref is rejected; oversized ls-refs returns a readable 413. Personal token endpoint is documented in API contract. Primary staging f6 deployment44527475370 passed deploy/smokes. Live Artifacts creation exposed a native RPC regression: optional extension property reads synthesize RPC methods. Fixed by selecting empty extensions when the native binding exists; only the registered fallback supplies import/fetch. Native browser transport similarly avoids extension probing. Proxy-shaped route and browser tests cover this; removing the guard makes the route test fail. Replacement deploy44532452799 at0f504c8dc pending. No staging project or VM persisted from failed seed (route cleans the orphan). CF settings independently confirm native ARTIFACTS present, hosted binding/DO absent. Browser project list loaded with zero page errors. Artifacts/GitHub creation gates remain pending the replacement deployment. + + +## Final candidate proof (2026-11-19) + +Candidate e7ac643b18f4ca864e403d33f7fbcf7a1a5e8fe8 has identical runtime to reviewed0f504c8dc; later changes document vendoring and add real-SQLite rejected-pack GC/tombstoned-deletion coverage. Hosted22/22, full API lint/typecheck passed. Security/Cloudflare/architecture PASS; completion validator independently A-F PASS, release completion pending CI/merge/production. Five Codex threads resolved. CodeRabbit requested at readiness12:33, trusted workflow44525031212; explicit skip12:34:24 (136files>100), ending wait per policy. + +Replacement staging44532452799 succeeded. Authenticated Playwright created Artifacts01M7T0EY1H2F03C1KK3W60DMQ9 and GitHub01M7T0F97C4V2BNV2M645TFF9M:201, branches200, selfhost token/git routes404. Both projects deleted200 and verified404. Dashboard/projects/settings and project overview navigation: zero page/console errors. No staging VM created. Runtime equivalence0f→e7 avoids another deploy for docs/tests only. + +Final BOX: existing f6→e7 ordinary bucket upgrade exit0/healthy; hosted project01M7T0482A939BRG0JFFK9VG62 created201, owner token200/unauth401. Normal fresh-node task01M7T0VJHK2381FBXA2VG6PM8Q / sessionbc1634b8-0065-43d9-835f-1d75197ec00b used OpenCode big-pickle free and replied pong. Independent cookie-free clone of sam/ping-run-one-shell-g6pm8q verified pushed commit164c22e3dc1c52de674718cc3996a31f75833c29 with h2-proof.txt=pong. Stop/node/project DELETE200, project404/nodesempty, GCP inventory no matching VM for either attempt. Test agent credential removed200, own SSHkeyabsent/firewall404, remote/local access/scratch removed; checkout clean at e7 and four original containers healthy. BOX FREE feature.selfhost-landing sequence405. + +First final BOX attempt01M7T05XSYH7ZPX5Y24DC4S4CH failed Ubuntu GCE mirror503 installing Docker before ready callback. Node01M7T062B9J4M1ZMBWT0Z2BXFP deleted through SAM; coordinator approved one normal fresh retry, which passed above. Sanitized evidence library01M7T0VM6MXVT21PMF5AJ4QMB7 and backlog01M7T0W1QW6WGMZGK1RYAXEEB1 track bounded retries/fallback mirror and failure callback. Raw debug copy deleted after analysis per policy. + +Current CI at e7:30success/8skip, only Playwright Visual Tests pending (44533748428/job135593986625). Final release checklist remains unchecked until prerequisite/main merge, current-head CI and production finish. + + +## Late review corrections (2026-11-19 18:21 UTC) + +PR Shepherd found two newer 13:32 Codex threads omitted from the earlier five-thread resolution report. Both applied: failed ingest persisted incomplete pack rows until another admitted ingest, which quota could block; failed GC cleared pending before sweeping and never retried. Runtime delta touches PackStore.cleanupOrphans/ingest (extract existing sweep), HostedGitRepo.processReceive error branch, alarm/runAlarm/gc retry bookkeeping, and repositories.maxGcAttempts metadata. Auth, deletion and happy-path git protocol are unchanged. + +Incomplete rows now clear immediately after failed ingest before alarm scheduling; GC also sweeps them independently. Successful GC clears pending/attempts under its writer slot. Failure persists retry intent and attempts under that same slot, re-arms five minutes later up to administrator-lowerable maxGcAttempts=3, then preserves a failed marker without automatic rearming. Success resets the consecutive-failure budget. Errors are carried out after blockConcurrencyWhile completes to avoid DO reset discarding retry handling. + +Full real-git/SQLite suite24/24 passed; GC/deletion units8/8 passed, including transient recovery, four success/failure cycles, attempt exhaustion, and alarm-scheduling failure ordering. Negative controls independently failed: disabling immediate cleanup left2199552bytes==cap; disabling retry handling leftpending0 instead of1. Restored tests pass. Security delta review PASS, including serialized failure metadata. No implementation omission remains; fresh CI and zero unresolved threads must still be confirmed. + +Coordinator decision720e4e43-2b39-4979-a6e1-3024553dd7c8 explicitly waives repeating BOX if delta stays confined to these failure paths, full real-git+new SQLite tests/negative controls pass, security delta passes, and fresh CI is green with zero open threads. Existing BOX proof/cleanup remains valid under those conditions. Staging native seam is unchanged. From 0eda6a2bdac6e21c0b7abf25c4a6a68aebaca262 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 18:30:44 +0000 Subject: [PATCH 48/65] fix(selfhost): enforce Git ref component and suffix rules --- apps/api/src/vendor/dgit/UPSTREAM.md | 2 + apps/api/src/vendor/dgit/git/protocol.ts | 4 +- .../hosted-git/hosted-git-conformance.test.ts | 21 +++++++++ .../unit/selfhost/hosted-git-refname.test.ts | 43 +++++++++++++++++++ .../2026-11-19-selfhost-hosted-git-h2.md | 9 ++++ 5 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 apps/api/tests/unit/selfhost/hosted-git-refname.test.ts diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index aca00f8708..bbd5e5bd4f 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -34,3 +34,5 @@ SAM adds `git/budget.ts` around pack ingest, reads and delta application. Every SQL identifiers use static allowlisted statements, and variable-sized bind lists are split below the runtime parameter ceiling. The additional GC admission and response accounting checks are covered by the hosted git suite. - PackStore exposes its existing incomplete-pack sweep as `cleanupOrphans`, so failed uploads can reclaim quota immediately and GC can retry storage cleanup independently of another admitted push. + +- Ref admission rejects `.lock` suffixes on every path component and a final dot, matching Git check-ref-format; the full rule matrix also retains SAM conservative character and length bounds. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index e806640a88..b6befafcd7 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1262,8 +1262,8 @@ export async function validatePush( } const bad = !cmd.ref.startsWith("refs/") || cmd.ref.includes("..") || BAD_REF.test(cmd.ref) || cmd.ref.endsWith(".lock") || cmd.ref.includes("@{") || cmd.ref.includes("//") - || cmd.ref.endsWith("/") || cmd.ref.length > 255 - || cmd.ref.split("/").some((c) => c.startsWith(".")); + || cmd.ref.endsWith("/") || cmd.ref.endsWith(".") || cmd.ref.length > 255 + || cmd.ref.split("/").some((c) => c.startsWith(".") || c.endsWith(".lock")); if (bad) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "funny refname" }); continue; diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 97839d57e5..716ff14150 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -775,6 +775,27 @@ describe('ref-only push admission', () => { }); +describe('Git ref-name admission through smart HTTP', () => { + it('rejects every .lock path component and accepts a similar valid ref', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Ref names'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const oid = (await gitOk(['ls-remote', remote, 'refs/heads/main'])).stdout.split(/\s+/)[0]!; + const send = async (branch: string) => (await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, body: buildReceivePackRequest(oid, branch, new Uint8Array()) as BodyInit })).text(); + for (const branch of ['foo.lock/bar', 'foo.lock', 'ends-dot.']) { + expect((await git(['check-ref-format', `refs/heads/${branch}`])).code).not.toBe(0); + expect(await send(branch)).toContain(`ng refs/heads/${branch} funny refname`); + } + for (const branch of ['normal', 'feature/x', 'foo.lockish/bar']) { + expect((await git(['check-ref-format', `refs/heads/${branch}`])).code).toBe(0); + expect(await send(branch)).toContain(`ok refs/heads/${branch}`); + } + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain('refs/heads/foo.lockish/bar'); + expect(refs).not.toContain('refs/heads/foo.lock/bar'); + }); +}); + describe('repository cleanup through real SQLite', () => { it('schedules and reclaims an ingested pack whose only ref update is rejected', async () => { const owner = await createEmailOnlyUser(); diff --git a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts new file mode 100644 index 0000000000..8e82c2a79a --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts @@ -0,0 +1,43 @@ +import { spawnSync } from 'node:child_process'; + +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +import { withGitWorkBudget } from '../../../src/vendor/dgit/git/budget'; +import { validatePush } from '../../../src/vendor/dgit/git/protocol'; +import type { GitStore } from '../../../src/vendor/dgit/git/store'; + +// Audit every rule in https://git-scm.com/docs/git-check-ref-format. The real smart-HTTP +// suite separately proves the parser/DO/write path with ordinary and nested branch controls. +const invalid = [ + 'refs/heads/.hidden/x', 'refs/heads/x/.hidden', 'refs/heads/x.lock/y', 'refs/heads/x.lock', + 'HEAD', '@', 'refs/heads/x y', 'refs/heads/x..y', 'refs/heads/x~y', 'refs/heads/x^y', 'refs/heads/x:y', + 'refs/heads/x?y', 'refs/heads/x*y', 'refs/heads/x[y', '/refs/heads/x', 'refs/heads/x/', + 'refs/heads/x//y', 'refs/heads/x.', 'refs/heads/x@{y', 'refs/heads/x\\y', + ...Array.from({ length: 33 }, (_, i) => `refs/heads/x${String.fromCharCode(i === 32 ? 127 : i)}y`), +]; +const valid = ['refs/heads/normal', 'refs/heads/feature/x', 'refs/tags/v1.0', 'refs/heads/x.lockish/y', 'refs/heads/a.b/c', 'refs/heads/café']; +const store = { + getMeta: () => null, reachableVersion: () => '0', refs: () => [], resolveHead: () => null, + getRef: () => null, has: () => true, +} as unknown as GitStore; +async function decision(ref: string) { + return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, async () => { + const plan = await validatePush(store, [{ old: '0'.repeat(40), next: 'a'.repeat(40), ref }], null, null); + return plan.decisions[0]; + }); +} +describe('validatePush Git ref-format rules', () => { + it.each(invalid)('rejects invalid ref %j', async (ref) => { + // NUL cannot cross an OS argv boundary; the protocol also uses it as the capabilities delimiter. + if (!ref.includes('\0')) expect(spawnSync('git', ['check-ref-format', ref]).status).not.toBe(0); + expect(await decision(ref)).toMatchObject({ ref, reject: 'funny refname' }); + }); + it.each(valid)('accepts valid ref %j', async (ref) => { + expect(spawnSync('git', ['check-ref-format', ref]).status).toBe(0); + expect(await decision(ref)).toMatchObject({ ref, set: 'a'.repeat(40) }); + }); + it.each(['refs/heads/xy', 'refs/heads/x&y', 'refs/heads/x`y', 'refs/heads/x"y', "refs/heads/x'y", `refs/heads/${'x'.repeat(256)}`])('keeps SAM conservative safety bound for %j', async (ref) => { + expect(await decision(ref)).toMatchObject({ reject: 'funny refname' }); + }); +}); diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index fef8b1a8c0..2803564112 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -64,3 +64,12 @@ Incomplete rows now clear immediately after failed ingest before alarm schedulin Full real-git/SQLite suite24/24 passed; GC/deletion units8/8 passed, including transient recovery, four success/failure cycles, attempt exhaustion, and alarm-scheduling failure ordering. Negative controls independently failed: disabling immediate cleanup left2199552bytes==cap; disabling retry handling leftpending0 instead of1. Restored tests pass. Security delta review PASS, including serialized failure metadata. No implementation omission remains; fresh CI and zero unresolved threads must still be confirmed. Coordinator decision720e4e43-2b39-4979-a6e1-3024553dd7c8 explicitly waives repeating BOX if delta stays confined to these failure paths, full real-git+new SQLite tests/negative controls pass, security delta passes, and fresh CI is green with zero open threads. Existing BOX proof/cleanup remains valid under those conditions. Staging native seam is unchanged. + + +## Ref-name review and complete rule audit (18:30 UTC) + +New current-head Codex r4633207972 found intermediate .lock components accepted by validatePush. Added the component suffix guard. Auditing every rule from https://git-scm.com/docs/git-check-ref-format also found missing whole-ref trailing-dot refusal; added that guard in the same fix. All other ten rules were already enforced in the refs/ namespace; conservative HTML/whitespace/255-character restrictions remain unchanged. + +Real raw smart-HTTP test refuses foo.lock/bar, foo.lock and ends-dot., and accepts normal, feature/x and foo.lockish/bar through the same validatePush/write path. Real validatePush rule matrix66/66 compares Git CLI outcomes (NUL checked directly since OS argv cannot carry it); full conformance25/25. Independent negative controls: remove component guard -> raw HTTP accepts the invalid ref; remove trailing-dot guard -> exactly1matrixfailure/65pass. Restored suite rerun. Security independently audited all ten rules and passed this delta. + +Coordinator decision5e57db22-5e40-46af-8aec-f1894395779f extends NOBOXREPEAT to this invalid-name admission tightening if ordinary+nested positive controls, negative control, full real-git, security delta, fresh CI and zero threads all pass. It rejects names the ordinary BOX branch never used; auth, happy-path valid names and deletion remain unchanged. Fresh CI remains required. From d16d1538e993ccef17391df025eef6f040e58e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 22:31:59 +0000 Subject: [PATCH 49/65] fix(selfhost): prove push closure per command before trusting it Codex r4633317762: reachableComplete walked straight into the shared trusted set, so a command whose closure walk failed left its unproven frontier there and a later command in the same push could point a ref at a nonexistent object. Each walk now collects into a scratch set and merges only when its closure is complete. The cache-less path had the same class of bug: packComplete trusted every object outside the new pack, but a rejected pack stays ingested until GC, so a later push could reference its broken commit. Every command now proves its closure by the same walk; packComplete and the push_edges helpers are removed. Real git/SQLite attack tests for both paths fail on the old code; positive multi-ref controls (cache extension and shallow push) pass. Co-Authored-By: Claude Opus 5.5 --- .../selfhost/hosted-git/hosted-git-repo.ts | 3 +- apps/api/src/vendor/dgit/UPSTREAM.md | 2 + apps/api/src/vendor/dgit/git/protocol.ts | 92 +++------ apps/api/src/vendor/dgit/git/store.ts | 54 ----- .../hosted-git/hosted-git-conformance.test.ts | 192 +++++++++++++++++- .../unit/selfhost/hosted-git-refname.test.ts | 4 +- 6 files changed, 223 insertions(+), 124 deletions(-) diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index a303d7ce4b..c78bb08b61 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -197,6 +197,7 @@ export class HostedGitRepo extends DurableObject { head: this.store.head(), objects: this.store.objectCount(), bytes: this.store.dbSize(), + reachableCache: this.store.reachableCacheValid(), }); } return new Response('not found\n', { status: 404 }); @@ -479,7 +480,7 @@ export class HostedGitRepo extends DurableObject { } } - const plan = await validatePush(this.store, commands, unpackError, packId); + const plan = await validatePush(this.store, commands, unpackError); const { results, changed, needsGc } = this.ctx.storage.transactionSync(() => commitPush(this.store, plan) ); diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index bbd5e5bd4f..3e0f40f704 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -36,3 +36,5 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - PackStore exposes its existing incomplete-pack sweep as `cleanupOrphans`, so failed uploads can reclaim quota immediately and GC can retry storage cleanup independently of another admitted push. - Ref admission rejects `.lock` suffixes on every path component and a final dot, matching Git check-ref-format; the full rule matrix also retains SAM conservative character and length bounds. + +- Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index b6befafcd7..c2e280f728 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1116,24 +1116,32 @@ const BAD_REF = /[\s~^:?*\[\\'"<>&`\x00-\x1f\x7f]/; * (and tag->target) with a presence probe at each node catches it before the * ref moves. `known` is pre-seeded with the pre-existing ref tips, whose * closure was validated at their own push, so descent stops there — the walk - * touches only objects this push introduced. + * touches only objects this push introduced (or older objects no ref holds). + * + * SAM: the walk is transactional per command. Newly reached oids go into a + * scratch set and are merged into `known` only once the whole closure is + * proven present. Upstream walked straight into `known`, so a command whose + * walk failed left its unproven frontier there and a later command in the + * same push stopped at it: a ref could then name an object that does not + * exist (Codex r4633317762). `known` therefore only ever holds validated + * closures, which is also what commitPush folds into the reachable cache. */ async function reachableComplete(store: GitStore, tip: string, known: OidSet): Promise { - // Cursor BFS over `known` itself: newly reached oids append past `start`, - // and pre-existing entries (a fast-forward's already-validated closure) sit - // before it and are never re-walked. Reusing the set as its own frontier - // needs no separate hex-oid stack to walk it. - const start = known.size; - if (!known.addHex(tip)) return true; // tip already in a validated closure - for (let i = start; i < known.size; i++) { - const oid = known.atHex(i); + if (known.hasHex(tip)) return true; // tip already in a validated closure + // Cursor BFS over the scratch set itself: newly reached oids append past + // the cursor, so no separate hex-oid stack is needed to walk it. + const fresh = new OidSet(1024); + fresh.addHex(tip); + for (let i = 0; i < fresh.size; i++) { + const oid = fresh.atHex(i); const meta = store.typeAndSize(oid); if (!meta) return false; if (meta.type === "blob") continue; const obj = await store.get(oid); if (!obj) return false; - for (const child of childOids(obj)) known.addHex(child); + for (const child of childOids(obj)) if (!known.hasHex(child)) fresh.addHex(child); } + for (let i = 0; i < fresh.size; i++) known.addHex(fresh.atHex(i)); return true; } @@ -1182,67 +1190,21 @@ function childOids(obj: { type: ObjType; data: Uint8Array }): string[] { return []; } -/** - * Verify a freshly ingested pack is connectivity-complete — every child oid its - * objects reference is present in `pack_objects` ∪ `objects` — and return the - * first missing child, or null when complete. This is the storage-backed - * counterpart to walking the graph: it scans the pack's non-blob objects one - * keyset page at a time, stages their referenced children into `push_edges` in - * bounded batches, and lets SQLite anti-join each batch against the stores. A - * complete pack means every tip in it has a complete closure (by induction over - * the edges), so the whole push is connected — checked in flat memory, with no - * OidSet that scales with the object count. Used for a fresh push, where the - * old walk built a reachable set the commit step then discarded anyway. - */ -async function packComplete(store: GitStore, packId: number): Promise { - const PAGE = 1000; - const EDGE_BATCH = 8192; - store.resetPushEdges(); - let after = ""; - let pending: string[] = []; - const flush = (): string | null => { - if (!pending.length) return null; - store.addPushEdges(pending); - pending = []; - const miss = store.firstMissingPushEdge(); - store.resetPushEdges(); - return miss; - }; - for (;;) { - const page = store.packNonBlobOidsAfter(packId, after, PAGE); - if (!page.length) break; - for (const oid of page) { - const obj = await store.get(oid); - if (!obj) return oid; // indexed but unreadable — the pack is not complete - for (const child of childOids(obj)) pending.push(child); - if (pending.length >= EDGE_BATCH) { - const miss = flush(); - if (miss) return miss; - } - } - after = page[page.length - 1]; - } - return flush(); -} - export async function validatePush( store: GitStore, commands: PushCommand[], - unpackError: string | null, - packId: number | null + unpackError: string | null ): Promise { // whether the reachable cache is valid for the pre-push refs: only then can // it be extended in place (union with the connectivity walk) instead of // rebuilt from scratch on the next full clone const hadCache = store.getMeta("reachable-version") === store.reachableVersion(); - // A fresh push (no cache to extend) verifies connectivity in SQL rather than - // by walking into an OidSet — the walk's result would be discarded by the - // commit step's invalidate below, so it was pure memory spent to reject a - // broken pack. `packMissing` names the first unresolved child, or stays null. - // A fast-forward keeps the cheap new-object walk, which both verifies and - // extends the cache in one pass. - const packMissing = - !hadCache && !unpackError && packId !== null ? await packComplete(store, packId) : null; + // SAM: every command proves its closure by walking, with or without a cache. + // Upstream checked a cache-less push in SQL ("every child of the new pack is + // in pack_objects ∪ objects"), which is sound only if every object outside + // the new pack is itself closure-complete. Here a pack whose refs were all + // rejected stays ingested until GC reclaims it, so an earlier broken pack + // could vouch for a later command. Repository caps bound the walk. // pre-existing ref tips bound the connectivity walk: their closure is // already validated, so a normal fast-forward only re-checks new objects const known = new OidSet(4096); @@ -1277,9 +1239,7 @@ export async function validatePush( decisions.push({ ref: cmd.ref, expectedOld: cmd.old, del: true }); continue; } - const connected = hadCache - ? await reachableComplete(store, cmd.next, known) - : packMissing === null && store.has(cmd.next); + const connected = await reachableComplete(store, cmd.next, known); if (!connected) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "missing necessary objects" }); continue; diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index 4eae2d27b4..5302b7780f 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -79,9 +79,6 @@ export class GitStore { data TEXT NOT NULL, PRIMARY KEY (tip_oid, period) ); - CREATE TABLE IF NOT EXISTS push_edges ( - child TEXT NOT NULL - ); `); const flag = this.getMeta("has-loose"); if (flag === null) { @@ -160,57 +157,6 @@ export class GitStore { return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM objects").one().n + this.packs.countObjects(); } - // --- push connectivity --------------------------------------------------- - // Connectivity of a fresh push is checked in SQL, not by an in-memory graph - // walk: the pushed pack must be complete, i.e. every object it introduces - // must have its referenced children in `pack_objects` ∪ `objects`. Children - // are staged into `push_edges` in bounded batches and each batch is - // anti-joined against the stores, so the check costs O(batch) rows of scratch - // rather than an OidSet that scales with the object count. - - /** A page of a pack's non-blob oids after `after` (keyset, so the scan holds - * one page, never the whole pack). Empty array ends the walk. */ - packNonBlobOidsAfter(packId: number, after: string, limit: number): string[] { - return this.sql - .exec<{ oid: string }>( - "SELECT oid FROM pack_objects WHERE pack_id = ? AND type != 'blob' AND oid > ? ORDER BY oid LIMIT ?", - packId, - after, - limit, - ) - .toArray() - .map((r) => r.oid); - } - - resetPushEdges(): void { - this.sql.exec("DELETE FROM push_edges"); - } - - /** Stage referenced child oids, chunked under the DO's ~100 bound-variable - * statement cap. */ - addPushEdges(children: string[]): void { - for (let i = 0; i < children.length; i += 64) { - const batch = children.slice(i, i + 64); - const placeholders = batch.map(() => "(?)").join(","); - this.sql.exec(`INSERT INTO push_edges (child) VALUES ${placeholders}`, ...batch); - } - } - - /** The first staged child absent from both stores, or null when every staged - * child is present. SQLite runs the membership test over its own indexes, so - * no oid set is built in the isolate. */ - firstMissingPushEdge(): string | null { - const rows = this.sql - .exec<{ child: string }>( - `SELECT e.child FROM push_edges e - WHERE NOT EXISTS (SELECT 1 FROM pack_objects p WHERE p.oid = e.child) - AND NOT EXISTS (SELECT 1 FROM objects o WHERE o.oid = e.child) - LIMIT 1`, - ) - .toArray(); - return rows.length ? rows[0].child : null; - } - /** Resolve an abbreviated oid; null if unknown or ambiguous. */ findOid(prefix: string): string | null { if (!/^[0-9a-f]{4,40}$/.test(prefix)) return null; diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 716ff14150..83ee0416df 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -7,7 +7,7 @@ * project-create route (artifacts provider, an email-only user with no GitHub link), which seeds * the README in-process; workspace credentials come from the real POST /workspaces/:id/git-token. */ -import { execFile } from 'node:child_process'; +import { execFile, spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { mkdirSync } from 'node:fs'; import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; @@ -874,3 +874,193 @@ describe('repository cleanup through real SQLite', () => { expect((await runtime.fetch(`/__test/repository/${project.artifactsRepoId}`, { method: 'DELETE' })).status).toBe(200); }); }); + +/** + * Push connectivity admission: a ref may only move to an object whose whole closure is + * present. Each scenario builds raw packs with the git CLI, sends them through the real + * receive-pack route into the real SQLite store, and asserts on refs read back plus an + * fsck of a fresh clone. + */ +describe('push connectivity admission (closure must be complete per command)', () => { + const ZERO = '0'.repeat(40); + + function gitEnv(): NodeJS.ProcessEnv { + return { + PATH: process.env.PATH ?? '', + HOME: scratch, + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }; + } + + /** A pack holding exactly `oids`, deliberately omitting anything they reference. */ + function packOf(cwd: string, oids: string[]): Buffer { + const out = spawnSync('git', ['pack-objects', '--stdout'], { + cwd, + env: gitEnv(), + input: `${oids.join('\n')}\n`, + maxBuffer: 16 * 1024 * 1024, + }); + if (out.status !== 0) throw new Error(`pack-objects failed: ${out.stderr.toString()}`); + return out.stdout; + } + + async function rev(cwd: string, spec: string): Promise { + return (await gitOk(['rev-parse', spec], cwd)).stdout.trim(); + } + + /** Commit one new uniquely named file and return the commit and its root tree. */ + async function commitFile(cwd: string, name: string): Promise<{ commit: string; tree: string }> { + await writeFile(join(cwd, name), `${name} ${randomBytes(8).toString('hex')}\n`); + await gitOk(['add', name], cwd); + await gitOk(['commit', '-m', name], cwd); + return { commit: await rev(cwd, 'HEAD'), tree: await rev(cwd, 'HEAD^{tree}') }; + } + + async function receive( + project: CreatedProject, + token: string, + commands: Array<[old: string, next: string, ref: string]>, + pack?: Uint8Array + ): Promise { + const packet = (line: string) => (Buffer.byteLength(line) + 4).toString(16).padStart(4, '0') + line; + const lines = commands.map(([old, next, ref], i) => + packet(`${old} ${next} ${ref}${i === 0 ? '\0report-status' : ''}\n`) + ); + const head = Buffer.from(lines.join('') + '0000'); + const body = pack ? Buffer.concat([head, Buffer.from(pack)]) : head; + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body: body as unknown as BodyInit, + }); + return res.text(); + } + + async function reachableCache(project: CreatedProject): Promise { + const info = (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { + reachableCache: boolean; + }; + return info.reachableCache; + } + + async function assertCleanClone(remote: string): Promise { + const check = await freshDir('closure-check'); + await gitOk(['clone', remote, check]); + expect((await git(['fsck', '--strict', '--connectivity-only'], check)).code).toBe(0); + expect((await git(['fsck', '--strict'], check)).code).toBe(0); + return check; + } + + it('with a reachable cache, a failed first command does not vouch for a later command (Codex r4633317762)', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure cache attack'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-cache'); + await gitOk(['clone', remote, work]); // a full clone persists the reachable cache + expect(await reachableCache(project)).toBe(true); + + const { commit, tree } = await commitFile(work, 'attack.txt'); + // The pack carries the commit but not its tree. The first command's walk reaches the + // missing tree and fails; the second command names that same tree directly. + const out = await receive( + project, + token, + [ + [ZERO, commit, 'refs/heads/attack-commit'], + [ZERO, tree, 'refs/heads/attack-tree'], + ], + packOf(work, [commit]) + ); + expect(out).toContain('ng refs/heads/attack-commit missing necessary objects'); + expect(out).toContain('ng refs/heads/attack-tree missing necessary objects'); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain('refs/heads/main'); + expect(refs).not.toContain('attack-commit'); + expect(refs).not.toContain('attack-tree'); + expect(await reachableCache(project)).toBe(true); + await assertCleanClone(remote); + }); + + it('with a reachable cache, a valid multi-ref push whose closures overlap is accepted and extends the cache', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure cache control'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-cache-ok'); + await gitOk(['clone', remote, work]); + expect(await reachableCache(project)).toBe(true); + + const first = await commitFile(work, 'one.txt'); + const second = await commitFile(work, 'two.txt'); // child of `first` + await gitOk(['branch', 'b-one', first.commit], work); + await gitOk(['branch', 'b-two', second.commit], work); + await gitOk(['push', 'origin', 'b-one', 'b-two', 'HEAD:refs/heads/main'], work); + // A fast-forward with a valid prior cache extends it in place rather than invalidating. + expect(await reachableCache(project)).toBe(true); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${first.commit}\trefs/heads/b-one`); + expect(refs).toContain(`${second.commit}\trefs/heads/b-two`); + // The next full clone is served from the extended cache, so a missing object fails fsck. + const check = await assertCleanClone(remote); + expect(await rev(check, 'origin/b-two')).toBe(second.commit); + }); + + it('without a reachable cache, a commit left by a rejected pack cannot be referenced later', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure stale pack'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-stale'); + await gitOk(['init', '-q', '-b', 'main', work]); + const orphan = await commitFile(work, 'orphan.txt'); // root commit, tree not sent + expect(await reachableCache(project)).toBe(false); + + const first = await receive(project, token, [[ZERO, orphan.commit, 'refs/heads/stale']], packOf(work, [orphan.commit])); + expect(first).toContain('ng refs/heads/stale missing necessary objects'); + // The rejected pack stays ingested until GC runs; it must not count as validated history. + const child = await commitFile(work, 'child.txt'); + const childTreeObjects = (await gitOk(['ls-tree', '-r', '-t', child.commit], work)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(/\s+/)[2]!) + .filter((oid) => oid !== orphan.tree); + const second = await receive( + project, + token, + [ + [ZERO, orphan.commit, 'refs/heads/reuse-orphan'], + [ZERO, child.commit, 'refs/heads/child-of-orphan'], + ], + packOf(work, [child.commit, child.tree, ...childTreeObjects]) + ); + expect(second).toContain('ng refs/heads/reuse-orphan missing necessary objects'); + expect(second).toContain('ng refs/heads/child-of-orphan missing necessary objects'); + const ref = await receive(project, token, [[ZERO, orphan.commit, 'refs/heads/ref-only']]); + expect(ref).toContain('ng refs/heads/ref-only missing necessary objects'); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain('refs/heads/main'); + expect(refs).not.toMatch(/stale|reuse-orphan|child-of-orphan|ref-only/); + expect(await reachableCache(project)).toBe(false); + await assertCleanClone(remote); + }); + + it('without a reachable cache, a valid push from a shallow clone is accepted', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure shallow control'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-shallow'); + await gitOk(['clone', '--depth', '1', remote, work]); // not a full clone: no cache + expect(await reachableCache(project)).toBe(false); + const next = await commitFile(work, 'shallow.txt'); + await gitOk(['push', 'origin', 'HEAD:refs/heads/main', 'HEAD:refs/heads/shallow-copy'], work); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${next.commit}\trefs/heads/main`); + expect(refs).toContain(`${next.commit}\trefs/heads/shallow-copy`); + await assertCleanClone(remote); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts index 8e82c2a79a..326dacbf30 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts @@ -19,11 +19,11 @@ const invalid = [ const valid = ['refs/heads/normal', 'refs/heads/feature/x', 'refs/tags/v1.0', 'refs/heads/x.lockish/y', 'refs/heads/a.b/c', 'refs/heads/café']; const store = { getMeta: () => null, reachableVersion: () => '0', refs: () => [], resolveHead: () => null, - getRef: () => null, has: () => true, + getRef: () => null, typeAndSize: () => ({ type: 'blob', size: 1 }), } as unknown as GitStore; async function decision(ref: string) { return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, async () => { - const plan = await validatePush(store, [{ old: '0'.repeat(40), next: 'a'.repeat(40), ref }], null, null); + const plan = await validatePush(store, [{ old: '0'.repeat(40), next: 'a'.repeat(40), ref }], null); return plan.decisions[0]; }); } From c1f7bc51a277854ed31079a66212cc49a93e1378 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 22:34:42 +0000 Subject: [PATCH 50/65] task: record H2 takeover, closure fix and evidence Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-19-selfhost-hosted-git-h2.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 2803564112..baf2bd60d6 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -73,3 +73,17 @@ New current-head Codex r4633207972 found intermediate .lock components accepted Real raw smart-HTTP test refuses foo.lock/bar, foo.lock and ends-dot., and accepts normal, feature/x and foo.lockish/bar through the same validatePush/write path. Real validatePush rule matrix66/66 compares Git CLI outcomes (NUL checked directly since OS argv cannot carry it); full conformance25/25. Independent negative controls: remove component guard -> raw HTTP accepts the invalid ref; remove trailing-dot guard -> exactly1matrixfailure/65pass. Restored suite rerun. Security independently audited all ten rules and passed this delta. Coordinator decision5e57db22-5e40-46af-8aec-f1894395779f extends NOBOXREPEAT to this invalid-name admission tightening if ordinary+nested positive controls, negative control, full real-git, security delta, fresh CI and zero threads all pass. It rejects names the ordinary BOX branch never used; auth, happy-path valid names and deletion remain unchanged. Fresh CI remains required. + + +## Takeover by task 01M7TY7Z3HBTSDSSV85FPRHE1B (2026-11-19 ~21:00 UTC) + +Previous owner 01M7SR1B79 stopped after repeated provider content-filter refusals; its pushed head 0eda6a2bd was intact. + +- [x] Merge main 917077fef (L22c merged): conflicts only in L22c files (took main's final versions) and deploy/selfhost/README.md (kept the hosted-git section, dropped main's now-false "Hosted git: not included" bullet). Merge 553a9060f. +- [x] Codex P2 r4633317762: `reachableComplete` now walks each command into a scratch OidSet and merges into `known` only once the closure is complete. +- [x] Same class, found while fixing it: the cache-less path trusted `packComplete` + `store.has(tip)`. That is sound only if every object outside the new pack is closure-complete, but a pack whose refs were all rejected stays ingested until GC. A later push (ref-only, or a pack whose commit's parent is the stale commit) could point a ref at an incomplete closure. Every command now proves its closure with the same walk; `packComplete` and the `push_edges` helpers/table creation are removed (existing repos keep an empty, unused `push_edges` table; no DO DROP). +- [x] Real git/SQLite tests (describe "push connectivity admission"): cache-path multi-ref attack, cache-less stale-rejected-pack attack (ref-only and child-pack variants), and positive controls (overlapping multi-ref push extends the cache and a full clone fscks; shallow-clone push on the cache-less path). Both attack tests fail on 0eda6a2bd. Discrimination: A non-transactional walk -> both attack tests red; B cache-less presence-only -> stale-pack test red; C never merging into `known` -> cache control red (clone from extended cache fails fsck). Hosted suite 29/29, self-host unit 186/186, API typecheck and focused lint pass. +- Bound (rule 81): one walk is bounded by the repository caps (30,000 objects, 256 MiB stored), the 128 MiB per-request inflation budget and the 120 s git-operation deadline. Worst case is one walk over every object in the repository: at most 30,000 SQLite presence probes plus inflating the non-blob objects, completing in one attempt or failing closed with the budget error. A fresh push's walk reads the same non-blob objects `packComplete` read before. +- [ ] Security delta review + one adversarial pass over the whole push admission path +- [ ] Fresh CI green, 0 open threads, Codex re-requested on final head +- [ ] Final BOX smoke on the exact final head over main (closes the L22c "box from main runs an agent session" criterion deferred to H2 by Raphaël) From f9eb945efd0c8e6cca2a84bea91a1344753259f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:02:53 +0000 Subject: [PATCH 51/65] fix(selfhost): harden hosted git push admission after adversarial review Security delta review of d16d1538e and one adversarial pass over the whole push admission path: - HIGH: validatePush peeled every ref tip to seed the validated set, inflating each under the push's decompression budget, so a few large tips made every later push fail, deletions included. Seeding now reads no objects (cached peel targets only). - The closure walk checks the type git requires at every edge, including edges into already-validated objects, and blames the referencing object so a valid shared object is never poisoned. Branches refuse non-commits. - Failed walks are memoized per push along the BFS path, so repeated or overlapping failing commands cannot multiply the walk. - An object that does not parse rejects its own command instead of failing the push; GC is queued when validation or commit throws after a pack was ingested. - Deleting a missing ref succeeds without queueing GC; arming the GC alarm keeps an earlier armed alarm; directory/file ref conflicts are refused. GC inflation, delta depth at ingest and GC's input-gate hold are deferred to tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md and documented as a known limit. Request-body helpers move to hosted-git-body.ts to keep the Durable Object under 500 lines. Co-Authored-By: Claude Opus 5.5 --- .../selfhost/hosted-git/hosted-git-body.ts | 64 +++++ .../src/selfhost/hosted-git/hosted-git-gc.ts | 29 ++ .../selfhost/hosted-git/hosted-git-repo.ts | 92 ++---- apps/api/src/vendor/dgit/UPSTREAM.md | 2 + apps/api/src/vendor/dgit/git/protocol.ts | 156 ++++++++++- .../hosted-git/hosted-git-conformance.test.ts | 216 +++++++++++++- .../hosted-git/support/hosted-git-entry.ts | 18 ++ .../selfhost/hosted-git-closure-walk.test.ts | 137 +++++++++ .../unit/selfhost/hosted-git-deletion.test.ts | 2 + .../selfhost/hosted-git-gc-admission.test.ts | 12 +- .../hosted-git-push-admission.test.ts | 265 ++++++++++++++++++ .../unit/selfhost/hosted-git-refname.test.ts | 11 +- deploy/selfhost/README.md | 4 + .../2026-11-19-selfhost-hosted-git-h2.md | 11 +- ...1-19-hosted-git-gc-and-ingest-hardening.md | 38 +++ 15 files changed, 966 insertions(+), 91 deletions(-) create mode 100644 apps/api/src/selfhost/hosted-git/hosted-git-body.ts create mode 100644 apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts create mode 100644 apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts create mode 100644 tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-body.ts b/apps/api/src/selfhost/hosted-git/hosted-git-body.ts new file mode 100644 index 0000000000..3c6f2fd935 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-body.ts @@ -0,0 +1,64 @@ +/** + * Bounded request-body reading for the hosted git Durable Object: pkt-line lengths, whole-body + * reads with a byte cap, and draining a refused upload so the client sees the refusal reason. + */ +import { readGitChunk } from '../../vendor/dgit/git/budget'; +import { concat, td } from '../../vendor/dgit/git/util'; + +const PKT_LENGTH = /^[0-9a-f]{4}$/i; + +export class RequestTooLargeError extends Error { + constructor() { + super('request body exceeds maximum size'); + } +} + +/** + * A pkt-line length: exactly four hex digits. 0 is a flush packet; 1-3 are invalid. `parseInt` + * alone would accept "-004" and walk the parser backwards forever (security review, HIGH). + */ +export function pktLength(bytes: Uint8Array): number { + const text = td.decode(bytes); + if (!PKT_LENGTH.test(text)) throw new Error('bad pkt-line in push request'); + const len = parseInt(text, 16); + if (len !== 0 && len < 4) throw new Error('bad pkt-line in push request'); + return len; +} + +/** Read a whole request body, refusing (without buffering further) past `maxBytes`. */ +export async function readBodyBounded(req: Request, maxBytes: number): Promise { + if (!req.body) return new Uint8Array(0); + const reader = req.body.getReader(); + const parts: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await readGitChunk(reader); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => undefined); + throw new RequestTooLargeError(); + } + parts.push(value); + } + return concat(parts); +} + +/** Discard up to `maxBytes` of a request body, then cancel whatever is left. */ +export async function drainBounded( + reader: ReadableStreamDefaultReader | null, + maxBytes: number +): Promise { + if (!reader) return; + let drained = 0; + try { + while (drained <= maxBytes) { + const { done, value } = await readGitChunk(reader); + if (done) return; + drained += value?.byteLength ?? 0; + } + await reader.cancel(); + } catch { + // The client may already be gone. + } +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts index 47f140285f..aca46902f5 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts @@ -15,6 +15,35 @@ const GC_MAX_OBJECTS = 300_000; /** The Durable Object SQLite ceiling a migration must not cross while duplicating objects. */ const DO_STORAGE_CAP = 10 * 1024 * 1024 * 1024; +/** Delay before the GC alarm runs after a push queues work, coalescing bursts of pushes. */ +export const GC_DELAY_MS = 5 * 60 * 1000; + +type AlarmStorage = { + getAlarm(): Promise; + setAlarm(scheduledTime: number): Promise; +}; + +/** + * Arm the GC alarm GC_DELAY_MS from now unless one is already due sooner. Keeping an earlier + * alarm means a steady trickle of pushes cannot postpone cleanup indefinitely. + */ +export async function armHostedGitGcAlarm(storage: AlarmStorage): Promise { + const due = Date.now() + GC_DELAY_MS; + const armed = await storage.getAlarm(); + if (armed !== null && armed <= due) return; + await storage.setAlarm(due); +} + +/** + * Queue a GC episode for what a push left behind: history stranded by a force push or delete, + * or an ingested pack whose refs were rejected or never decided. Resets the retry budget. + */ +export async function queueHostedGitGc(store: GitStore, storage: AlarmStorage): Promise { + store.setMeta('gc-pending', '1'); + store.setMeta('gc-attempts', '0'); + await armHostedGitGcAlarm(storage).catch(() => undefined); +} + export interface HostedGitGcResult { removed: number; kept: number; diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index c78bb08b61..30449e7c24 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -27,10 +27,17 @@ import { validatePush, } from '../../vendor/dgit/git/protocol'; import { GitStore } from '../../vendor/dgit/git/store'; -import { concat, td, te } from '../../vendor/dgit/git/util'; +import { concat, te } from '../../vendor/dgit/git/util'; import { gunzipLimited } from '../../vendor/dgit/git/zlib'; import type { HostedGitEnv } from './env'; -import { type HostedGitGcResult, runHostedGitGc } from './hosted-git-gc'; +import { drainBounded, pktLength, readBodyBounded, RequestTooLargeError } from './hosted-git-body'; +import { + armHostedGitGcAlarm, + GC_DELAY_MS, + type HostedGitGcResult, + queueHostedGitGc, + runHostedGitGc, +} from './hosted-git-gc'; import { filterLsRefsResponse, lsRefsPrefixes } from './hosted-git-ls-refs'; import { type HostedGitLimits, @@ -48,68 +55,9 @@ const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; const MAX_ACTIVE_UPLOADS = 4; /** Decompressed objects held for delta-base resolution during one push. */ const INGEST_CACHE_BYTES = 32 * 1024 * 1024; -const GC_DELAY_MS = 5 * 60 * 1000; const PACK_HEADER_BYTES = 12; /** The pkt-line command section of a push (ref updates + capabilities) before the pack. */ const MAX_COMMAND_SECTION_BYTES = 1024 * 1024; -const PKT_LENGTH = /^[0-9a-f]{4}$/i; - -class RequestTooLargeError extends Error { - constructor() { - super('request body exceeds maximum size'); - } -} - -/** - * A pkt-line length: exactly four hex digits. 0 is a flush packet; 1-3 are invalid. `parseInt` - * alone would accept "-004" and walk the parser backwards forever (security review, HIGH). - */ -function pktLength(bytes: Uint8Array): number { - const text = td.decode(bytes); - if (!PKT_LENGTH.test(text)) throw new Error('bad pkt-line in push request'); - const len = parseInt(text, 16); - if (len !== 0 && len < 4) throw new Error('bad pkt-line in push request'); - return len; -} - -/** Read a whole request body, refusing (without buffering further) past `maxBytes`. */ -async function readBodyBounded(req: Request, maxBytes: number): Promise { - if (!req.body) return new Uint8Array(0); - const reader = req.body.getReader(); - const parts: Uint8Array[] = []; - let total = 0; - for (;;) { - const { done, value } = await readGitChunk(reader); - if (done) break; - total += value.byteLength; - if (total > maxBytes) { - await reader.cancel().catch(() => undefined); - throw new RequestTooLargeError(); - } - parts.push(value); - } - return concat(parts); -} - -/** Discard up to `maxBytes` of a request body, then cancel whatever is left. */ -async function drainBounded( - reader: ReadableStreamDefaultReader | null, - maxBytes: number -): Promise { - if (!reader) return; - let drained = 0; - try { - while (drained <= maxBytes) { - const { done, value } = await readGitChunk(reader); - if (done) return; - drained += value?.byteLength ?? 0; - } - await reader.cancel(); - } catch { - // The client may already be gone. - } -} - export class HostedGitRepo extends DurableObject { private store: GitStore; private readonly settingsEnv: HostedGitEnv; @@ -463,7 +411,7 @@ export class HostedGitRepo extends DurableObject { error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), }); }); - await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS); + await armHostedGitGcAlarm(this.ctx.storage); const msg = err instanceof Error ? err.message : String(err); unpackError = msg.includes('exceeds maximum push size') ? hostedGitPushTooLargeMessage(maxBytes) @@ -480,19 +428,21 @@ export class HostedGitRepo extends DurableObject { } } - const plan = await validatePush(this.store, commands, unpackError); - const { results, changed, needsGc } = this.ctx.storage.transactionSync(() => - commitPush(this.store, plan) - ); + let outcome: ReturnType; + try { + const plan = await validatePush(this.store, commands, unpackError); + outcome = this.ctx.storage.transactionSync(() => commitPush(this.store, plan)); + } catch (err) { + // Reclaim a pack that never reached a ref decision, or it holds quota with no cleanup queued. + if (packId !== null) await queueHostedGitGc(this.store, this.ctx.storage); + throw err; + } + const { results, changed, needsGc } = outcome; if (changed) { this.store.setMeta('created', '1'); this.store.setMeta('last-push', String(Date.now())); } - if (needsGc || packId !== null) { - this.store.setMeta('gc-pending', '1'); - this.store.setMeta('gc-attempts', '0'); - await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS).catch(() => undefined); - } + if (needsGc || packId !== null) await queueHostedGitGc(this.store, this.ctx.storage); if (caps.includes('report-status')) emit(renderStatus(results, unpackError, sideband)); } } diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 3e0f40f704..c7e595e170 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -38,3 +38,5 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Ref admission rejects `.lock` suffixes on every path component and a final dot, matching Git check-ref-format; the full rule matrix also retains SAM conservative character and length bounds. - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. + +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index c2e280f728..9d19aac2c5 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -7,7 +7,7 @@ import { GitStore } from "./store"; import { PackWriter } from "./pack"; import { OidSet } from "./oidset"; import { MultipartCapture, MultipartPackUpload } from "./multipart"; -import { parseCommit, parseTag, parseTree, isGitlinkMode, isTreeMode, TYPE_NUM, NUM_TYPE, ObjType } from "./objects"; +import { GitParseError, parseCommit, parseTag, parseTree, isGitlinkMode, isTreeMode, TYPE_NUM, NUM_TYPE, ObjType } from "./objects"; const AGENT = "agent=dgit/0.3"; const INFINITE_DEPTH = 0x7fffffff; @@ -1126,20 +1126,68 @@ const BAD_REF = /[\s~^:?*\[\\'"<>&`\x00-\x1f\x7f]/; * exist (Codex r4633317762). `known` therefore only ever holds validated * closures, which is also what commitPush folds into the reachable cache. */ -async function reachableComplete(store: GitStore, tip: string, known: OidSet): Promise { +async function reachableComplete( + store: GitStore, + tip: string, + known: OidSet, + failed: OidSet +): Promise { if (known.hasHex(tip)) return true; // tip already in a validated closure - // Cursor BFS over the scratch set itself: newly reached oids append past - // the cursor, so no separate hex-oid stack is needed to walk it. + if (failed.hasHex(tip)) return false; // an earlier command in this push proved it incomplete + // Cursor BFS over the scratch set itself: newly reached oids append past the + // cursor, so no separate hex-oid stack is needed to walk it. Parallel arrays + // hold each entry's BFS parent and the type its referencing edge requires. const fresh = new OidSet(1024); + let parent = new Uint32Array(1024); + let expect: (ObjType | null)[] = [null]; // the tip may be any type fresh.addHex(tip); + // SAM: every oid on the BFS path from the tip to a failing entry has that + // entry in its closure, so it is incomplete for the rest of this push. + // Recording the path means repeated or overlapping failing commands stop + // at the first known-bad oid instead of re-walking the same objects. + const fail = (i: number): false => { + for (let j = i; ; j = parent[j]) { + failed.addHex(fresh.atHex(j)); + if (j === 0) return false; + } + }; for (let i = 0; i < fresh.size; i++) { const oid = fresh.atHex(i); + if (i > 0 && failed.hasHex(oid)) return fail(i); const meta = store.typeAndSize(oid); - if (!meta) return false; + if (!meta) return fail(i); + // A type mismatch is the referencing object's fault, not this object's: blame the + // parent (and its ancestors) so a valid object shared elsewhere stays usable. + if (expect[i] !== null && meta.type !== expect[i]) return fail(parent[i]); if (meta.type === "blob") continue; const obj = await store.get(oid); - if (!obj) return false; - for (const child of childOids(obj)) if (!known.hasHex(child)) fresh.addHex(child); + if (!obj) return fail(i); + let children: ChildRef[]; + try { + children = childRefs(obj); + } catch (err) { + // SAM: a commit, tag or tree that does not parse cannot have a proven + // closure; reject this command rather than failing the whole push. + if (err instanceof GitParseError) return fail(i); + throw err; + } + for (const child of children) { + if (known.hasHex(child.oid) || fresh.hasHex(child.oid)) { + // Already validated or queued under another edge: this edge still has to name + // an object of the type it requires (absent ones fail when their entry is walked). + const type = store.typeAndSize(child.oid)?.type; + if (type !== undefined && type !== child.type) return fail(i); + continue; + } + fresh.addHex(child.oid); + if (fresh.size > parent.length) { + const bigger = new Uint32Array(parent.length * 2); + bigger.set(parent); + parent = bigger; + } + parent[fresh.size - 1] = i; + expect[fresh.size - 1] = child.type; + } } for (let i = 0; i < fresh.size; i++) known.addHex(fresh.atHex(i)); return true; @@ -1190,6 +1238,41 @@ function childOids(obj: { type: ObjType; data: Uint8Array }): string[] { return []; } +/** An object a parent references, with the type the reference requires. */ +interface ChildRef { + oid: string; + type: ObjType; +} + +const TAG_TARGET_TYPES: ReadonlySet = new Set(["commit", "tree", "blob", "tag"]); + +/** + * The objects a non-blob object references (blobs are leaves), each with the type + * git requires at that edge. SAM: upstream returned bare oids, so a commit whose + * "tree" was a blob, or whose parent was a tree, passed the presence-only walk and + * then broke every clone ("bad tree pointer"); the walk now checks each edge's type. + */ +function childRefs(obj: { type: ObjType; data: Uint8Array }): ChildRef[] { + if (obj.type === "commit") { + const c = parseCommit(obj.data); + return [{ oid: c.tree, type: "tree" }, ...c.parents.map((oid) => ({ oid, type: "commit" as ObjType }))]; + } + if (obj.type === "tag") { + const t = parseTag(obj.data); + if (!TAG_TARGET_TYPES.has(t.type)) throw new GitParseError("tag has invalid type header"); + return [{ oid: t.object, type: t.type as ObjType }]; + } + if (obj.type === "tree") { + const out: ChildRef[] = []; + for (const e of parseTree(obj.data)) { + if (isGitlinkMode(e.mode)) continue; + out.push({ oid: e.oid, type: isTreeMode(e.mode) ? "tree" : "blob" }); + } + return out; + } + return []; +} + export async function validatePush( store: GitStore, commands: PushCommand[], @@ -1207,14 +1290,48 @@ export async function validatePush( // could vouch for a later command. Repository caps bound the walk. // pre-existing ref tips bound the connectivity walk: their closure is // already validated, so a normal fast-forward only re-checks new objects + // SAM: seeding reads no objects. Upstream peeled every ref tip here, which + // inflated each tip under the push's decompression budget on every push, so + // a handful of large tips made every later push, including the deletion + // that would remove them, exceed the budget. Only cached peel targets count. const known = new OidSet(4096); - for (const r of store.refs()) { + const existing = store.refs(); + for (const r of existing) { known.addHex(r.target); - const c = await peelToCommitOid(store, r.target); - if (c) known.addHex(c); + const peeled = store.getPeeled(r.target); + if (peeled) known.addHex(peeled); } const knownHead = store.resolveHead(); if (knownHead) known.addHex(knownHead); + // oids proven to have an incomplete closure earlier in this push + const failed = new OidSet(1024); + // SAM: directory/file conflicts. Git cannot store both refs/heads/a and + // refs/heads/a/b (clients fail to fetch them), so a new ref must not be a path + // prefix of a ref, nor have one as a prefix. Deletions in this push with a + // matching old value apply first, as in git's ref transaction. + const refNames = new Set(); + const dirCounts = new Map(); + const trackRef = (name: string, delta: 1 | -1) => { + if (delta === 1) refNames.add(name); + else refNames.delete(name); + for (let k = name.indexOf("/"); k !== -1; k = name.indexOf("/", k + 1)) { + const dir = name.slice(0, k); + dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + delta); + } + }; + const refConflict = (name: string) => { + if ((dirCounts.get(name) ?? 0) > 0) return true; + for (let k = name.indexOf("/"); k !== -1; k = name.indexOf("/", k + 1)) { + if (refNames.has(name.slice(0, k))) return true; + } + return false; + }; + for (const r of existing) trackRef(r.name, 1); + for (const cmd of commands) { + if (cmd.next === ZERO_OID && refNames.has(cmd.ref) && store.getRef(cmd.ref) === cmd.old) { + trackRef(cmd.ref, -1); + } + } const decisions: PushDecision[] = []; for (const cmd of commands) { @@ -1239,13 +1356,24 @@ export async function validatePush( decisions.push({ ref: cmd.ref, expectedOld: cmd.old, del: true }); continue; } - const connected = await reachableComplete(store, cmd.next, known); + if (current === ZERO_OID && refConflict(cmd.ref)) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "ref name conflicts with an existing ref" }); + continue; + } + // SAM: git refuses to write a non-commit to a branch; a clone of such a + // repository fails while updating HEAD. + if (cmd.ref.startsWith("refs/heads/") && store.typeAndSize(cmd.next)?.type !== "commit") { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "trying to write non-commit object to branch" }); + continue; + } + const connected = await reachableComplete(store, cmd.next, known, failed); if (!connected) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "missing necessary objects" }); continue; } const forced = cmd.old !== ZERO_OID && !(await isAncestor(store, cmd.old, cmd.next)); decisions.push({ ref: cmd.ref, expectedOld: cmd.old, set: cmd.next, forced }); + if (current === ZERO_OID) trackRef(cmd.ref, 1); } return { decisions, known, hadCache }; } @@ -1275,6 +1403,12 @@ export function commitPush(store: GitStore, plan: PushPlan): { results: CommandR continue; } if (d.del) { + // SAM: deleting a ref that does not exist succeeds without changing + // anything (as in git), so it must not queue a GC episode either. + if (current === ZERO_OID) { + results.push({ ref: d.ref, ok: true }); + continue; + } store.delRef(d.ref); needsGc = true; } else { diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 83ee0416df..04bd2d2026 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -943,6 +943,23 @@ describe('push connectivity admission (closure must be complete per command)', ( return res.text(); } + async function info(project: CreatedProject): Promise<{ objects: number }> { + return (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { objects: number }; + } + + async function gcState(project: CreatedProject): Promise<{ pending: string; alarm: number | null }> { + const res = await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`); + return (await res.json()) as { pending: string; alarm: number | null }; + } + + /** Every blob and subtree under a commit's root tree. */ + async function treeObjects(cwd: string, commit: string): Promise { + return (await gitOk(['ls-tree', '-r', '-t', commit], cwd)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(/\s+/)[2]!); + } + async function reachableCache(project: CreatedProject): Promise { const info = (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { reachableCache: boolean; @@ -968,18 +985,19 @@ describe('push connectivity admission (closure must be complete per command)', ( const { commit, tree } = await commitFile(work, 'attack.txt'); // The pack carries the commit but not its tree. The first command's walk reaches the - // missing tree and fails; the second command names that same tree directly. + // missing tree and fails; the second command names that same tree directly. It is a tag, + // since branches refuse non-commits before any walk, so only the walk decides it. const out = await receive( project, token, [ [ZERO, commit, 'refs/heads/attack-commit'], - [ZERO, tree, 'refs/heads/attack-tree'], + [ZERO, tree, 'refs/tags/attack-tree'], ], packOf(work, [commit]) ); expect(out).toContain('ng refs/heads/attack-commit missing necessary objects'); - expect(out).toContain('ng refs/heads/attack-tree missing necessary objects'); + expect(out).toContain('ng refs/tags/attack-tree missing necessary objects'); const refs = (await gitOk(['ls-remote', remote])).stdout; expect(refs).toContain('refs/heads/main'); expect(refs).not.toContain('attack-commit'); @@ -1049,6 +1067,198 @@ describe('push connectivity admission (closure must be complete per command)', ( await assertCleanClone(remote); }); + it('with a reachable cache, one failing command does not block or pollute a valid sibling', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure mixed push'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-mixed'); + await gitOk(['clone', remote, work]); + expect(await reachableCache(project)).toBe(true); + const base = await rev(work, 'HEAD'); + const valid = await commitFile(work, 'valid.txt'); + await gitOk(['checkout', '-q', '--detach', base], work); + const broken = await commitFile(work, 'broken.txt'); + const validObjects = (await gitOk(['rev-list', '--objects', valid.commit, `^${base}`], work)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(' ')[0]!); + const out = await receive( + project, + token, + [ + [ZERO, broken.commit, 'refs/heads/broken'], + [ZERO, valid.commit, 'refs/heads/valid'], + ], + packOf(work, [broken.commit, ...validObjects]) + ); + expect(out).toContain('ng refs/heads/broken missing necessary objects'); + expect(out).toContain('ok refs/heads/valid'); + expect(await reachableCache(project)).toBe(true); + const check = await assertCleanClone(remote); + expect(await rev(check, 'origin/valid')).toBe(valid.commit); + expect((await gitOk(['ls-remote', remote])).stdout).not.toContain('refs/heads/broken'); + }); + + it('refuses a commit that does not parse for that command only, and queues its pack for GC', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure malformed'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + const work = await freshDir('closure-malformed'); + await gitOk(['init', '-q', '-b', 'main', work]); + const made = spawnSync('git', ['hash-object', '-t', 'commit', '--literally', '-w', '--stdin'], { + cwd: work, + env: gitEnv(), + input: `author ${'Test 0 +0000'}\ncommitter Test 0 +0000\n\nno tree header\n`, + }); + expect(made.status).toBe(0); + const malformed = made.stdout.toString().trim(); + const ordinary = await commitFile(work, 'ordinary.txt'); + const out = await receive( + project, + token, + [ + [ZERO, malformed, 'refs/heads/malformed'], + [ZERO, ordinary.commit, 'refs/heads/ordinary'], + ], + packOf(work, [malformed, ordinary.commit, ordinary.tree, ...(await treeObjects(work, ordinary.commit))]) + ); + expect(out).toContain('ng refs/heads/malformed missing necessary objects'); + expect(out).toContain('ok refs/heads/ordinary'); + expect((await gcState(project)).pending).toBe('1'); + await assertCleanClone(remote); + }); + + it('queues GC for an ingested pack when validation fails before any ref decision', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure validate fault'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + const before = await info(project); + const work = await freshDir('closure-fault'); + await gitOk(['init', '-q', '-b', 'main', work]); + const root = await commitFile(work, 'fault.txt'); + // The next read of this commit throws: ingest has stored the pack, the walk then faults. + await runtime.fetch(`/__test/fail-read/${project.artifactsRepoId}/${root.commit}`, { method: 'POST' }); + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body: buildReceivePackRequest( + root.commit, + 'fault', + packOf(work, [root.commit, root.tree, ...(await treeObjects(work, root.commit))]) + ) as BodyInit, + }); + const text = await res.text(); + // The fault surfaced from validation, not from ingest (which would answer "unpack ..."). + expect(res.status).toBe(500); + expect(text).not.toContain('unpack'); + expect((await info(project)).objects).toBeGreaterThan(before.objects); + const queued = await gcState(project); + expect(queued.pending).toBe('1'); + expect(queued.alarm).not.toBeNull(); + expect((await gitOk(['ls-remote', remote])).stdout).not.toContain('refs/heads/fault'); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect((await info(project)).objects).toBe(before.objects); + }); + + it('keeps pushes and deletions working however large the existing ref tips are', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Large tips'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('large-tips'); + await gitOk(['clone', remote, work]); + const base = await rev(work, 'HEAD'); + // Each tip is a commit with a 5 MiB message (a few KB compressed). Objects over a quarter of + // the 16 MiB serving cache are never cached, so every read inflates it again. A push costs + // about 10 MiB of a 14 MiB decompression budget; reading the existing tips on each push + // would exceed it from the second tip on. + const message = join(work, '..', `msg-${randomBytes(4).toString('hex')}`); + await writeFile(message, 'a'.repeat(5 * 1024 * 1024)); + const setting = "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxInflatedBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"; + await runtime.DATABASE.prepare(setting).bind(JSON.stringify(14 * 1024 * 1024), Date.now()).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + for (let i = 0; i < 4; i++) { + await gitOk(['checkout', '-q', '--detach', base], work); + await writeFile(join(work, `big-${i}.txt`), `${i}\n`); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-q', '-F', message], work); + await gitOk(['push', 'origin', `HEAD:refs/heads/big-${i}`], work); + } + const small = await commitFile(work, 'small.txt'); + await gitOk(['push', 'origin', 'HEAD:refs/heads/small'], work); + await gitOk(['push', 'origin', '--delete', 'big-0'], work); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${small.commit}\trefs/heads/small`); + expect(refs).toContain('refs/heads/big-3'); + expect(refs).not.toContain('refs/heads/big-0\n'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxInflatedBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + + it('refuses objects of the wrong type at an edge or on a branch, and keeps clones working', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Edge types'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('edge-types'); + await gitOk(['init', '-q', '-b', 'main', work]); + const plain = await commitFile(work, 'plain.txt'); + const blob = (await gitOk(['rev-parse', `${plain.commit}:plain.txt`], work)).stdout.trim(); + const made = spawnSync('git', ['hash-object', '-t', 'commit', '--literally', '-w', '--stdin'], { + cwd: work, + env: gitEnv(), + input: `tree ${blob}\nauthor Test 0 +0000\ncommitter Test 0 +0000\n\nblob as tree\n`, + }); + expect(made.status).toBe(0); + const evil = made.stdout.toString().trim(); + const out = await receive( + project, + token, + [ + [ZERO, evil, 'refs/heads/evil'], + [ZERO, plain.tree, 'refs/heads/tree-branch'], + [ZERO, plain.tree, 'refs/tags/tree-tag'], + ], + packOf(work, [evil, blob, plain.tree]) + ); + expect(out).toContain('ng refs/heads/evil missing necessary objects'); + expect(out).toContain('ng refs/heads/tree-branch trying to write non-commit object to branch'); + expect(out).toContain('ok refs/tags/tree-tag'); + await assertCleanClone(remote); + }); + + it('treats deleting a missing ref as a no-op that queues no GC, and refuses D/F ref conflicts', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Ref no-ops'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + const missing = await receive(project, token, [[ZERO, ZERO, 'refs/heads/never-existed']]); + expect(missing).toContain('ok refs/heads/never-existed'); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + + const main = (await gitOk(['ls-remote', remote, 'refs/heads/main'])).stdout.split(/\s+/)[0]!; + expect(await receive(project, token, [[ZERO, main, 'refs/heads/df']])).toContain('ok refs/heads/df'); + const nested = await receive(project, token, [ + [ZERO, main, 'refs/heads/df/x'], + [ZERO, main, 'refs/heads/dfx'], + ]); + expect(nested).toContain('ng refs/heads/df/x ref name conflicts with an existing ref'); + expect(nested).toContain('ok refs/heads/dfx'); + // A real deletion is the control: it changes refs and queues GC. + expect(await receive(project, token, [[main, ZERO, 'refs/heads/df']])).toContain('ok refs/heads/df'); + expect((await gcState(project)).pending).toBe('1'); + await assertCleanClone(remote); + }); + it('without a reachable cache, a valid push from a shallow clone is accepted', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Closure shallow control'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index c9fc44fecf..f66292bb0a 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -42,6 +42,19 @@ export class HostedGitRepoTest extends HostedGitRepo { try { await this.alarm(); } finally { store.get = get; } return new Response('ok'); } + if (new URL(req.url).pathname.startsWith('/__test/fail-read/')) { + // One-shot: the next read of this object throws, as a storage fault or an exhausted work + // budget would, so a push fails after its pack was ingested but before any ref decision. + const oid = new URL(req.url).pathname.slice('/__test/fail-read/'.length); + const store = (this as unknown as { store: { get: (oid: string, ...rest: unknown[]) => Promise } }).store; + const get = store.get; + store.get = async (target: string, ...rest: unknown[]) => { + if (target !== oid) return get.call(store, target, ...rest); + store.get = get; + throw new Error('injected read failure during push validation'); + }; + return new Response('ok'); + } if (new URL(req.url).pathname === '/__test/gc-state') { return Response.json({ pending: this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'").toArray()[0]?.value, alarm: await this.ctx.storage.getAlarm() }); } @@ -114,6 +127,11 @@ app.delete('/__test/repository/:repo', async (c) => { return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/', { method: 'DELETE' }); }); +app.post('/__test/fail-read/:repo/:oid', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns.get(ns.idFromName(c.req.param('repo'))).fetch(`https://hosted-git/__test/fail-read/${c.req.param('oid')}`); +}); + app.post('/__test/alarm/:repo/:mode', (c) => { const ns = c.env.HOSTED_GIT!; return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/alarm' + (c.req.param('mode') === 'fail' ? '-fail' : '')); diff --git a/apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts b/apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts new file mode 100644 index 0000000000..50d1505f6e --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts @@ -0,0 +1,137 @@ +import { createHash } from 'node:crypto'; + +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +import { withGitWorkBudget } from '../../../src/vendor/dgit/git/budget'; +import { validatePush } from '../../../src/vendor/dgit/git/protocol'; +import type { GitStore } from '../../../src/vendor/dgit/git/store'; + +/** + * The connectivity walk's per-push failure memo, counted at the object-store boundary. + * The real-git suite (tests/hosted-git) proves admission end to end; these tests drive + * validatePush past every count in the path (rule 81) and measure how much it reads. + */ +const ZERO = '0'.repeat(40); +const oidOf = (label: string) => createHash('sha1').update(label).digest('hex'); +const enc = new TextEncoder(); +const SIG = 'Test 0 +0000'; + +type Obj = { type: 'commit' | 'tree' | 'blob' | 'tag'; data: Uint8Array }; + +/** A fake object store over a map, counting every presence probe and object read. */ +function fakeStore(objects: Map) { + const counts = { probes: 0, reads: 0 }; + const store = { + getMeta: () => null, + reachableVersion: () => 'v', + refs: () => [], + resolveHead: () => null, + getRef: () => null, + getPeeled: () => null, + typeAndSize: (oid: string) => { + counts.probes += 1; + const obj = objects.get(oid); + return obj ? { type: obj.type, size: obj.data.length } : null; + }, + get: async (oid: string) => { + counts.reads += 1; + return objects.get(oid) ?? null; + }, + } as unknown as GitStore; + return { store, counts }; +} + +/** + * A linear history c1..cN sharing one tree. `missingTree` points the ROOT commit at an absent + * tree, so a walk from the tip must cross the whole history before it fails. + */ +function chain( + length: number, + opts: { missingTree?: boolean; brokenRoot?: boolean; label?: string } = {} +) { + const objects = new Map(); + const blob = oidOf('blob'); + objects.set(blob, { type: 'blob', data: enc.encode('hello\n') }); + const tree = oidOf('tree'); + const entry = new Uint8Array([...enc.encode('100644 a.txt\0'), ...Buffer.from(blob, 'hex')]); + objects.set(tree, { type: 'tree', data: entry }); + const commits: string[] = []; + for (let i = 1; i <= length; i++) { + const oid = oidOf(`${opts.label ?? 'commit'}-${i}`); + const parent = commits.length ? `parent ${commits[commits.length - 1]}\n` : ''; + const rootTree = i === 1 && opts.missingTree ? oidOf('absent-tree') : tree; + const header = i === 1 && opts.brokenRoot ? '' : `tree ${rootTree}\n`; + const text = `${header}${parent}author ${SIG}\ncommitter ${SIG}\n\nc${i}\n`; + objects.set(oid, { type: 'commit', data: enc.encode(text) }); + commits.push(oid); + } + return { objects, commits }; +} + +async function decide(store: GitStore, commands: { old: string; next: string; ref: string }[]) { + return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => validatePush(store, commands, null)); +} + +const N = 1201; // history longer than any internal batch, not a multiple of 2 +const K = 2001; // commands, more than the commit count + +describe('validatePush closure walk', () => { + it('rejects many commands at one broken tip after walking the history once', async () => { + const { objects, commits } = chain(N, { missingTree: true }); + const { store, counts } = fakeStore(objects); + const tip = commits[commits.length - 1]!; + const commands = Array.from({ length: K }, (_, i) => ({ + old: ZERO, + next: tip, + ref: `refs/heads/b${i}`, + })); + const plan = await decide(store, commands); + expect(plan.decisions).toHaveLength(K); + for (const d of plan.decisions) expect(d.reject).toBe('missing necessary objects'); + // One full walk (N commits, a type probe for each commit's edge to the shared tree, the + // tree and blob, the absent tree) plus one branch type probe per command; every later + // command stops at its tip, which that walk recorded as failed. Unmemoized: about K x N. + expect(counts.probes).toBeLessThanOrEqual(2 * N + 3 + K); + expect(counts.reads).toBeLessThanOrEqual(N + 1); + }); + + it('rejects commands at every commit of a broken history without re-walking it', async () => { + const { objects, commits } = chain(N, { missingTree: true }); + const { store, counts } = fakeStore(objects); + // Oldest first: each tip's walk reaches its parent, which an earlier command proved broken. + // Unmemoized, command i re-walks i commits: about N^2 / 2 reads. + const commands = commits.map((next, i) => ({ old: ZERO, next, ref: `refs/heads/c${i}` })); + const plan = await decide(store, commands); + for (const d of plan.decisions) expect(d.reject).toBe('missing necessary objects'); + expect(counts.probes).toBeLessThanOrEqual(5 * N); + expect(counts.reads).toBeLessThanOrEqual(2 * N); + }); + + it('rejects a commit that does not parse instead of failing the whole push', async () => { + const { objects, commits } = chain(3, { brokenRoot: true }); + const good = chain(2, { label: 'good' }); + for (const [oid, obj] of good.objects) objects.set(oid, obj); + const { store } = fakeStore(objects); + const plan = await decide(store, [ + { old: ZERO, next: commits[2]!, ref: 'refs/heads/broken' }, + { old: ZERO, next: good.commits[1]!, ref: 'refs/heads/good' }, + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: good.commits[1] }); + }); + + it('accepts a complete history and every commit in it (positive control)', async () => { + const { objects, commits } = chain(N); + const { store, counts } = fakeStore(objects); + const commands = [...commits] + .reverse() + .map((next, i) => ({ old: ZERO, next, ref: `refs/heads/ok${i}` })); + const plan = await decide(store, commands); + for (const [i, d] of plan.decisions.entries()) + expect(d).toMatchObject({ set: commands[i]!.next }); + // The first command proves the whole history; later commands stop at their own tip. + expect(counts.reads).toBeLessThanOrEqual(N + 1); + expect(plan.known.hasHex(commits[0]!)).toBe(true); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts index d2cde12f1e..eab33d8cde 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts @@ -7,6 +7,7 @@ const state = vi.hoisted(() => ({ events: [] as string[], validate: vi.fn(), setAlarm: vi.fn(async () => undefined), + getAlarm: vi.fn(async () => null), cancel: vi.fn(), deleteAlarm: vi.fn(async () => undefined), })); @@ -72,6 +73,7 @@ function repo() { sql: {}, deleteAlarm: state.deleteAlarm, setAlarm: state.setAlarm, + getAlarm: state.getAlarm, transactionSync: (fn: () => unknown) => fn(), }, blockConcurrencyWhile: async (fn: () => Promise) => fn(), diff --git a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts index 9f7feaf7c5..0cb673b9ce 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts @@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({ attempts: '0', gc: vi.fn(async () => ({ removed: 1, kept: 2 })), setAlarm: vi.fn(async () => undefined), + getAlarm: vi.fn(async () => null), })); vi.mock('cloudflare:workers', () => ({ DurableObject: class { @@ -31,7 +32,10 @@ vi.mock('../../../src/vendor/dgit/git/store', () => ({ } }, })); -vi.mock('../../../src/selfhost/hosted-git/hosted-git-gc', () => ({ runHostedGitGc: mocks.gc })); +vi.mock('../../../src/selfhost/hosted-git/hosted-git-gc', async (importOriginal) => ({ + ...(await importOriginal()), + runHostedGitGc: mocks.gc, +})); beforeEach(() => { mocks.pending = '1'; mocks.attempts = '0'; @@ -41,7 +45,7 @@ beforeEach(() => { describe('hosted git GC admission', () => { it('rechecks uploads after waiting behind a push, and runs once after the upload leaves', async () => { const ctx = { - storage: { setAlarm: mocks.setAlarm }, + storage: { setAlarm: mocks.setAlarm, getAlarm: mocks.getAlarm }, blockConcurrencyWhile: async (action: () => Promise) => action(), }; const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); @@ -68,7 +72,7 @@ describe('hosted git GC admission', () => { expect(mocks.gc).toHaveBeenCalledOnce(); }); it('retries a transient failed sweep and resets its attempt budget after success', async () => { - const ctx = { storage: { setAlarm: mocks.setAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() }; + const ctx = { storage: { setAlarm: mocks.setAlarm, getAlarm: mocks.getAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() }; const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); for (let cycle = 0; cycle < 4; cycle++) { mocks.pending = '1'; @@ -83,7 +87,7 @@ describe('hosted git GC admission', () => { await repo.alarm(); expect(mocks.gc).toHaveBeenCalledTimes(calls); }); it('stops automatic retries after the configured consecutive failure budget', async () => { - const repo = new HostedGitRepo({ storage: { setAlarm: mocks.setAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() } as unknown as DurableObjectState, {}); + const repo = new HostedGitRepo({ storage: { setAlarm: mocks.setAlarm, getAlarm: mocks.getAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() } as unknown as DurableObjectState, {}); mocks.gc.mockRejectedValue(new Error('permanent failure')); for (let tick = 0; tick < 5; tick++) await repo.alarm(); expect(mocks.gc).toHaveBeenCalledTimes(3); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts new file mode 100644 index 0000000000..0e694b72e2 --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -0,0 +1,265 @@ +import { createHash } from 'node:crypto'; + +import { describe, expect, it, vi } from 'vitest'; + +import { armHostedGitGcAlarm, GC_DELAY_MS } from '../../../src/selfhost/hosted-git/hosted-git-gc'; +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +import { withGitWorkBudget } from '../../../src/vendor/dgit/git/budget'; +import { commitPush, validatePush } from '../../../src/vendor/dgit/git/protocol'; +import type { GitStore } from '../../../src/vendor/dgit/git/store'; + +/** + * Push admission guards from the adversarial review of PR #2907, at the store boundary: + * ref seeding reads no objects, every walked edge has the type git requires, branches hold + * only commits, directory/file ref conflicts are refused, and deleting a missing ref is a + * no-op that queues no GC. tests/hosted-git covers the same guards through real git. + */ +const ZERO = '0'.repeat(40); +const enc = new TextEncoder(); +const oidOf = (label: string) => createHash('sha1').update(label).digest('hex'); +const SIG = 'Test 0 +0000'; + +type Kind = 'commit' | 'tree' | 'blob' | 'tag'; +type Obj = { type: Kind; data: Uint8Array }; + +function treeEntry(mode: string, name: string, oid: string): number[] { + return [...enc.encode(`${mode} ${name}\0`), ...Buffer.from(oid, 'hex')]; +} + +class Repo { + objects = new Map(); + refs = new Map(); + reads = 0; + + put(label: string, type: Kind, data: Uint8Array): string { + const oid = oidOf(label); + this.objects.set(oid, { type, data }); + return oid; + } + blob(label: string) { + return this.put(label, 'blob', enc.encode(`${label}\n`)); + } + tree(label: string, entries: number[][]) { + return this.put(label, 'tree', new Uint8Array(entries.flat())); + } + commit(label: string, tree: string, parents: string[] = []) { + const text = `tree ${tree}\n${parents.map((p) => `parent ${p}\n`).join('')}author ${SIG}\ncommitter ${SIG}\n\n${label}\n`; + return this.put(label, 'commit', enc.encode(text)); + } + tag(label: string, object: string, type: string) { + return this.put(label, 'tag', enc.encode(`object ${object}\ntype ${type}\ntag ${label}\ntagger ${SIG}\n\n${label}\n`)); + } + /** A complete one-file commit. */ + simple(label: string, parents: string[] = []) { + const tree = this.tree(`${label}-tree`, [treeEntry('100644', 'f', this.blob(`${label}-blob`))]); + return this.commit(label, tree, parents); + } + + store(): GitStore { + return { + getMeta: () => null, + reachableVersion: () => 'v', + refs: () => [...this.refs].map(([name, target]) => ({ name, target })), + resolveHead: () => null, + getRef: (name: string) => this.refs.get(name) ?? null, + getPeeled: () => null, + typeAndSize: (oid: string) => { + const obj = this.objects.get(oid); + return obj ? { type: obj.type, size: obj.data.length } : null; + }, + get: async (oid: string) => { + this.reads += 1; + return this.objects.get(oid) ?? null; + }, + head: () => 'refs/heads/main', + setHead: () => undefined, + setRef: (name: string, target: string) => void this.refs.set(name, target), + delRef: (name: string) => void this.refs.delete(name), + invalidateReachable: () => undefined, + extendReachable: () => undefined, + } as unknown as GitStore; + } +} + +async function decide(repo: Repo, commands: [old: string, next: string, ref: string][]) { + return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush(repo.store(), commands.map(([old, next, ref]) => ({ old, next, ref })), null) + ); +} + +describe('push admission: ref seeding', () => { + it('reads no existing ref tip before deciding commands', async () => { + const repo = new Repo(); + const tips: string[] = []; + for (let i = 0; i < 1201; i++) { + tips.push(repo.simple(`tip-${i}`)); + repo.refs.set(`refs/heads/t${i}`, tips[i]!); + } + const next = repo.simple('on-top', [tips[7]!]); + repo.reads = 0; + const plan = await decide(repo, [ + [tips[3]!, ZERO, 'refs/heads/t3'], + [ZERO, next, 'refs/heads/new'], + ]); + expect(plan.decisions[0]).toMatchObject({ del: true }); + expect(plan.decisions[1]).toMatchObject({ set: next }); + // The new commit and its tree: its parent is an existing tip and is never read. + expect(repo.reads).toBe(2); + }); +}); + +describe('push admission: edge types', () => { + it('refuses a commit whose tree is a blob, with a valid sibling accepted', async () => { + const repo = new Repo(); + const blob = repo.blob('loose'); + const evil = repo.commit('blob-as-tree', blob); + const good = repo.simple('good'); + const plan = await decide(repo, [ + [ZERO, evil, 'refs/heads/evil'], + [ZERO, good, 'refs/heads/good'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: good }); + }); + + it('refuses a commit whose parent is a tree', async () => { + const repo = new Repo(); + const base = repo.simple('base'); + const tree = repo.tree('t', [treeEntry('100644', 'f', repo.blob('b'))]); + const evil = repo.commit('tree-as-parent', tree, [tree]); + repo.refs.set('refs/heads/main', base); + const plan = await decide(repo, [[ZERO, evil, 'refs/heads/evil']]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + }); + + it('refuses a validated object at an edge of the wrong type', async () => { + const repo = new Repo(); + const tip = repo.simple('tip'); + repo.refs.set('refs/heads/main', tip); + // The existing tip is in the validated set, but a commit's tree must be a tree. + const evil = repo.commit('commit-as-tree', tip); + const plan = await decide(repo, [[ZERO, evil, 'refs/heads/evil']]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + const ok = repo.simple('child', [tip]); + expect((await decide(repo, [[ZERO, ok, 'refs/heads/child']])).decisions[0]).toMatchObject({ set: ok }); + }); + + it('refuses a tree entry whose mode disagrees with its object type', async () => { + const repo = new Repo(); + const inner = repo.tree('inner', [treeEntry('100644', 'f', repo.blob('x'))]); + const evil = repo.commit('mode', repo.tree('outer', [treeEntry('100644', 'dir', inner)])); + const fine = repo.commit('fine', repo.tree('outer-ok', [treeEntry('40000', 'dir', inner)])); + const plan = await decide(repo, [ + [ZERO, evil, 'refs/heads/evil'], + [ZERO, fine, 'refs/heads/fine'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: fine }); + }); + + it('refuses an annotated tag whose type header disagrees with its object', async () => { + const repo = new Repo(); + const commit = repo.simple('tagged'); + const lying = repo.tag('lying', commit, 'tree'); + const honest = repo.tag('honest', commit, 'commit'); + const plan = await decide(repo, [ + [ZERO, lying, 'refs/tags/lying'], + [ZERO, honest, 'refs/tags/honest'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: honest }); + }); + + it('refuses a non-commit on a branch but allows it as a lightweight tag', async () => { + const repo = new Repo(); + const tree = repo.tree('bare', [treeEntry('100644', 'f', repo.blob('y'))]); + const plan = await decide(repo, [ + [ZERO, tree, 'refs/heads/tree'], + [ZERO, tree, 'refs/tags/tree'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'trying to write non-commit object to branch' }); + expect(plan.decisions[1]).toMatchObject({ set: tree }); + }); +}); + +describe('push admission: directory/file ref conflicts', () => { + it('refuses a ref nested under an existing ref, and an existing ref nested under a new one', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + repo.refs.set('refs/heads/a', c); + repo.refs.set('refs/heads/x/y', c); + const plan = await decide(repo, [ + [ZERO, c, 'refs/heads/a/b'], + [ZERO, c, 'refs/heads/x'], + [ZERO, c, 'refs/heads/ab'], + [ZERO, c, 'refs/heads/x-y'], + ]); + expect(plan.decisions.map((d) => d.reject ?? 'set')).toEqual([ + 'ref name conflicts with an existing ref', + 'ref name conflicts with an existing ref', + 'set', + 'set', + ]); + }); + + it('refuses the second of two conflicting new refs in one push', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + const plan = await decide(repo, [ + [ZERO, c, 'refs/heads/n'], + [ZERO, c, 'refs/heads/n/m'], + ]); + expect(plan.decisions[0]).toMatchObject({ set: c }); + expect(plan.decisions[1]).toMatchObject({ reject: 'ref name conflicts with an existing ref' }); + }); + + it('allows replacing a ref with a nested one when the same push deletes it', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + repo.refs.set('refs/heads/a', c); + const plan = await decide(repo, [ + [ZERO, c, 'refs/heads/a/b'], + [c, ZERO, 'refs/heads/a'], + ]); + expect(plan.decisions[0]).toMatchObject({ set: c }); + expect(plan.decisions[1]).toMatchObject({ del: true }); + }); +}); + +describe('push admission: deleting a missing ref', () => { + it('reports success without changing refs or queueing GC, with a real deletion control', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + repo.refs.set('refs/heads/real', c); + const missing = commitPush(repo.store(), await decide(repo, [[ZERO, ZERO, 'refs/heads/nope']])); + expect(missing).toMatchObject({ changed: false, needsGc: false }); + expect(missing.results).toEqual([{ ref: 'refs/heads/nope', ok: true }]); + const real = commitPush(repo.store(), await decide(repo, [[c, ZERO, 'refs/heads/real']])); + expect(real).toMatchObject({ changed: true, needsGc: true }); + expect(repo.refs.has('refs/heads/real')).toBe(false); + }); +}); + +describe('armHostedGitGcAlarm', () => { + it('keeps an alarm already due sooner, and arms one when none is due or it is later', async () => { + vi.useFakeTimers({ now: 1_000_000 }); + try { + const due = Date.now() + GC_DELAY_MS; + const storage = (armed: number | null) => ({ + getAlarm: vi.fn(async () => armed), + setAlarm: vi.fn(async () => undefined), + }); + const sooner = storage(Date.now() + 1000); + await armHostedGitGcAlarm(sooner); + expect(sooner.setAlarm).not.toHaveBeenCalled(); + const none = storage(null); + await armHostedGitGcAlarm(none); + expect(none.setAlarm).toHaveBeenCalledWith(due); + const later = storage(due + 60_000); + await armHostedGitGcAlarm(later); + expect(later.setAlarm).toHaveBeenCalledWith(due); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts index 326dacbf30..71c4f534ff 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts @@ -17,9 +17,18 @@ const invalid = [ ...Array.from({ length: 33 }, (_, i) => `refs/heads/x${String.fromCharCode(i === 32 ? 127 : i)}y`), ]; const valid = ['refs/heads/normal', 'refs/heads/feature/x', 'refs/tags/v1.0', 'refs/heads/x.lockish/y', 'refs/heads/a.b/c', 'refs/heads/café']; +// The pushed tip is a commit with an empty tree, so valid names reach a `set` decision. +const tip = 'a'.repeat(40); +const tree = 'b'.repeat(40); +const objects: Record = { + [tip]: { type: 'commit', data: new TextEncoder().encode(`tree ${tree}\n\nmsg\n`) }, + [tree]: { type: 'tree', data: new Uint8Array(0) }, +}; const store = { getMeta: () => null, reachableVersion: () => '0', refs: () => [], resolveHead: () => null, - getRef: () => null, typeAndSize: () => ({ type: 'blob', size: 1 }), + getRef: () => null, getPeeled: () => null, + typeAndSize: (oid: string) => (objects[oid] ? { type: objects[oid].type, size: 1 } : null), + get: async (oid: string) => objects[oid] ?? null, } as unknown as GitStore; async function decision(ref: string) { return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, async () => { diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 4c7097dbe6..1fd2156344 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -219,6 +219,10 @@ push checks quota. Defaults are 64 MiB per push, 30,000 objects 10,000 refs and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation per request, delta depth 100 and 120 seconds per git operation. Operators can lower these limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. +Known limit: GC inflates every object it moves, under the same decompression budget, so it +cannot finish while more than `repositories.maxInflatedBytes` of pushed content waits for +collection. Unreclaimed packs then count toward the storage limit. Tracked in +`tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md`. Clone/push credentials expire and runtime credentials also require the same active workspace and callback generation. Deleting a project removes its hosted repository. At the ref limit, delete old refs in a separate push before creating replacements; an unvalidated deletion does not reserve space for new refs. diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index baf2bd60d6..48c0d7a554 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -84,6 +84,15 @@ Previous owner 01M7SR1B79 stopped after repeated provider content-filter refusal - [x] Same class, found while fixing it: the cache-less path trusted `packComplete` + `store.has(tip)`. That is sound only if every object outside the new pack is closure-complete, but a pack whose refs were all rejected stays ingested until GC. A later push (ref-only, or a pack whose commit's parent is the stale commit) could point a ref at an incomplete closure. Every command now proves its closure with the same walk; `packComplete` and the `push_edges` helpers/table creation are removed (existing repos keep an empty, unused `push_edges` table; no DO DROP). - [x] Real git/SQLite tests (describe "push connectivity admission"): cache-path multi-ref attack, cache-less stale-rejected-pack attack (ref-only and child-pack variants), and positive controls (overlapping multi-ref push extends the cache and a full clone fscks; shallow-clone push on the cache-less path). Both attack tests fail on 0eda6a2bd. Discrimination: A non-transactional walk -> both attack tests red; B cache-less presence-only -> stale-pack test red; C never merging into `known` -> cache control red (clone from extended cache fails fsck). Hosted suite 29/29, self-host unit 186/186, API typecheck and focused lint pass. - Bound (rule 81): one walk is bounded by the repository caps (30,000 objects, 256 MiB stored), the 128 MiB per-request inflation budget and the 120 s git-operation deadline. Worst case is one walk over every object in the repository: at most 30,000 SQLite presence probes plus inflating the non-blob objects, completing in one attempt or failing closed with the budget error. A fresh push's walk reads the same non-blob objects `packComplete` read before. -- [ ] Security delta review + one adversarial pass over the whole push admission path +- [x] Security delta review of d16d1538e: 0 CRITICAL/HIGH. MEDIUM-1 (failed walks not memoized, so repeated failing commands cost K x N) and MEDIUM-2 (a throw in validatePush left the ingested pack without GC; pre-existing) were fixed; LOW items were tested. +- [x] One adversarial pass over the whole push admission path (auth, parsing, limits, ingest, validatePush, commitPush, GC, status): 1 HIGH, 4 MEDIUM, 5 LOW; auth, CAS, savepoint, deletion and the earlier fixes held. Fixed in this PR: + - HIGH: seeding `known` peeled every ref tip, inflating each under the push budget, so nine large tips wedged every later push, deletions included. Seeding now reads no objects; it uses cached peel targets only. + - MEDIUM-2: the walk now checks the type git requires at every edge (commit.tree is a tree, parents are commits, tree entries match their mode, a tag's object matches its type header, including edges into already-validated objects). Branches refuse non-commits. A mismatch blames the referencing object, so a valid shared object is never poisoned. + - MEDIUM-5 (part): deleting a missing ref succeeds without queueing GC; arming the GC alarm keeps an earlier armed alarm, so pushes cannot postpone GC indefinitely. + - LOW-6: directory/file ref conflicts are refused (git transaction semantics, deletions in the same push first). + - Per-push failure memo (BFS path to the failing oid), GitParseError rejected per command, GC queued when validation/commit throws after ingest. +- Deferred with justification to `tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md`: MEDIUM-3 (GC inflates migrated objects under the same budget, so it cannot finish past 128 MiB of uncollected inflated content; needs a raw-copy GC redesign; documented as a known limit in the README), MEDIUM-4 (delta depth not checked at ingest; git defaults to 50), MEDIUM-5 rest (GC holds the input gate), LOW-7..10. Every deferred item needs a write token for that repository and is confined to it. +- Tests: unit hosted-git-closure-walk (memo at 1201 commits / 2001 commands, parse errors) and hosted-git-push-admission (seeding reads zero tips at 1201 refs, edge types, branch rule, D/F, no-op delete, alarm arming); real git: mixed failing/valid sibling with cache, malformed commit, validation fault after ingest queues GC (one-shot read-fault hook), large tips under a 14 MiB budget, edge types, no-op delete and D/F. Every guard was mutated once and the intended tests went red (memo, parse catch, GC on throw, non-transactional walk, peel seeding, child-vs-parent blame, duplicate-edge check, D/F, branch rule, no-op delete, first-edge type). +- Request-body helpers moved to `hosted-git-body.ts` so `hosted-git-repo.ts` stays under 500 lines; GC queueing is one helper (`queueHostedGitGc`, `armHostedGitGcAlarm`). - [ ] Fresh CI green, 0 open threads, Codex re-requested on final head - [ ] Final BOX smoke on the exact final head over main (closes the L22c "box from main runs an agent session" criterion deferred to H2 by Raphaël) diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md new file mode 100644 index 0000000000..68881719ce --- /dev/null +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -0,0 +1,38 @@ +# Hosted git: GC without inflation, delta depth at ingest, GC scheduling + +## Problem + +The adversarial review of the push admission path in PR #2907 (H2, SAM-hosted git, self-host only) left these findings open. Each needs a design change rather than a guard, so they were deferred with justification in the PR. The HIGH finding and the other MEDIUM and LOW items in that review were fixed in #2907. + +1. **GC needs to inflate every migrated pack object** (review M3). `runHostedGitGc` (`apps/api/src/selfhost/hosted-git/hosted-git-gc.ts`) moves each reachable pack object to loose storage through `store.get`, which inflates it under the GC alarm's single `repositories.maxInflatedBytes` budget (128 MiB). Two cases exceed that budget: + - highly compressible blobs (14 blobs of 15 MiB stored in about 0.4 MiB); + - more than 128 MiB of inflated pack content accumulated between collections. + + GC then fails on every attempt, garbage packs are never reclaimed, and the repository drifts towards `maxRepoBytes`, where every push is refused. The reviewer reproduced this at 268 MB of a 268.4 MB cap. Raising the budget only moves the bound, since a compression bomb can exceed any inflation or deadline cap. +2. **Delta depth is enforced on read but not at ingest** (review M4). `packstore.ts` resolves deltas eagerly at ingest without checking `maxDeltaDepth`, so a pack built with `--depth=250` is accepted. Cold reads then throw `delta chain exceeds depth`, and a shallow clone aborts with `early EOF` until GC rewrites the objects loose. The exception is thrown inside the upload response stream and is not caught. +3. **GC holds the input gate for the whole sweep** (review M5, the part not fixed in #2907). `gc()` runs under `blockConcurrencyWhile` for up to `workTimeoutMs` (120 s), blocking every other request to that repository, reads included. +4. **Lower-severity items** (review L7 to L10): + - **No rate limit.** There is no per-token or per-repository request rate limit, and a queued push is authorized before it waits on `receiveChain`. + - **Command lines dropped silently.** Unmatched command pkt-lines are skipped with no `ng`, and invalid UTF-8 ref bytes alias to U+FFFD. + - **Gzip buffering.** The gzip push path buffers about 3× `maxPushBytes`. + - **Quadratic copying.** `need()` concatenates repeatedly while reading the command section. + +## Context + +Found by the security-auditor adversarial pass on 2026-11-19 (task 01M7TY7Z3HBTSDSSV85FPRHE1B). The reproductions ran against the Durable Object in Miniflare/workerd. + +Who can trigger them: +- Every item needs a token with write access to the repository: a project member, or that project's agent workspace. +- The blast radius is that one repository. +- Item 1 is also reachable without malice, when several large pushes land between collections. +- An operator can recover by deleting and recreating the project's repository. + +## Acceptance Criteria + +- [ ] GC reclaims unreachable packs without inflating reachable objects (copy raw pack entries, or drop packs whose objects no ref reaches), and completes for a repository whose reachable content inflates past `maxInflatedBytes`. A real-git test proves it. +- [ ] GC work is deadline-bounded and resumable, with throughput stated at the 30,000-object / 256 MiB envelope (`.claude/rules/81-work-bounds-must-state-throughput.md`). +- [ ] Ingest records delta depth and refuses a pack whose chains exceed `maxDeltaDepth`. A real-git test pushes `--depth=250` and is refused, and a normal pack is accepted. +- [ ] Errors raised while streaming an upload-pack response end the stream cleanly. +- [ ] GC no longer blocks reads for the whole sweep; a test shows a clone proceeding while GC runs. +- [ ] Decide on and implement per-token push rate limiting, or record why not. +- [ ] Every malformed command line is answered with `ng` or a refusal, never dropped. From 8bc9a3af4ff96465152897e25aaa66372b1049cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:22:11 +0000 Subject: [PATCH 52/65] fix(selfhost): admit only objects git can read; bound old-history reads Independent re-verification of f9eb945ef (0 CRITICAL/HIGH): - F2: the lenient parsers admitted commits with author before tree, tags without object/type/tag in order, and tree entries with invalid modes or names. Git cannot clone those. The admission walk now checks each object's shape, so a malformed object rejects its own command. - F1 (part): with a valid reachable cache the walk stops at any cached object (one SQL lookup, no read); an ancestry check that exhausts the work budget counts as a forced update rather than failing the push. The dead peel-cache seeding is dropped. The cache-less heavy-history case is tracked in the hosted-git hardening backlog task. Also give the reverse-tunnel Worker import-graph walk the same CI timeout as the sibling graph test (it timed out at the 5 s default under load), via one shared GRAPH_WALK_TIMEOUT_MS. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/vendor/dgit/UPSTREAM.md | 2 +- apps/api/src/vendor/dgit/git/protocol.ts | 93 ++++++++-- .../tests/helpers/selfhost-only-modules.ts | 2 + .../hosted-git/hosted-git-conformance.test.ts | 37 ++++ .../hosted-git-push-admission.test.ts | 168 +++++++++++++++++- .../unit/selfhost/hosted-git-refname.test.ts | 69 +++++-- .../selfhost/reverse-tunnel-placement.test.ts | 17 +- .../selfhost/selfhost-only-modules.test.ts | 4 +- .../2026-11-19-selfhost-hosted-git-h2.md | 8 + ...1-19-hosted-git-gc-and-ingest-hardening.md | 10 +- 10 files changed, 372 insertions(+), 38 deletions(-) diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index c7e595e170..2c13b13155 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -39,4 +39,4 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. -- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads (header order, tag headers, tree modes and names); with a valid reachable cache the walk stops at cached objects; an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 9d19aac2c5..87dd47d9b5 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1,7 +1,7 @@ /* eslint-disable */ // @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) // FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) -import { concat, isOid, ZERO_OID, te } from "./util"; +import { concat, isOid, ZERO_OID, td, te } from "./util"; import { pkt, FLUSH, PktParser } from "./pktline"; import { GitStore } from "./store"; import { PackWriter } from "./pack"; @@ -1130,9 +1130,13 @@ async function reachableComplete( store: GitStore, tip: string, known: OidSet, - failed: OidSet + failed: OidSet, + cached: boolean ): Promise { - if (known.hasHex(tip)) return true; // tip already in a validated closure + // SAM: with a valid reachable cache, every cached object is reachable from a + // validated ref tip, so its closure is complete: one SQL lookup, no object read. + const validated = (oid: string) => known.hasHex(oid) || (cached && store.reachableHas(oid)); + if (validated(tip)) return true; // tip already in a validated closure if (failed.hasHex(tip)) return false; // an earlier command in this push proved it incomplete // Cursor BFS over the scratch set itself: newly reached oids append past the // cursor, so no separate hex-oid stack is needed to walk it. Parallel arrays @@ -1164,6 +1168,7 @@ async function reachableComplete( if (!obj) return fail(i); let children: ChildRef[]; try { + assertGitObjectShape(obj); children = childRefs(obj); } catch (err) { // SAM: a commit, tag or tree that does not parse cannot have a proven @@ -1172,7 +1177,7 @@ async function reachableComplete( throw err; } for (const child of children) { - if (known.hasHex(child.oid) || fresh.hasHex(child.oid)) { + if (validated(child.oid) || fresh.hasHex(child.oid)) { // Already validated or queued under another edge: this edge still has to name // an object of the type it requires (absent ones fail when their entry is walked). const type = store.typeAndSize(child.oid)?.type; @@ -1238,6 +1243,58 @@ function childOids(obj: { type: ObjType; data: Uint8Array }): string[] { return []; } +const TREE_MODES: ReadonlySet = new Set(["100644", "100755", "100664", "120000", "40000", "160000"]); + +/** Header keys of a commit or tag, in order (continuation lines belong to the previous key). */ +function headerKeys(data: Uint8Array): string[] { + const text = td.decode(data); + const end = text.indexOf("\n\n"); + const keys: string[] = []; + for (const line of (end === -1 ? text : text.slice(0, end)).split("\n")) { + if (line === "" || line.startsWith(" ")) continue; + keys.push(line.slice(0, line.indexOf(" ") === -1 ? line.length : line.indexOf(" "))); + } + return keys; +} + +/** + * SAM: refuse objects git itself cannot read, so a pushed object can never make the + * repository uncloneable. The parsers above are lenient (any header order, any mode + * text); git requires a commit to start with `tree` and its parents, a tag to start + * with `object`, `type`, `tag`, and tree entries with a known mode and a plain name. + */ +function assertGitObjectShape(obj: { type: ObjType; data: Uint8Array }): void { + if (obj.type === "commit") { + const keys = headerKeys(obj.data); + let i = 0; + if (keys[i++] !== "tree") throw new GitParseError("commit must start with a tree header"); + while (keys[i] === "parent") i++; + if (keys[i] !== "author" || keys[i + 1] !== "committer") { + throw new GitParseError("commit must have author then committer after its parents"); + } + for (const k of keys.slice(i + 2)) { + if (k === "tree" || k === "parent" || k === "author" || k === "committer") { + throw new GitParseError(`commit has a misplaced ${k} header`); + } + } + } else if (obj.type === "tag") { + const keys = headerKeys(obj.data); + if (keys[0] !== "object" || keys[1] !== "type" || keys[2] !== "tag") { + throw new GitParseError("tag must start with object, type and tag headers"); + } + if (!parseTag(obj.data).tag) throw new GitParseError("tag has an empty name"); + } else if (obj.type === "tree") { + const names = new Set(); + for (const e of parseTree(obj.data)) { + if (!TREE_MODES.has(e.mode)) throw new GitParseError("tree entry has an invalid mode"); + if (!e.name || e.name.includes("/") || names.has(e.name)) { + throw new GitParseError("tree entry has an invalid or duplicate name"); + } + names.add(e.name); + } + } +} + /** An object a parent references, with the type the reference requires. */ interface ChildRef { oid: string; @@ -1273,6 +1330,21 @@ function childRefs(obj: { type: ObjType; data: Uint8Array }): ChildRef[] { return []; } +/** + * SAM: the ancestry check only decides whether an update strands history (GC and + * cache invalidation). When a heavy history exhausts the push's work budget, treat + * the update as forced, the conservative answer, rather than failing the push. + */ +async function isAncestorOrForced(store: GitStore, old: string, next: string): Promise { + try { + return await isAncestor(store, old, next); + } catch (err) { + const msg = err instanceof Error ? err.message : ""; + if (msg.includes("exceeds decompression budget") || msg.includes("exceeds time budget")) return false; + throw err; + } +} + export async function validatePush( store: GitStore, commands: PushCommand[], @@ -1293,14 +1365,11 @@ export async function validatePush( // SAM: seeding reads no objects. Upstream peeled every ref tip here, which // inflated each tip under the push's decompression budget on every push, so // a handful of large tips made every later push, including the deletion - // that would remove them, exceed the budget. Only cached peel targets count. + // that would remove them, exceed the budget. A walk that reaches a tagged + // commit descends through it instead (or stops at the reachable cache). const known = new OidSet(4096); const existing = store.refs(); - for (const r of existing) { - known.addHex(r.target); - const peeled = store.getPeeled(r.target); - if (peeled) known.addHex(peeled); - } + for (const r of existing) known.addHex(r.target); const knownHead = store.resolveHead(); if (knownHead) known.addHex(knownHead); // oids proven to have an incomplete closure earlier in this push @@ -1366,12 +1435,12 @@ export async function validatePush( decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "trying to write non-commit object to branch" }); continue; } - const connected = await reachableComplete(store, cmd.next, known, failed); + const connected = await reachableComplete(store, cmd.next, known, failed, hadCache); if (!connected) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "missing necessary objects" }); continue; } - const forced = cmd.old !== ZERO_OID && !(await isAncestor(store, cmd.old, cmd.next)); + const forced = cmd.old !== ZERO_OID && !(await isAncestorOrForced(store, cmd.old, cmd.next)); decisions.push({ ref: cmd.ref, expectedOld: cmd.old, set: cmd.next, forced }); if (current === ZERO_OID) trackRef(cmd.ref, 1); } diff --git a/apps/api/tests/helpers/selfhost-only-modules.ts b/apps/api/tests/helpers/selfhost-only-modules.ts index 82a4dfc24b..5005d4e80b 100644 --- a/apps/api/tests/helpers/selfhost-only-modules.ts +++ b/apps/api/tests/helpers/selfhost-only-modules.ts @@ -18,6 +18,8 @@ import ts from 'typescript'; export const REPO_ROOT = resolve(import.meta.dirname, '../../../..'); export const API_SRC = resolve(REPO_ROOT, 'apps/api/src'); +/** Walking a >1,000-file import graph takes several seconds on a loaded CI runner. */ +export const GRAPH_WALK_TIMEOUT_MS = 60_000; /** Repository-relative path prefixes only the self-host build may contain. */ export const SELFHOST_ONLY_PATHS: readonly string[] = [ diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 04bd2d2026..3ee9297c34 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -1235,6 +1235,43 @@ describe('push connectivity admission (closure must be complete per command)', ( await assertCleanClone(remote); }); + it('refuses objects git cannot read (header order, tag headers, tree modes) and keeps clones working', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Object shapes'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('object-shapes'); + await gitOk(['init', '-q', '-b', 'main', work]); + const plain = await commitFile(work, 'plain.txt'); + const blob = (await gitOk(['rev-parse', `${plain.commit}:plain.txt`], work)).stdout.trim(); + const literal = (type: string, input: Buffer | string) => { + const out = spawnSync('git', ['hash-object', '-t', type, '--literally', '-w', '--stdin'], { cwd: work, env: gitEnv(), input }); + expect(out.status).toBe(0); + return out.stdout.toString().trim(); + }; + const sig = 'Test 0 +0000'; + const authorFirst = literal('commit', `author ${sig}\ntree ${plain.tree}\ncommitter ${sig}\n\nauthor first\n`); + const typeFirstTag = literal('tag', `type commit\nobject ${plain.commit}\ntag odd\ntagger ${sig}\n\nodd\n`); + const badModeTree = literal('tree', Buffer.concat([Buffer.from('8 f\0'), Buffer.from(blob, 'hex')])); + const badModeCommit = literal('commit', `tree ${badModeTree}\nauthor ${sig}\ncommitter ${sig}\n\nbad mode\n`); + const out = await receive( + project, + token, + [ + [ZERO, authorFirst, 'refs/heads/author-first'], + [ZERO, typeFirstTag, 'refs/tags/type-first'], + [ZERO, badModeCommit, 'refs/heads/bad-mode'], + [ZERO, plain.commit, 'refs/heads/plain'], + ], + packOf(work, [authorFirst, typeFirstTag, badModeTree, badModeCommit, plain.commit, plain.tree, blob]) + ); + expect(out).toContain('ng refs/heads/author-first missing necessary objects'); + expect(out).toContain('ng refs/tags/type-first missing necessary objects'); + expect(out).toContain('ng refs/heads/bad-mode missing necessary objects'); + expect(out).toContain('ok refs/heads/plain'); + const check = await assertCleanClone(remote); + expect(await rev(check, 'origin/plain')).toBe(plain.commit); + }); + it('treats deleting a missing ref as a no-op that queues no GC, and refuses D/F ref conflicts', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Ref no-ops'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 0e694b72e2..40e6d0baa3 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -47,7 +47,11 @@ class Repo { return this.put(label, 'commit', enc.encode(text)); } tag(label: string, object: string, type: string) { - return this.put(label, 'tag', enc.encode(`object ${object}\ntype ${type}\ntag ${label}\ntagger ${SIG}\n\n${label}\n`)); + return this.put( + label, + 'tag', + enc.encode(`object ${object}\ntype ${type}\ntag ${label}\ntagger ${SIG}\n\n${label}\n`) + ); } /** A complete one-file commit. */ simple(label: string, parents: string[] = []) { @@ -83,7 +87,11 @@ class Repo { async function decide(repo: Repo, commands: [old: string, next: string, ref: string][]) { return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => - validatePush(repo.store(), commands.map(([old, next, ref]) => ({ old, next, ref })), null) + validatePush( + repo.store(), + commands.map(([old, next, ref]) => ({ old, next, ref })), + null + ) ); } @@ -141,7 +149,9 @@ describe('push admission: edge types', () => { const plan = await decide(repo, [[ZERO, evil, 'refs/heads/evil']]); expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); const ok = repo.simple('child', [tip]); - expect((await decide(repo, [[ZERO, ok, 'refs/heads/child']])).decisions[0]).toMatchObject({ set: ok }); + expect((await decide(repo, [[ZERO, ok, 'refs/heads/child']])).decisions[0]).toMatchObject({ + set: ok, + }); }); it('refuses a tree entry whose mode disagrees with its object type', async () => { @@ -177,7 +187,9 @@ describe('push admission: edge types', () => { [ZERO, tree, 'refs/heads/tree'], [ZERO, tree, 'refs/tags/tree'], ]); - expect(plan.decisions[0]).toMatchObject({ reject: 'trying to write non-commit object to branch' }); + expect(plan.decisions[0]).toMatchObject({ + reject: 'trying to write non-commit object to branch', + }); expect(plan.decisions[1]).toMatchObject({ set: tree }); }); }); @@ -263,3 +275,151 @@ describe('armHostedGitGcAlarm', () => { } }); }); + +describe('push admission: object shapes git can read', () => { + const header = `author ${SIG}\ncommitter ${SIG}`; + it('refuses commits, tags and trees git cannot parse, with git-shaped controls accepted', async () => { + const repo = new Repo(); + const tree = repo.tree('shape-tree', [treeEntry('100644', 'f', repo.blob('shape-blob'))]); + const signed = repo.put( + 'signed', + 'commit', + enc.encode( + `tree ${tree}\n${header}\nencoding UTF-8\ngpgsig -----BEGIN PGP SIGNATURE-----\n line\n -----END PGP SIGNATURE-----\n\nsigned\n` + ) + ); + const authorFirst = repo.put( + 'author-first', + 'commit', + enc.encode(`${header.split('\n')[0]}\ntree ${tree}\n${header.split('\n')[1]}\n\nx\n`) + ); + const noCommitter = repo.put( + 'no-committer', + 'commit', + enc.encode(`tree ${tree}\nauthor ${SIG}\n\nx\n`) + ); + const lateParent = repo.put( + 'late-parent', + 'commit', + enc.encode(`tree ${tree}\n${header}\nparent ${signed}\n\nx\n`) + ); + const tagTypeFirst = repo.put( + 'type-first', + 'tag', + enc.encode(`type commit\nobject ${signed}\ntag t\ntagger ${SIG}\n\nx\n`) + ); + const tagNoName = repo.put( + 'no-name', + 'tag', + enc.encode(`object ${signed}\ntype commit\ntagger ${SIG}\n\nx\n`) + ); + const badMode = repo.commit( + 'bad-mode', + repo.tree('bad-mode-tree', [treeEntry('8', 'f', repo.blob('m'))]) + ); + const dupName = repo.commit( + 'dup-name', + repo.tree('dup-tree', [ + treeEntry('100644', 'f', repo.blob('d1')), + treeEntry('100644', 'f', repo.blob('d2')), + ]) + ); + const slashName = repo.commit( + 'slash', + repo.tree('slash-tree', [treeEntry('100644', 'a/b', repo.blob('s'))]) + ); + const plan = await decide(repo, [ + [ZERO, signed, 'refs/heads/signed'], + [ZERO, authorFirst, 'refs/heads/author-first'], + [ZERO, noCommitter, 'refs/heads/no-committer'], + [ZERO, lateParent, 'refs/heads/late-parent'], + [ZERO, tagTypeFirst, 'refs/tags/type-first'], + [ZERO, tagNoName, 'refs/tags/no-name'], + [ZERO, badMode, 'refs/heads/bad-mode'], + [ZERO, dupName, 'refs/heads/dup-name'], + [ZERO, slashName, 'refs/heads/slash'], + [ZERO, repo.tag('good-tag', signed, 'commit'), 'refs/tags/good'], + ]); + const outcome = plan.decisions.map((d) => (d.reject ? 'reject' : 'set')); + expect(outcome).toEqual([ + 'set', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'set', + ]); + }); +}); + +describe('push admission: bounded reads of old history', () => { + /** A history of `n` commits where only the newest is a ref tip. */ + function history(repo: Repo, n: number) { + const commits: string[] = []; + for (let i = 0; i < n; i++) + commits.push(repo.simple(`h-${i}`, commits.length ? [commits[commits.length - 1]!] : [])); + return commits; + } + + it('stops at the reachable cache when a push forks from an old commit', async () => { + for (const cached of [true, false]) { + const repo = new Repo(); + const commits = history(repo, 1201); + repo.refs.set('refs/heads/main', commits[commits.length - 1]!); + const reachable = new Set(repo.objects.keys()); + // Fork just below the tip, so proving the parent's closure spans the whole history. + const fork = repo.simple(`fork-${cached}`, [commits[commits.length - 2]!]); + const store = repo.store() as unknown as Record; + store.getMeta = (key: string) => (cached && key === 'reachable-version' ? 'v' : null); + store.reachableHas = (oid: string) => reachable.has(oid); + repo.reads = 0; + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: ZERO, next: fork, ref: 'refs/heads/fork' }], + null + ) + ); + expect(plan.decisions[0]).toMatchObject({ set: fork }); + // Cached: the fork commit and its tree. Without the cache (control): the walk proves + // the old history down to the root, since no ref tip covers it. + if (cached) expect(repo.reads).toBe(2); + else expect(repo.reads).toBeGreaterThan(1201); + } + }); + + it('treats an update as forced when the ancestry check exhausts the work budget', async () => { + const repo = new Repo(); + const old = repo.simple('old'); + const side = repo.simple('side'); + const next = repo.simple('next', [side]); + repo.refs.set('refs/heads/main', old); + repo.refs.set('refs/heads/side', side); + const store = repo.store() as unknown as Record; + const get = store.get as (oid: string) => Promise; + let failRead: string | null = side; + store.get = async (oid: string) => { + if (oid === failRead) throw new Error('git work exceeds decompression budget'); + return get(oid); + }; + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush(store as unknown as GitStore, [{ old, next, ref: 'refs/heads/main' }], null) + ); + expect(plan.decisions[0]).toMatchObject({ set: next, forced: true }); + // Any other failure still fails the push. + failRead = side; + store.get = async (oid: string) => { + if (oid === failRead) throw new Error('storage unavailable'); + return get(oid); + }; + await expect( + withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush(store as unknown as GitStore, [{ old, next, ref: 'refs/heads/main' }], null) + ) + ).rejects.toThrow('storage unavailable'); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts index 71c4f534ff..a9bd2811d2 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts @@ -10,29 +10,68 @@ import type { GitStore } from '../../../src/vendor/dgit/git/store'; // Audit every rule in https://git-scm.com/docs/git-check-ref-format. The real smart-HTTP // suite separately proves the parser/DO/write path with ordinary and nested branch controls. const invalid = [ - 'refs/heads/.hidden/x', 'refs/heads/x/.hidden', 'refs/heads/x.lock/y', 'refs/heads/x.lock', - 'HEAD', '@', 'refs/heads/x y', 'refs/heads/x..y', 'refs/heads/x~y', 'refs/heads/x^y', 'refs/heads/x:y', - 'refs/heads/x?y', 'refs/heads/x*y', 'refs/heads/x[y', '/refs/heads/x', 'refs/heads/x/', - 'refs/heads/x//y', 'refs/heads/x.', 'refs/heads/x@{y', 'refs/heads/x\\y', - ...Array.from({ length: 33 }, (_, i) => `refs/heads/x${String.fromCharCode(i === 32 ? 127 : i)}y`), + 'refs/heads/.hidden/x', + 'refs/heads/x/.hidden', + 'refs/heads/x.lock/y', + 'refs/heads/x.lock', + 'HEAD', + '@', + 'refs/heads/x y', + 'refs/heads/x..y', + 'refs/heads/x~y', + 'refs/heads/x^y', + 'refs/heads/x:y', + 'refs/heads/x?y', + 'refs/heads/x*y', + 'refs/heads/x[y', + '/refs/heads/x', + 'refs/heads/x/', + 'refs/heads/x//y', + 'refs/heads/x.', + 'refs/heads/x@{y', + 'refs/heads/x\\y', + ...Array.from( + { length: 33 }, + (_, i) => `refs/heads/x${String.fromCharCode(i === 32 ? 127 : i)}y` + ), +]; +const valid = [ + 'refs/heads/normal', + 'refs/heads/feature/x', + 'refs/tags/v1.0', + 'refs/heads/x.lockish/y', + 'refs/heads/a.b/c', + 'refs/heads/café', ]; -const valid = ['refs/heads/normal', 'refs/heads/feature/x', 'refs/tags/v1.0', 'refs/heads/x.lockish/y', 'refs/heads/a.b/c', 'refs/heads/café']; // The pushed tip is a commit with an empty tree, so valid names reach a `set` decision. const tip = 'a'.repeat(40); const tree = 'b'.repeat(40); const objects: Record = { - [tip]: { type: 'commit', data: new TextEncoder().encode(`tree ${tree}\n\nmsg\n`) }, + [tip]: { + type: 'commit', + data: new TextEncoder().encode( + `tree ${tree}\nauthor T 0 +0000\ncommitter T 0 +0000\n\nmsg\n` + ), + }, [tree]: { type: 'tree', data: new Uint8Array(0) }, }; const store = { - getMeta: () => null, reachableVersion: () => '0', refs: () => [], resolveHead: () => null, - getRef: () => null, getPeeled: () => null, + getMeta: () => null, + reachableVersion: () => '0', + refs: () => [], + resolveHead: () => null, + getRef: () => null, + getPeeled: () => null, typeAndSize: (oid: string) => (objects[oid] ? { type: objects[oid].type, size: 1 } : null), get: async (oid: string) => objects[oid] ?? null, } as unknown as GitStore; async function decision(ref: string) { return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, async () => { - const plan = await validatePush(store, [{ old: '0'.repeat(40), next: 'a'.repeat(40), ref }], null); + const plan = await validatePush( + store, + [{ old: '0'.repeat(40), next: 'a'.repeat(40), ref }], + null + ); return plan.decisions[0]; }); } @@ -46,7 +85,15 @@ describe('validatePush Git ref-format rules', () => { expect(spawnSync('git', ['check-ref-format', ref]).status).toBe(0); expect(await decision(ref)).toMatchObject({ ref, set: 'a'.repeat(40) }); }); - it.each(['refs/heads/xy', 'refs/heads/x&y', 'refs/heads/x`y', 'refs/heads/x"y', "refs/heads/x'y", `refs/heads/${'x'.repeat(256)}`])('keeps SAM conservative safety bound for %j', async (ref) => { + it.each([ + 'refs/heads/xy', + 'refs/heads/x&y', + 'refs/heads/x`y', + 'refs/heads/x"y', + "refs/heads/x'y", + `refs/heads/${'x'.repeat(256)}`, + ])('keeps SAM conservative safety bound for %j', async (ref) => { expect(await decision(ref)).toMatchObject({ reject: 'funny refname' }); }); }); diff --git a/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts b/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts index 797c0167f1..2d5aeee61f 100644 --- a/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts +++ b/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts @@ -17,17 +17,22 @@ import { REVERSE_TUNNEL_MIGRATIONS } from '../../../src/selfhost/reverse-tunnel- import { API_SRC, collectImportGraph, + GRAPH_WALK_TIMEOUT_MS, REPO_ROOT, selfhostOnlyFindings, } from '../../helpers/selfhost-only-modules'; describe('self-host-only placement', () => { - it('keeps reverse implementation out of the real Worker import graph', () => { - const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); - expect(graph.files.length).toBeGreaterThan(100); - expect(graph.files).toContain('apps/api/src/services/node-provisioning-ingress.ts'); - expect(selfhostOnlyFindings(graph)).toEqual([]); - }); + it( + 'keeps reverse implementation out of the real Worker import graph', + () => { + const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); + expect(graph.files.length).toBeGreaterThan(100); + expect(graph.files).toContain('apps/api/src/services/node-provisioning-ingress.ts'); + expect(selfhostOnlyFindings(graph)).toEqual([]); + }, + GRAPH_WALK_TIMEOUT_MS + ); it('follows forbidden imports from a neutral entry and recognizes package imports', () => { const scratchRoot = join(REPO_ROOT, '.tmp'); mkdirSync(scratchRoot, { recursive: true }); diff --git a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts index 07b521d8ba..d2fe9979bb 100644 --- a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts @@ -23,6 +23,7 @@ import { API_SRC, CLOUDFLARE_ENTRY_FORBIDDEN_PATHS, collectImportGraph, + GRAPH_WALK_TIMEOUT_MS, REPO_ROOT, selfhostOnlyFindings, } from '../../helpers/selfhost-only-modules'; @@ -38,9 +39,6 @@ function celldEntryImports(): string[] { .map((specifier) => resolve(API_SRC, specifier.slice(prefix.length))); } -/** Walking a >1,000-file import graph takes several seconds on a loaded CI runner. */ -const GRAPH_WALK_TIMEOUT_MS = 60_000; - describe('self-host-only code stays out of the Cloudflare Worker', () => { it('detects real imports of the hosted DO, vendored git and pako', () => { const scratchRoot = resolve(REPO_ROOT, '.tmp'); diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 48c0d7a554..a604394a25 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -96,3 +96,11 @@ Previous owner 01M7SR1B79 stopped after repeated provider content-filter refusal - Request-body helpers moved to `hosted-git-body.ts` so `hosted-git-repo.ts` stays under 500 lines; GC queueing is one helper (`queueHostedGitGc`, `armHostedGitGcAlarm`). - [ ] Fresh CI green, 0 open threads, Codex re-requested on final head - [ ] Final BOX smoke on the exact final head over main (closes the L22c "box from main runs an agent session" criterion deferred to H2 by Raphaël) + +## Independent re-verification of f9eb945ef (23:20 UTC) + +A fresh security-auditor re-verified f9eb945ef. It found 0 CRITICAL and 0 HIGH. Its 400-seed differential fuzz confirmed the failure memo, the parse-failure handling, GC-on-throw, the no-op delete, the alarm and the D/F checks. Mutating the blame-parent logic to blame the child made 74 fuzz cases red. + +MEDIUM-F2 was fixed: lenient parsers let a writer push a commit with `author` before `tree`, tags missing or reordering `object`/`type`/`tag`, or tree modes like `8`, and git then cannot clone. `assertGitObjectShape` now runs in the walk, so a malformed object rejects its own command. A real-git test reproduces each shape; a signed commit with continuation lines and extra headers stays accepted. + +MEDIUM-F1 was partly fixed: with a valid reachable cache the walk stops at cached objects (SQL lookup, no read), and an ancestry check that exhausts the work budget counts as a forced update rather than failing the push. The dead `getPeeled` seeding was dropped. The cache-less heavy-history case and F4 (alarm error handling) were deferred to the backlog task. Discrimination was checked again: removing the shape check, the cache stop or the budget tolerance each turned its intended tests red. diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md index 68881719ce..a063bb4095 100644 --- a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -11,7 +11,14 @@ The adversarial review of the push admission path in PR #2907 (H2, SAM-hosted gi GC then fails on every attempt, garbage packs are never reclaimed, and the repository drifts towards `maxRepoBytes`, where every push is refused. The reviewer reproduced this at 268 MB of a 268.4 MB cap. Raising the budget only moves the bound, since a compression bomb can exceed any inflation or deadline cap. 2. **Delta depth is enforced on read but not at ingest** (review M4). `packstore.ts` resolves deltas eagerly at ingest without checking `maxDeltaDepth`, so a pack built with `--depth=250` is accepted. Cold reads then throw `delta chain exceeds depth`, and a shallow clone aborts with `early EOF` until GC rewrites the objects loose. The exception is thrown inside the upload response stream and is not caught. 3. **GC holds the input gate for the whole sweep** (review M5, the part not fixed in #2907). `gc()` runs under `blockConcurrencyWhile` for up to `workTimeoutMs` (120 s), blocking every other request to that repository, reads included. -4. **Lower-severity items** (review L7 to L10): +4. **Pushes over heavy history without a reachable cache** (re-verification F1, the part not fixed in #2907). + - With a valid reachable cache, a push stops at any cached object. Without one, the case after any deletion or force push until the next full clone, a push whose parent is not a ref tip proves that parent's closure by walking old commits and trees under the 128 MiB budget. + - A repository whose old trees inflate past the budget then cannot accept a fork-from-old-commit push. A full clone faces the same envelope. + - An ancestry check that runs out of budget is already treated as a forced update rather than failing the push. + - Fix: keep a persistent set of validated objects that only GC prunes. GC already computes the reachable set, and every accepted push adds its proven closure. Or record commit parents at ingest. + - Also: `store.setPeeled` is never called, so `getPeeled` and the `peeled` table are dead upstream code. Remove them or populate them. +5. **Alarm error handling** (re-verification F4): `armHostedGitGcAlarm` in the failed-ingest path propagates a `getAlarm`/`setAlarm` error as a 500, which is deliberate so the earlier tests keep the cleanup-before-alarm ordering. `queueHostedGitGc` swallows alarm errors, so `gc-pending=1` can wait for the next push. +6. **Lower-severity items** (review L7 to L10): - **No rate limit.** There is no per-token or per-repository request rate limit, and a queued push is authorized before it waits on `receiveChain`. - **Command lines dropped silently.** Unmatched command pkt-lines are skipped with no `ng`, and invalid UTF-8 ref bytes alias to U+FFFD. - **Gzip buffering.** The gzip push path buffers about 3× `maxPushBytes`. @@ -36,3 +43,4 @@ Who can trigger them: - [ ] GC no longer blocks reads for the whole sweep; a test shows a clone proceeding while GC runs. - [ ] Decide on and implement per-token push rate limiting, or record why not. - [ ] Every malformed command line is answered with `ng` or a refusal, never dropped. +- [ ] A push forking from an old, heavy, uncached commit succeeds within the budget. A real-git test proves it, with no reachable cache present. From 77e55dbbff8fbb19674cb865dc7da8acdc59c9c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:36:44 +0000 Subject: [PATCH 53/65] fix(selfhost): never trust the reachable cache for admission; byte-exact shape check Narrow verification of 8bc9a3af4 found a HIGH regression: the walk's reachable-cache stop let a push name an object GC had deleted, after a clone raced a deleting push and stamped a stale reachable set as current. - Remove the cache stop: admission never consults the reachable cache. - saveReachable stamps only the ref version its clone walk started from. - GC invalidates the reachable cache whenever it deletes objects. - The object shape check runs on raw bytes: lossy UTF-8 decoding hid BOM-prefixed commits and tags (clone-breaking) and merged distinct non-UTF-8 tree names. Header sections must be newline-terminated; NUL, ".", ".." and ".git" names are refused; every 100xxx file mode is accepted. Co-Authored-By: Claude Opus 5.5 --- .../src/selfhost/hosted-git/hosted-git-gc.ts | 2 + apps/api/src/vendor/dgit/UPSTREAM.md | 4 +- apps/api/src/vendor/dgit/git/protocol.ts | 129 ++++++++---- apps/api/src/vendor/dgit/git/store.ts | 8 +- .../hosted-git-push-admission.test.ts | 195 +++++++++++++++--- .../2026-11-19-selfhost-hosted-git-h2.md | 11 + ...1-19-hosted-git-gc-and-ingest-hardening.md | 5 +- 7 files changed, 271 insertions(+), 83 deletions(-) diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts index aca46902f5..25d92e0b8d 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts @@ -105,6 +105,8 @@ export async function runHostedGitGc(store: GitStore): Promise 0) store.invalidateReachable(); return noHeadroom ? { removed, kept: reachable.size, skipped: true } : { removed, kept: reachable.size }; diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 2c13b13155..03c64e4821 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -39,4 +39,6 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. -- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads (header order, tag headers, tree modes and names); with a valid reachable cache the walk stops at cached objects; an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (header order, newline-terminated headers, tag headers, tree modes and unique names other than `.`, `..` and `.git`); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. + +- The reachable cache is stamped only with the ref version its clone walk started from, so a push that lands during the walk cannot leave a stale set marked current, and GC invalidates the cache whenever it deletes objects. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 87dd47d9b5..aeb655649e 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1,7 +1,7 @@ /* eslint-disable */ // @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) // FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) -import { concat, isOid, ZERO_OID, td, te } from "./util"; +import { concat, isOid, ZERO_OID, te } from "./util"; import { pkt, FLUSH, PktParser } from "./pktline"; import { GitStore } from "./store"; import { PackWriter } from "./pack"; @@ -666,6 +666,7 @@ export async function uploadPack( let send = fullClone ? store.loadReachable() : null; if (!send) { + const walkVersion = store.reachableVersion(); const excluded = await excludedObjects(store, req.haves, req.clientShallows, req.wants); // a plain clone enumerates the whole database: size the walk's set up front // so it never doubles (a doubling keeps the old and new arrays live at once) @@ -681,7 +682,7 @@ export async function uploadPack( ); if (fullClone) { try { - await store.saveReachable(send); + await store.saveReachable(send, walkVersion); } catch { // the cache is best-effort: a failed persist just means the next full // clone walks again, never a wrong pack @@ -1130,13 +1131,9 @@ async function reachableComplete( store: GitStore, tip: string, known: OidSet, - failed: OidSet, - cached: boolean + failed: OidSet ): Promise { - // SAM: with a valid reachable cache, every cached object is reachable from a - // validated ref tip, so its closure is complete: one SQL lookup, no object read. - const validated = (oid: string) => known.hasHex(oid) || (cached && store.reachableHas(oid)); - if (validated(tip)) return true; // tip already in a validated closure + if (known.hasHex(tip)) return true; // tip already in a validated closure if (failed.hasHex(tip)) return false; // an earlier command in this push proved it incomplete // Cursor BFS over the scratch set itself: newly reached oids append past the // cursor, so no separate hex-oid stack is needed to walk it. Parallel arrays @@ -1177,7 +1174,7 @@ async function reachableComplete( throw err; } for (const child of children) { - if (validated(child.oid) || fresh.hasHex(child.oid)) { + if (known.hasHex(child.oid) || fresh.hasHex(child.oid)) { // Already validated or queued under another edge: this edge still has to name // an object of the type it requires (absent ones fail when their entry is walked). const type = store.typeAndSize(child.oid)?.type; @@ -1243,54 +1240,98 @@ function childOids(obj: { type: ObjType; data: Uint8Array }): string[] { return []; } -const TREE_MODES: ReadonlySet = new Set(["100644", "100755", "100664", "120000", "40000", "160000"]); +/** Git's file modes (any 100xxx permission set), plus symlink, tree and gitlink. */ +const TREE_MODE = /^(100[0-7]{3}|120000|40000|160000)$/; -/** Header keys of a commit or tag, in order (continuation lines belong to the previous key). */ -function headerKeys(data: Uint8Array): string[] { - const text = td.decode(data); - const end = text.indexOf("\n\n"); - const keys: string[] = []; - for (const line of (end === -1 ? text : text.slice(0, end)).split("\n")) { - if (line === "" || line.startsWith(" ")) continue; - keys.push(line.slice(0, line.indexOf(" ") === -1 ? line.length : line.indexOf(" "))); +/** Bytes as a one-char-per-byte string: lossless, unlike a UTF-8 decode (BOMs, invalid bytes). */ +function byteString(data: Uint8Array, start: number, end: number): string { + let out = ""; + for (let i = start; i < end; i += 8192) { + out += String.fromCharCode(...data.subarray(i, Math.min(end, i + 8192))); } - return keys; + return out; +} + +/** + * Header lines of a commit or tag, as raw byte strings, or null when the header + * section is not newline-terminated (git cannot parse a tag whose last header + * lacks its newline). The section ends at the first blank line or at the end. + */ +function rawHeaderLines(data: Uint8Array): string[] | null { + let stop = data.length; + for (let i = 0; i + 1 < data.length; i++) { + if (data[i] === 10 && data[i + 1] === 10) { + stop = i + 1; + break; + } + } + if (stop === 0 || data[stop - 1] !== 10) return null; + const lines: string[] = []; + for (let i = 0, start = 0; i < stop; i++) { + if (data[i] === 10) { + lines.push(byteString(data, start, i)); + start = i + 1; + } + } + return lines; +} + +function headerKeyList(lines: string[]): string[] { + return lines.filter((l) => !l.startsWith(" ")).map((l) => (l.includes(" ") ? l.slice(0, l.indexOf(" ")) : l)); +} + +function isDotGitName(name: string): boolean { + return name.toLowerCase().replace(/[ .]+$/, "") === ".git"; } /** * SAM: refuse objects git itself cannot read, so a pushed object can never make the - * repository uncloneable. The parsers above are lenient (any header order, any mode - * text); git requires a commit to start with `tree` and its parents, a tag to start - * with `object`, `type`, `tag`, and tree entries with a known mode and a plain name. + * repository uncloneable. The parsers above are lenient (any header order, lossy + * UTF-8 decoding); git requires a commit to start with `tree` and its parents, a tag + * to start with `object`, `type`, `tag`, newline-terminated headers, and tree entries + * with a known mode and a plain, unique name. Checked on raw bytes, so a BOM or an + * invalid UTF-8 byte is neither hidden nor mistaken for another name. */ function assertGitObjectShape(obj: { type: ObjType; data: Uint8Array }): void { - if (obj.type === "commit") { - const keys = headerKeys(obj.data); - let i = 0; - if (keys[i++] !== "tree") throw new GitParseError("commit must start with a tree header"); - while (keys[i] === "parent") i++; - if (keys[i] !== "author" || keys[i + 1] !== "committer") { - throw new GitParseError("commit must have author then committer after its parents"); - } - for (const k of keys.slice(i + 2)) { - if (k === "tree" || k === "parent" || k === "author" || k === "committer") { - throw new GitParseError(`commit has a misplaced ${k} header`); + if (obj.type === "commit" || obj.type === "tag") { + const lines = rawHeaderLines(obj.data); + if (!lines) throw new GitParseError(`${obj.type} headers are not newline-terminated`); + if (lines.some((l) => l.includes("\0"))) throw new GitParseError(`${obj.type} header contains NUL`); + const keys = headerKeyList(lines); + if (obj.type === "commit") { + let i = 0; + if (keys[i++] !== "tree") throw new GitParseError("commit must start with a tree header"); + while (keys[i] === "parent") i++; + if (keys[i] !== "author" || keys[i + 1] !== "committer") { + throw new GitParseError("commit must have author then committer after its parents"); } + for (const k of keys.slice(i + 2)) { + if (k === "tree" || k === "parent" || k === "author" || k === "committer") { + throw new GitParseError(`commit has a misplaced ${k} header`); + } + } + } else { + if (keys[0] !== "object" || keys[1] !== "type" || keys[2] !== "tag") { + throw new GitParseError("tag must start with object, type and tag headers"); + } + const name = lines.filter((l) => !l.startsWith(" "))[2]!.slice(4); + if (!name) throw new GitParseError("tag has an empty name"); } - } else if (obj.type === "tag") { - const keys = headerKeys(obj.data); - if (keys[0] !== "object" || keys[1] !== "type" || keys[2] !== "tag") { - throw new GitParseError("tag must start with object, type and tag headers"); - } - if (!parseTag(obj.data).tag) throw new GitParseError("tag has an empty name"); } else if (obj.type === "tree") { + const data = obj.data; const names = new Set(); - for (const e of parseTree(obj.data)) { - if (!TREE_MODES.has(e.mode)) throw new GitParseError("tree entry has an invalid mode"); - if (!e.name || e.name.includes("/") || names.has(e.name)) { + for (let pos = 0; pos < data.length; ) { + const sp = data.indexOf(32, pos); + const nul = sp === -1 ? -1 : data.indexOf(0, sp + 1); + if (sp === -1 || nul === -1 || nul + 21 > data.length) throw new GitParseError("malformed tree"); + const mode = byteString(data, pos, sp); + const name = byteString(data, sp + 1, nul); + pos = nul + 21; + if (!TREE_MODE.test(mode)) throw new GitParseError("tree entry has an invalid mode"); + if (!name || name.includes("/") || name === "." || name === ".." || isDotGitName(name) || names.has(name)) { throw new GitParseError("tree entry has an invalid or duplicate name"); } - names.add(e.name); + names.add(name); } } } @@ -1435,7 +1476,7 @@ export async function validatePush( decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "trying to write non-commit object to branch" }); continue; } - const connected = await reachableComplete(store, cmd.next, known, failed, hadCache); + const connected = await reachableComplete(store, cmd.next, known, failed); if (!connected) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "missing necessary objects" }); continue; diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index 5302b7780f..39a61cb60d 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -327,8 +327,12 @@ export class GitStore { * landing during a cold clone) the version guard abandons the stamp, leaving * the half-written table unversioned and thus ignored until it is rebuilt. */ - async saveReachable(set: OidSet): Promise { - const version = this.reachableVersion(); + async saveReachable(set: OidSet, version: string = this.reachableVersion()): Promise { + // SAM: `version` is the ref version the walk that built `set` started from. + // A push that moved refs during that walk (the walk yields) makes `set` + // describe old refs; stamping it with the new version would let a stranded, + // later-collected object pass for reachable. + if (this.reachableVersion() !== version) return; this.sql.exec("DELETE FROM reachable"); const n = set.markedSize; for (let i = 0; i < n; i++) { diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 40e6d0baa3..27e8e5dc01 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -278,6 +278,85 @@ describe('armHostedGitGcAlarm', () => { describe('push admission: object shapes git can read', () => { const header = `author ${SIG}\ncommitter ${SIG}`; + it('refuses byte-level shapes git cannot read, and accepts names that are not UTF-8', async () => { + const repo = new Repo(); + const blob = repo.blob('bytes-blob'); + const tree = repo.tree('bytes-tree', [treeEntry('100644', 'f', blob)]); + const bom = [0xef, 0xbb, 0xbf]; + const raw = (label: string, type: Kind, bytes: number[]) => + repo.put(label, type, new Uint8Array(bytes)); + const sigLines = `author ${SIG}\ncommitter ${SIG}\n`; + const bomCommit = raw('bom-commit', 'commit', [ + ...bom, + ...enc.encode(`tree ${tree}\n${sigLines}\nx\n`), + ]); + const good = repo.commit('good', tree); + const bomTag = raw('bom-tag', 'tag', [ + ...bom, + ...enc.encode(`object ${good}\ntype commit\ntag t\n\nx\n`), + ]); + const openTag = raw('open-tag', 'tag', [...enc.encode(`object ${good}\ntype commit\ntag v1`)]); + // The header section must end in a newline even when its last line is optional. + const openTagger = raw('open-tagger', 'tag', [ + ...enc.encode(`object ${good}\ntype commit\ntag v2\ntagger ${SIG}`), + ]); + const nulHeader = raw('nul', 'commit', [ + ...enc.encode(`tree ${tree}\nauthor T`), + 0, + ...enc.encode(` ${SIG}\ncommitter ${SIG}\n\nx\n`), + ]); + const entry = (mode: string, name: number[], oid: string) => [ + ...enc.encode(`${mode} `), + ...name, + 0, + ...Buffer.from(oid, 'hex'), + ]; + const latin = repo.commit( + 'latin', + repo.tree('latin-tree', [entry('100644', [0xe8], blob), entry('100644', [0xe9], blob)]) + ); + const bomName = repo.commit( + 'bom-name', + repo.tree('bom-name-tree', [entry('100644', bom, blob)]) + ); + const oddMode = repo.commit( + 'odd-mode', + repo.tree('odd-mode-tree', [entry('100600', [0x66], blob)]) + ); + const dotGit = repo.commit( + 'dot-git', + repo.tree('dot-git-tree', [entry('100644', [...enc.encode('.GIT ')], blob)]) + ); + const dotDot = repo.commit( + 'dot-dot', + repo.tree('dot-dot-tree', [entry('40000', [...enc.encode('..')], tree)]) + ); + const plan = await decide(repo, [ + [ZERO, bomCommit, 'refs/heads/bom'], + [ZERO, bomTag, 'refs/tags/bom'], + [ZERO, openTag, 'refs/tags/open'], + [ZERO, openTagger, 'refs/tags/open-tagger'], + [ZERO, nulHeader, 'refs/heads/nul'], + [ZERO, dotGit, 'refs/heads/dot-git'], + [ZERO, dotDot, 'refs/heads/dot-dot'], + [ZERO, latin, 'refs/heads/latin'], + [ZERO, bomName, 'refs/heads/bom-name'], + [ZERO, oddMode, 'refs/heads/odd-mode'], + ]); + expect(plan.decisions.map((d) => (d.reject ? 'reject' : 'set'))).toEqual([ + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'set', + 'set', + 'set', + ]); + }); + it('refuses commits, tags and trees git cannot parse, with git-shaped controls accepted', async () => { const repo = new Repo(); const tree = repo.tree('shape-tree', [treeEntry('100644', 'f', repo.blob('shape-blob'))]); @@ -356,40 +435,35 @@ describe('push admission: object shapes git can read', () => { }); }); -describe('push admission: bounded reads of old history', () => { - /** A history of `n` commits where only the newest is a ref tip. */ - function history(repo: Repo, n: number) { - const commits: string[] = []; - for (let i = 0; i < n; i++) - commits.push(repo.simple(`h-${i}`, commits.length ? [commits[commits.length - 1]!] : [])); - return commits; - } - - it('stops at the reachable cache when a push forks from an old commit', async () => { - for (const cached of [true, false]) { - const repo = new Repo(); - const commits = history(repo, 1201); - repo.refs.set('refs/heads/main', commits[commits.length - 1]!); - const reachable = new Set(repo.objects.keys()); - // Fork just below the tip, so proving the parent's closure spans the whole history. - const fork = repo.simple(`fork-${cached}`, [commits[commits.length - 2]!]); - const store = repo.store() as unknown as Record; - store.getMeta = (key: string) => (cached && key === 'reachable-version' ? 'v' : null); - store.reachableHas = (oid: string) => reachable.has(oid); - repo.reads = 0; - const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => - validatePush( - store as unknown as GitStore, - [{ old: ZERO, next: fork, ref: 'refs/heads/fork' }], - null - ) - ); - expect(plan.decisions[0]).toMatchObject({ set: fork }); - // Cached: the fork commit and its tree. Without the cache (control): the walk proves - // the old history down to the root, since no ref tip covers it. - if (cached) expect(repo.reads).toBe(2); - else expect(repo.reads).toBeGreaterThan(1201); - } +describe('push admission: old history and the reachable cache', () => { + it('never trusts the reachable cache for a push: a cached but absent parent is refused', async () => { + // A clone racing a stranding push could once stamp a stale reachable set as current, + // and GC then deleted an object the cache still listed. Admission must not consult it. + const repo = new Repo(); + const base = repo.simple('base'); + repo.refs.set('refs/heads/main', base); + const gone = oidOf('collected-commit'); + const child = repo.simple('child-of-gone', [gone]); + const store = repo.store() as unknown as Record; + store.getMeta = (key: string) => (key === 'reachable-version' ? 'v' : null); + store.reachableHas = (oid: string) => oid === gone || repo.objects.has(oid); + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: ZERO, next: child, ref: 'refs/heads/child' }], + null + ) + ); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + const ok = repo.simple('child-of-base', [base]); + const control = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: ZERO, next: ok, ref: 'refs/heads/ok' }], + null + ) + ); + expect(control.decisions[0]).toMatchObject({ set: ok }); }); it('treats an update as forced when the ancestry check exhausts the work budget', async () => { @@ -423,3 +497,56 @@ describe('push admission: bounded reads of old history', () => { ).rejects.toThrow('storage unavailable'); }); }); + +describe('reachable cache stamping and GC', () => { + it('stamps a clone-built reachable set only if refs did not move during the walk', async () => { + const { GitStore } = await import('../../../src/vendor/dgit/git/store'); + const { OidSet } = await import('../../../src/vendor/dgit/git/oidset'); + const set = new OidSet(16); + set.markHex(oidOf('reachable-1')); + const fakeThis = (current: string) => ({ + reachableVersion: () => current, + sql: { exec: vi.fn() }, + setMeta: vi.fn(), + }); + const moved = fakeThis('after-push'); + await GitStore.prototype.saveReachable.call(moved as unknown as GitStore, set, 'before-push'); + expect(moved.setMeta).not.toHaveBeenCalled(); + expect(moved.sql.exec).not.toHaveBeenCalled(); + const steady = fakeThis('same'); + await GitStore.prototype.saveReachable.call(steady as unknown as GitStore, set, 'same'); + expect(steady.setMeta).toHaveBeenCalledWith('reachable-version', 'same'); + }); + + it('invalidates the reachable cache when GC deletes objects, and only then', async () => { + const { runHostedGitGc } = await import('../../../src/selfhost/hosted-git/hosted-git-gc'); + const gcStore = (loose: string[]) => { + const invalidateReachable = vi.fn(); + const store = { + objectCount: () => loose.length, + refs: () => [], + resolveHead: () => null, + typeAndSize: () => null, + get: async () => null, + packs: { + baseOids: () => [], + countObjects: () => 0, + totalPackBytes: () => 0, + lookup: () => null, + reset: () => undefined, + }, + dbSize: () => 0, + allOids: () => loose, + deleteObject: vi.fn(), + invalidateReachable, + } as unknown as GitStore; + return { store, invalidateReachable }; + }; + const withGarbage = gcStore([oidOf('garbage')]); + expect((await runHostedGitGc(withGarbage.store)).removed).toBe(1); + expect(withGarbage.invalidateReachable).toHaveBeenCalledOnce(); + const clean = gcStore([]); + expect((await runHostedGitGc(clean.store)).removed).toBe(0); + expect(clean.invalidateReachable).not.toHaveBeenCalled(); + }); +}); diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index a604394a25..869b5e9c99 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -104,3 +104,14 @@ A fresh security-auditor re-verified f9eb945ef. It found 0 CRITICAL and 0 HIGH. MEDIUM-F2 was fixed: lenient parsers let a writer push a commit with `author` before `tree`, tags missing or reordering `object`/`type`/`tag`, or tree modes like `8`, and git then cannot clone. `assertGitObjectShape` now runs in the walk, so a malformed object rejects its own command. A real-git test reproduces each shape; a signed commit with continuation lines and extra headers stays accepted. MEDIUM-F1 was partly fixed: with a valid reachable cache the walk stops at cached objects (SQL lookup, no read), and an ancestry check that exhausts the work budget counts as a forced update rather than failing the push. The dead `getPeeled` seeding was dropped. The cache-less heavy-history case and F4 (alarm error handling) were deferred to the backlog task. Discrimination was checked again: removing the shape check, the cache stop or the budget tolerance each turned its intended tests red. + +## Narrow verification of 8bc9a3af4 (23:45 UTC) + +The narrow verification found a HIGH regression introduced by the cache stop in 8bc9a3af4. A clone that raced a deleting push could stamp a stale reachable set as current (`saveReachable` captured its version after the walk). After GC deleted a stranded object, the cache stop admitted a push naming it, and clones failed. The same race on f9eb945ef rejected the push. Fixes: +- The cache stop is removed: admission never trusts the reachable cache. +- `saveReachable` stamps only the version its clone walk started from. +- GC invalidates the cache whenever it deletes objects. + +The shape check moved to raw bytes. Lossy UTF-8 decoding hid BOM-prefixed commits and tags (clone-breaking) and falsely merged distinct non-UTF-8 names. Header sections must be newline-terminated, header NUL is refused, `.`, `..` and `.git` variants are refused, and every `100xxx` file mode is accepted. The budget-tolerant ancestry check was confirmed sound (verdict D: PASS). + +Unit tests cover each fix: an absent cached parent is refused, with a control; the stamp guard; GC invalidation, with a control; BOM, unterminated, NUL, `.git` and `..` cases, plus accepted Latin-1, BOM-only and `100600` names. Each fix was mutated once and its test went red. diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md index a063bb4095..801a2948df 100644 --- a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -12,7 +12,7 @@ The adversarial review of the push admission path in PR #2907 (H2, SAM-hosted gi 2. **Delta depth is enforced on read but not at ingest** (review M4). `packstore.ts` resolves deltas eagerly at ingest without checking `maxDeltaDepth`, so a pack built with `--depth=250` is accepted. Cold reads then throw `delta chain exceeds depth`, and a shallow clone aborts with `early EOF` until GC rewrites the objects loose. The exception is thrown inside the upload response stream and is not caught. 3. **GC holds the input gate for the whole sweep** (review M5, the part not fixed in #2907). `gc()` runs under `blockConcurrencyWhile` for up to `workTimeoutMs` (120 s), blocking every other request to that repository, reads included. 4. **Pushes over heavy history without a reachable cache** (re-verification F1, the part not fixed in #2907). - - With a valid reachable cache, a push stops at any cached object. Without one, the case after any deletion or force push until the next full clone, a push whose parent is not a ref tip proves that parent's closure by walking old commits and trees under the 128 MiB budget. + - A push whose parent is not a ref tip proves that parent's closure by walking old commits and trees under the 128 MiB budget. Admission deliberately does not trust the reachable cache: a version of #2907 that did was shown to admit a parent GC had deleted, after a clone raced a deleting push (stamp race now fixed in `saveReachable`). - A repository whose old trees inflate past the budget then cannot accept a fork-from-old-commit push. A full clone faces the same envelope. - An ancestry check that runs out of budget is already treated as a forced update rather than failing the push. - Fix: keep a persistent set of validated objects that only GC prunes. GC already computes the reachable set, and every accepted push adds its proven closure. Or record commit parents at ingest. @@ -43,4 +43,5 @@ Who can trigger them: - [ ] GC no longer blocks reads for the whole sweep; a test shows a clone proceeding while GC runs. - [ ] Decide on and implement per-token push rate limiting, or record why not. - [ ] Every malformed command line is answered with `ng` or a refusal, never dropped. -- [ ] A push forking from an old, heavy, uncached commit succeeds within the budget. A real-git test proves it, with no reachable cache present. +- [ ] A push forking from an old, heavy commit succeeds within the budget. A real-git test proves it, and a stale or poisoned cache cannot vouch for a missing object. +- [ ] Optionally reject the remaining fsck error-level shapes that default clients tolerate but `transfer.fsckObjects=true` clients refuse: unsorted trees, malformed idents, CR in headers. From dc8e9e4ccd30c88f89e9da0fff2858b09c05794c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 23:56:35 +0000 Subject: [PATCH 54/65] fix(selfhost): pin the first header line; unstamp the cache before rewriting Final re-verification of 77e55dbb: the clone/push cache race is closed (reproduced on 8bc9a3af4, never on 77e55dbb). New findings fixed: - HIGH: a continuation line before `tree`/`object` was skipped by the header key list, yet git rejects such an object and clones fail. The first line must be exactly `tree ` or `object `. - MEDIUM: a second cold clone rewriting an already stamped reachable cache left it partial while yielding; a push in that window could stamp the partial set valid. saveReachable unstamps before rewriting. - LOW: refuse `git~1`, `.git:` streams, a `.gitmodules` symlink and tree entry names over 255 bytes, which break checkout of the default branch. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/vendor/dgit/UPSTREAM.md | 4 +- apps/api/src/vendor/dgit/git/protocol.ts | 27 ++++++++++- apps/api/src/vendor/dgit/git/store.ts | 4 ++ .../hosted-git/hosted-git-conformance.test.ts | 5 +- .../hosted-git-push-admission.test.ts | 48 ++++++++++++++++++- .../2026-11-19-selfhost-hosted-git-h2.md | 11 +++++ ...1-19-hosted-git-gc-and-ingest-hardening.md | 2 + 7 files changed, 95 insertions(+), 6 deletions(-) diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 03c64e4821..4ebdd0aadb 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -39,6 +39,6 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. -- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (header order, newline-terminated headers, tag headers, tree modes and unique names other than `.`, `..` and `.git`); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. -- The reachable cache is stamped only with the ref version its clone walk started from, so a push that lands during the walk cannot leave a stale set marked current, and GC invalidates the cache whenever it deletes objects. +- The reachable cache is stamped only with the ref version its clone walk started from, and unstamps the cache before rewriting it, so neither a push during the walk nor a second clone's rewrite can leave a stale or partial set marked current; GC invalidates the cache whenever it deletes objects. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index aeb655649e..9d09b39f88 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1280,10 +1280,16 @@ function headerKeyList(lines: string[]): string[] { return lines.filter((l) => !l.startsWith(" ")).map((l) => (l.includes(" ") ? l.slice(0, l.indexOf(" ")) : l)); } +/** `.git` as git's own path checks see it: case, trailing dots/spaces, NTFS short name and streams. */ function isDotGitName(name: string): boolean { - return name.toLowerCase().replace(/[ .]+$/, "") === ".git"; + const n = name.toLowerCase().replace(/[ .]+$/, ""); + return n === ".git" || n === "git~1" || n.startsWith(".git:"); } +const OID_LINE = /^[0-9a-f]{40}$/; +/** Longest single path component git checks out (NAME_MAX). */ +const MAX_TREE_NAME_BYTES = 255; + /** * SAM: refuse objects git itself cannot read, so a pushed object can never make the * repository uncloneable. The parsers above are lenient (any header order, lossy @@ -1297,6 +1303,12 @@ function assertGitObjectShape(obj: { type: ObjType; data: Uint8Array }): void { const lines = rawHeaderLines(obj.data); if (!lines) throw new GitParseError(`${obj.type} headers are not newline-terminated`); if (lines.some((l) => l.includes("\0"))) throw new GitParseError(`${obj.type} header contains NUL`); + // Git reads the first line by position: it must be the object's own first header, never a + // continuation line that the key list below would skip. + const first = obj.type === "commit" ? "tree " : "object "; + if (!lines[0]?.startsWith(first) || !OID_LINE.test(lines[0].slice(first.length))) { + throw new GitParseError(`${obj.type} must start with a ${first.trim()} line`); + } const keys = headerKeyList(lines); if (obj.type === "commit") { let i = 0; @@ -1328,9 +1340,20 @@ function assertGitObjectShape(obj: { type: ObjType; data: Uint8Array }): void { const name = byteString(data, sp + 1, nul); pos = nul + 21; if (!TREE_MODE.test(mode)) throw new GitParseError("tree entry has an invalid mode"); - if (!name || name.includes("/") || name === "." || name === ".." || isDotGitName(name) || names.has(name)) { + if ( + !name || + name.length > MAX_TREE_NAME_BYTES || + name.includes("/") || + name === "." || + name === ".." || + isDotGitName(name) || + names.has(name) + ) { throw new GitParseError("tree entry has an invalid or duplicate name"); } + if (mode === "120000" && name.toLowerCase().replace(/[ .]+$/, "") === ".gitmodules") { + throw new GitParseError("tree has a .gitmodules symlink"); + } names.add(name); } } diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index 39a61cb60d..db4d8babb5 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -333,6 +333,10 @@ export class GitStore { // describe old refs; stamping it with the new version would let a stranded, // later-collected object pass for reachable. if (this.reachableVersion() !== version) return; + // Unstamp before rewriting: while this rewrite yields, a stamp left from an earlier + // save would present the partial table as the whole reachable set, and a push in the + // window would extend that partial table and re-stamp it valid. + this.setMeta("reachable-version", ""); this.sql.exec("DELETE FROM reachable"); const n = set.markedSize; for (let i = 0; i < n; i++) { diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 3ee9297c34..e9fe2810d0 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -1250,6 +1250,7 @@ describe('push connectivity admission (closure must be complete per command)', ( }; const sig = 'Test 0 +0000'; const authorFirst = literal('commit', `author ${sig}\ntree ${plain.tree}\ncommitter ${sig}\n\nauthor first\n`); + const leading = literal('commit', ` junk\ntree ${plain.tree}\nauthor ${sig}\ncommitter ${sig}\n\nleading continuation\n`); const typeFirstTag = literal('tag', `type commit\nobject ${plain.commit}\ntag odd\ntagger ${sig}\n\nodd\n`); const badModeTree = literal('tree', Buffer.concat([Buffer.from('8 f\0'), Buffer.from(blob, 'hex')])); const badModeCommit = literal('commit', `tree ${badModeTree}\nauthor ${sig}\ncommitter ${sig}\n\nbad mode\n`); @@ -1258,13 +1259,15 @@ describe('push connectivity admission (closure must be complete per command)', ( token, [ [ZERO, authorFirst, 'refs/heads/author-first'], + [ZERO, leading, 'refs/heads/leading'], [ZERO, typeFirstTag, 'refs/tags/type-first'], [ZERO, badModeCommit, 'refs/heads/bad-mode'], [ZERO, plain.commit, 'refs/heads/plain'], ], - packOf(work, [authorFirst, typeFirstTag, badModeTree, badModeCommit, plain.commit, plain.tree, blob]) + packOf(work, [authorFirst, leading, typeFirstTag, badModeTree, badModeCommit, plain.commit, plain.tree, blob]) ); expect(out).toContain('ng refs/heads/author-first missing necessary objects'); + expect(out).toContain('ng refs/heads/leading missing necessary objects'); expect(out).toContain('ng refs/tags/type-first missing necessary objects'); expect(out).toContain('ng refs/heads/bad-mode missing necessary objects'); expect(out).toContain('ok refs/heads/plain'); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 27e8e5dc01..180053361b 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -357,6 +357,48 @@ describe('push admission: object shapes git can read', () => { ]); }); + it('refuses a leading continuation line and checkout-breaking names, with controls accepted', async () => { + const repo = new Repo(); + const blob = repo.blob('lead-blob'); + const tree = repo.tree('lead-tree', [treeEntry('100644', 'f', blob)]); + const good = repo.commit('lead-good', tree); + const sigLines = `author ${SIG}\ncommitter ${SIG}\n`; + const leadCommit = repo.put( + 'lead-commit', + 'commit', + enc.encode(` junk\ntree ${tree}\n${sigLines}\nx\n`) + ); + const leadTag = repo.put( + 'lead-tag', + 'tag', + enc.encode(` junk\nobject ${good}\ntype commit\ntag t\n\nx\n`) + ); + const named = (label: string, mode: string, name: string, oid: string) => + repo.commit(label, repo.tree(`${label}-tree`, [treeEntry(mode, name, oid)])); + const plan = await decide(repo, [ + [ZERO, leadCommit, 'refs/heads/lead'], + [ZERO, leadTag, 'refs/tags/lead'], + [ZERO, named('short', '40000', 'GIT~1', tree), 'refs/heads/short'], + [ZERO, named('stream', '100644', '.git:x', blob), 'refs/heads/stream'], + [ZERO, named('modules', '120000', '.gitmodules', blob), 'refs/heads/modules'], + [ZERO, named('long', '100644', 'n'.repeat(256), blob), 'refs/heads/long'], + [ZERO, named('limit', '100644', 'n'.repeat(255), blob), 'refs/heads/limit'], + [ZERO, named('modules-file', '100644', '.gitmodules', blob), 'refs/heads/modules-file'], + [ZERO, named('gitignore', '100644', '.gitignore', blob), 'refs/heads/gitignore'], + ]); + expect(plan.decisions.map((d) => (d.reject ? 'reject' : 'set'))).toEqual([ + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'set', + 'set', + 'set', + ]); + }); + it('refuses commits, tags and trees git cannot parse, with git-shaped controls accepted', async () => { const repo = new Repo(); const tree = repo.tree('shape-tree', [treeEntry('100644', 'f', repo.blob('shape-blob'))]); @@ -515,7 +557,11 @@ describe('reachable cache stamping and GC', () => { expect(moved.sql.exec).not.toHaveBeenCalled(); const steady = fakeThis('same'); await GitStore.prototype.saveReachable.call(steady as unknown as GitStore, set, 'same'); - expect(steady.setMeta).toHaveBeenCalledWith('reachable-version', 'same'); + // Unstamped before the rewrite, restamped only after it completes. + expect(steady.setMeta.mock.calls).toEqual([ + ['reachable-version', ''], + ['reachable-version', 'same'], + ]); }); it('invalidates the reachable cache when GC deletes objects, and only then', async () => { diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 869b5e9c99..123dbf23e4 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -115,3 +115,14 @@ The narrow verification found a HIGH regression introduced by the cache stop in The shape check moved to raw bytes. Lossy UTF-8 decoding hid BOM-prefixed commits and tags (clone-breaking) and falsely merged distinct non-UTF-8 names. Header sections must be newline-terminated, header NUL is refused, `.`, `..` and `.git` variants are refused, and every `100xxx` file mode is accepted. The budget-tolerant ancestry check was confirmed sound (verdict D: PASS). Unit tests cover each fix: an absent cached parent is refused, with a control; the stamp guard; GC invalidation, with a control; BOM, unterminated, NUL, `.git` and `..` cases, plus accepted Latin-1, BOM-only and `100600` names. Each fix was mutated once and its test went red. + +## Final re-verification of 77e55dbb (00:10 UTC) + +The original HIGH is closed. The race reproduced in 5 of 11 runs on 8bc9a3af4 and never on 77e55dbb. No admission path reads the reachable cache, and the shape check accepts everything git handles. + +New findings, fixed: +- HIGH: a leading continuation line before `tree`/`object` was skipped by the key list, but git rejects such an object. The first header line must now be exactly `tree ` or `object `. +- MEDIUM: a second cold clone rewriting a stamped cache left it partial during a yield, and a push in that window could stamp the partial set valid. `saveReachable` now unstamps before rewriting. +- LOW: `git~1`, `.git:` streams, a `.gitmodules` symlink and names over 255 bytes are now refused. + +Deferred to the backlog: path depth, and accepting uppercase-hex oids. Each guard was mutated once and its test went red. The real-git shape test also pushes the leading-continuation commit. diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md index 801a2948df..ba91d00171 100644 --- a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -44,4 +44,6 @@ Who can trigger them: - [ ] Decide on and implement per-token push rate limiting, or record why not. - [ ] Every malformed command line is answered with `ng` or a refusal, never dropped. - [ ] A push forking from an old, heavy commit succeeds within the budget. A real-git test proves it, and a stale or poisoned cache cannot vouch for a missing object. +- [ ] Decide whether to bound tree depth or total path length; 1,500 nested directories break checkout of the default branch. +- [ ] Optionally accept uppercase-hex oids in commit and tag headers, as git does (`isOid` is lowercase-only). - [ ] Optionally reject the remaining fsck error-level shapes that default clients tolerate but `transfer.fsckObjects=true` clients refuse: unsorted trees, malformed idents, CR in headers. From ef451677d40d218c4cd4382b20ab07f292708e50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:06:11 +0000 Subject: [PATCH 55/65] fix(selfhost): check reachable-cache validity when writing it Scoped verification of dc8e9e4c: the leading-continuation bypass is closed and nothing git accepts is refused. Two cache-concurrency MEDIUMs, one cause (validity carried forward instead of checked at the write): - Overlapping clone saves could stamp a partial table. saveReachable is single-flight: a generation counter, checked around every yield and before stamping, lets only the latest save write or stamp. - A push that read hadCache before a save unstamped could extend the partial table. commitPush re-checks reachableCacheValid() before refs move and extends only if the cache is still current. Also refuse `.gitmodules` symlinks in their NTFS short-name and stream forms. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/vendor/dgit/UPSTREAM.md | 4 +- apps/api/src/vendor/dgit/git/protocol.ts | 14 +++- apps/api/src/vendor/dgit/git/store.ts | 11 +++- .../hosted-git-push-admission.test.ts | 66 +++++++++++++++++++ .../2026-11-19-selfhost-hosted-git-h2.md | 11 ++++ 5 files changed, 100 insertions(+), 6 deletions(-) diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 4ebdd0aadb..8b8f0b8ab4 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -39,6 +39,6 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. -- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink in any of its NTFS forms); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. -- The reachable cache is stamped only with the ref version its clone walk started from, and unstamps the cache before rewriting it, so neither a push during the walk nor a second clone's rewrite can leave a stale or partial set marked current; GC invalidates the cache whenever it deletes objects. +- The reachable cache is stamped only with the ref version its clone walk started from, unstamps the cache before rewriting it, and lets only the latest of overlapping saves write or stamp; `commitPush` extends the cache only if it is still stamped current at commit time. A push during a clone walk, a second clone's rewrite, or a push during a rewrite therefore cannot leave a stale or partial set marked current; GC invalidates the cache whenever it deletes objects. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 9d09b39f88..893e6a1208 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1286,6 +1286,12 @@ function isDotGitName(name: string): boolean { return n === ".git" || n === "git~1" || n.startsWith(".git:"); } +/** `.gitmodules` in the same forms git checks: case, trailing dots/spaces, NTFS short name and streams. */ +function isDotGitmodulesName(name: string): boolean { + const n = name.toLowerCase().replace(/[ .]+$/, ""); + return n === ".gitmodules" || n === "gitmod~1" || n.startsWith(".gitmodules:"); +} + const OID_LINE = /^[0-9a-f]{40}$/; /** Longest single path component git checks out (NAME_MAX). */ const MAX_TREE_NAME_BYTES = 255; @@ -1351,7 +1357,7 @@ function assertGitObjectShape(obj: { type: ObjType; data: Uint8Array }): void { ) { throw new GitParseError("tree entry has an invalid or duplicate name"); } - if (mode === "120000" && name.toLowerCase().replace(/[ .]+$/, "") === ".gitmodules") { + if (mode === "120000" && isDotGitmodulesName(name)) { throw new GitParseError("tree has a .gitmodules symlink"); } names.add(name); @@ -1524,6 +1530,10 @@ export function commitPush(store: GitStore, plan: PushPlan): { results: CommandR let changed = false; let needsGc = false; let casMismatch = false; + // SAM: re-check the cache stamp now, before any ref moves. `plan.hadCache` was read + // before validation awaited; a clone's save may have unstamped and be rewriting the + // table since, and extending that partial table would stamp it current. + const cacheValid = plan.hadCache && store.reachableCacheValid(); for (const d of plan.decisions) { if (d.reject) { results.push({ ref: d.ref, ok: false, msg: d.reject }); @@ -1570,7 +1580,7 @@ export function commitPush(store: GitStore, plan: PushPlan): { results: CommandR // describing a command that did not apply) invalidates it, so the next full // clone rebuilds by walking rather than risk serving unreachable objects. if (changed) { - if (plan.hadCache && !needsGc && !casMismatch) store.extendReachable(plan.known); + if (cacheValid && !needsGc && !casMismatch) store.extendReachable(plan.known); else store.invalidateReachable(); } return { results, changed, needsGc }; diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts index db4d8babb5..4a36d2838d 100644 --- a/apps/api/src/vendor/dgit/git/store.ts +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -34,6 +34,8 @@ const CACHE_BUDGET = typeof caches !== "undefined" ? 16 * 1024 * 1024 : 128 * 10 export class GitStore { readonly packs: PackStore; readonly cache = new ObjCache(CACHE_BUDGET); + /** SAM: bumped by each saveReachable; only the latest save may keep writing or stamp. */ + private reachableSaveGeneration = 0; /** * Whether the loose `objects` table holds anything. A pushed repo is * pack-native — loose objects only appear after a gc migration (see @@ -333,6 +335,10 @@ export class GitStore { // describe old refs; stamping it with the new version would let a stranded, // later-collected object pass for reachable. if (this.reachableVersion() !== version) return; + // Single-flight: a later save's DELETE wipes this one's rows, so a superseded + // save must neither keep inserting nor stamp what is left. + const generation = ++this.reachableSaveGeneration; + const current = () => this.reachableSaveGeneration === generation && this.reachableVersion() === version; // Unstamp before rewriting: while this rewrite yields, a stamp left from an earlier // save would present the partial table as the whole reachable set, and a push in the // window would extend that partial table and re-stamp it valid. @@ -342,11 +348,12 @@ export class GitStore { for (let i = 0; i < n; i++) { this.sql.exec("INSERT OR IGNORE INTO reachable (oid) VALUES (?)", set.markedAtHex(i)); if ((i & 8191) === 8191) { - if (this.reachableVersion() !== version) return; + if (!current()) return; await new Promise((r) => setTimeout(r, 0)); + if (!current()) return; } } - if (this.reachableVersion() !== version) return; + if (!current()) return; this.setMeta("reachable-version", version); } diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 180053361b..2bc2fea00c 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -381,6 +381,8 @@ describe('push admission: object shapes git can read', () => { [ZERO, named('short', '40000', 'GIT~1', tree), 'refs/heads/short'], [ZERO, named('stream', '100644', '.git:x', blob), 'refs/heads/stream'], [ZERO, named('modules', '120000', '.gitmodules', blob), 'refs/heads/modules'], + [ZERO, named('modules-short', '120000', 'GITMOD~1', blob), 'refs/heads/modules-short'], + [ZERO, named('modules-stream', '120000', '.gitmodules:x', blob), 'refs/heads/modules-stream'], [ZERO, named('long', '100644', 'n'.repeat(256), blob), 'refs/heads/long'], [ZERO, named('limit', '100644', 'n'.repeat(255), blob), 'refs/heads/limit'], [ZERO, named('modules-file', '100644', '.gitmodules', blob), 'refs/heads/modules-file'], @@ -393,6 +395,8 @@ describe('push admission: object shapes git can read', () => { 'reject', 'reject', 'reject', + 'reject', + 'reject', 'set', 'set', 'set', @@ -547,6 +551,7 @@ describe('reachable cache stamping and GC', () => { const set = new OidSet(16); set.markHex(oidOf('reachable-1')); const fakeThis = (current: string) => ({ + reachableSaveGeneration: 0, reachableVersion: () => current, sql: { exec: vi.fn() }, setMeta: vi.fn(), @@ -596,3 +601,64 @@ describe('reachable cache stamping and GC', () => { expect(clean.invalidateReachable).not.toHaveBeenCalled(); }); }); + +describe('reachable cache writers check validity when they write', () => { + it('lets only the latest of two overlapping clone saves keep writing and stamp', async () => { + const { GitStore } = await import('../../../src/vendor/dgit/git/store'); + const { OidSet } = await import('../../../src/vendor/dgit/git/oidset'); + const n = 8192 * 2 + 5; // more than one insert batch, so each save yields mid-rewrite + const set = new OidSet(n); + for (let i = 0; i < n; i++) set.markHex(oidOf(`row-${i}`)); + let inserts = 0; + const store = { + reachableSaveGeneration: 0, + reachableVersion: () => 'v', + sql: { exec: (q: string) => void (q.startsWith('INSERT') && inserts++) }, + setMeta: vi.fn(), + } as unknown as InstanceType; + const save = GitStore.prototype.saveReachable; + const first = save.call(store, set, 'v'); // runs one batch, then yields + const second = save.call(store, set, 'v'); // supersedes it + await Promise.all([first, second]); + const stamps = (store.setMeta as ReturnType).mock.calls.filter( + ([, v]) => v === 'v' + ); + expect(stamps).toHaveLength(1); + // The superseded save stopped after its first batch; the latest wrote every row. + expect(inserts).toBe(8192 + n); + }); + + it('extends the cache at commit only if it is still stamped current, with a control', async () => { + const run = async (stillValid: boolean) => { + const repo = new Repo(); + const base = repo.simple('base'); + repo.refs.set('refs/heads/main', base); + const next = repo.simple('next', [base]); + const store = repo.store() as unknown as Record; + store.getMeta = (key: string) => (key === 'reachable-version' ? 'v' : null); + const extendReachable = vi.fn(); + const invalidateReachable = vi.fn(); + Object.assign(store, { + extendReachable, + invalidateReachable, + reachableCacheValid: () => stillValid, + }); + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: base, next, ref: 'refs/heads/main' }], + null + ) + ); + expect(plan.hadCache).toBe(true); + commitPush(store as unknown as GitStore, plan); + return { extendReachable, invalidateReachable }; + }; + const rewritten = await run(false); // a clone's save unstamped the cache during validation + expect(rewritten.extendReachable).not.toHaveBeenCalled(); + expect(rewritten.invalidateReachable).toHaveBeenCalledOnce(); + const steady = await run(true); + expect(steady.extendReachable).toHaveBeenCalledOnce(); + expect(steady.invalidateReachable).not.toHaveBeenCalled(); + }); +}); diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 123dbf23e4..48b768db31 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -126,3 +126,14 @@ New findings, fixed: - LOW: `git~1`, `.git:` streams, a `.gitmodules` symlink and names over 255 bytes are now refused. Deferred to the backlog: path depth, and accepting uppercase-hex oids. Each guard was mutated once and its test went red. The real-git shape test also pushes the leading-continuation commit. + +## Scoped verification of dc8e9e4c (00:25 UTC) + +- Q1 PASS: the leading-continuation bypass is closed. 27 crafted commit and tag shapes went through the real Durable Object; none of the accepted ones broke a clone. +- Q2 PASS: nothing that git fsck accepts and a default clone checks out is refused. +- Q3 found two MEDIUM cache-concurrency races, both fixed: + - Two overlapping clone saves could stamp a partial table. `saveReachable` is now single-flight through a generation counter, checked before and after every yield and before stamping. + - A push that read `hadCache` before a save unstamped could extend the partial table. `commitPush` now re-checks `reachableCacheValid()` at commit time, before refs move. +- LOW: the `.gitmodules` symlink check now covers `gitmod~1` and `.gitmodules:` streams. + +Unit tests cover overlapping saves (only the latest stamps; the superseded save stops after one batch), the commit-time re-check with a control, and the NTFS forms. Each guard was mutated once and its test went red. The admission HIGHs were independently verified closed; these last cache fixes have discriminating tests but no further review round. From 1bbf2aeb23f6c6d99437a5692ccc9b304b394fa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:18:47 +0000 Subject: [PATCH 56/65] fix(selfhost): resolve Codex findings on hosted git ls-refs, GC, buffering, TTL - Honor at most 256 ref-prefix arguments; past that answer unfiltered, as git does, so the filter cost is bounded by the cap (r4636317748). - Cancel an upstream response the repo-browse consumer abandons, so the hosted repository's upload slot is released (r4636466068). - GC drops whole packs holding nothing reachable and no delta base before inflating anything, so a rejected push's pack is reclaimed even when migrating the rest exceeds the budget (r4636595142, partial; resumable migration stays in the backlog), and keeps delta bases only while packs are kept (r4636595147). - Grow the receive command-section buffer geometrically (r4636751965). - The personal clone token honors ARTIFACTS_TOKEN_TTL_SECONDS like the workspace and browsing credentials (r4636751970). Co-Authored-By: Claude Opus 5.5 --- .../selfhost/hosted-git/hosted-git-body.ts | 35 ++++++++ .../src/selfhost/hosted-git/hosted-git-gc.ts | 23 +++-- .../selfhost/hosted-git/hosted-git-ls-refs.ts | 11 ++- .../selfhost/hosted-git/hosted-git-repo.ts | 30 ++++--- .../src/selfhost/hosted-git/token-route.ts | 3 + apps/api/src/vendor/dgit/UPSTREAM.md | 2 + apps/api/src/vendor/dgit/git/packstore.ts | 32 +++++++ .../hosted-git/hosted-git-conformance.test.ts | 59 +++++++++++- .../hosted-git/support/hosted-git-entry.ts | 10 +++ .../hosted-git/support/hosted-git-runtime.ts | 3 + .../hosted-git-ls-refs.test.ts | 14 +++ .../unit/selfhost/hosted-git-body.test.ts | 23 +++++ .../hosted-git-push-admission.test.ts | 89 +++++++++++++++++++ deploy/selfhost/README.md | 7 +- .../src/repo-browse/fetch-http-client.ts | 10 ++- .../tests/unit/fetch-http-client.test.ts | 39 ++++++++ .../2026-11-19-selfhost-hosted-git-h2.md | 13 +++ ...1-19-hosted-git-gc-and-ingest-hardening.md | 4 +- 18 files changed, 383 insertions(+), 24 deletions(-) create mode 100644 apps/api/tests/unit/selfhost/hosted-git-body.test.ts create mode 100644 packages/repo-hosting/tests/unit/fetch-http-client.test.ts diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-body.ts b/apps/api/src/selfhost/hosted-git/hosted-git-body.ts index 3c6f2fd935..a9305081d3 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-body.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-body.ts @@ -62,3 +62,38 @@ export async function drainBounded( // The client may already be gone. } } + +/** + * A byte buffer that grows geometrically as chunks arrive, so reading a body in many small chunks + * copies O(total) bytes rather than re-copying everything read so far on every chunk. + */ +export class ChunkBuffer { + private bytes: Uint8Array; + length: number; + /** Bytes copied so far, for tests that bound the work. */ + copied = 0; + + constructor(initial: Uint8Array = new Uint8Array(0)) { + this.bytes = initial; + this.length = initial.length; + } + + append(chunk: Uint8Array): void { + if (this.length + chunk.length > this.bytes.length) { + const grown = new Uint8Array( + Math.max(this.bytes.length * 2, this.length + chunk.length, 4096) + ); + grown.set(this.bytes.subarray(0, this.length)); + this.copied += this.length; + this.bytes = grown; + } + this.bytes.set(chunk, this.length); + this.length += chunk.length; + this.copied += chunk.length; + } + + /** The bytes in [start, end), clamped to what has been read. */ + view(start = 0, end = this.length): Uint8Array { + return this.bytes.subarray(start, Math.min(end, this.length)); + } +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts index 25d92e0b8d..bba810a73e 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts @@ -76,14 +76,26 @@ export async function runHostedGitGc(store: GitStore): Promise(store.packs.baseOids()); + let removed = 0; + + // Reclaim whole packs that hold nothing reachable and no delta base before inflating + // anything. A rejected push's pack is reclaimed this way even when migrating the rest + // would exceed the work budget. + for (const packId of store.packs.packIds()) { + const oids = store.packs.packObjectOids(packId); + if (oids.some((oid) => reachable.hasHex(oid) || bases.has(oid))) continue; + await store.packs.dropPack(packId); + removed += oids.length; + } const packCount = store.packs.countObjects(); const noHeadroom = packCount > 0 && store.dbSize() + store.packs.totalPackBytes() > DO_STORAGE_CAP; - let removed = 0; - if (packCount > 0 && !noHeadroom) { + const migrate = packCount > 0 && !noHeadroom; + if (migrate) { // Migrate reachable pack objects to loose storage first, then drop the packs. let migrated = 0; for (let i = 0; i < reachable.size; i++) { @@ -100,7 +112,8 @@ export async function runHostedGitGc(store: GitStore): Promise 0 ? prefixes : null; } diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index 30449e7c24..7f344694ba 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -30,7 +30,13 @@ import { GitStore } from '../../vendor/dgit/git/store'; import { concat, te } from '../../vendor/dgit/git/util'; import { gunzipLimited } from '../../vendor/dgit/git/zlib'; import type { HostedGitEnv } from './env'; -import { drainBounded, pktLength, readBodyBounded, RequestTooLargeError } from './hosted-git-body'; +import { + ChunkBuffer, + drainBounded, + pktLength, + readBodyBounded, + RequestTooLargeError, +} from './hosted-git-body'; import { armHostedGitGcAlarm, GC_DELAY_MS, @@ -331,28 +337,30 @@ export class HostedGitRepo extends DurableObject { const currentBytes = this.store.dbSize(); const maxBytes = hostedGitPushByteBudget(currentBytes, limits); let reader: ReadableStreamDefaultReader | null = null; - let buf: Uint8Array; + let body: ChunkBuffer; if (req.headers.get('content-encoding')?.includes('gzip')) { - buf = gunzipLimited(await readBodyBounded(req, limits.maxPushBytes), limits.maxPushBytes); + body = new ChunkBuffer( + gunzipLimited(await readBodyBounded(req, limits.maxPushBytes), limits.maxPushBytes) + ); } else { reader = req.body?.getReader() ?? null; - buf = new Uint8Array(0); + body = new ChunkBuffer(); } // The pkt-line command section is small; everything after it is the pack. let pos = 0; const need = async (n: number): Promise => { - while (buf.length - pos < n) { + while (body.length - pos < n) { if (!reader) return false; const { done, value } = await readGitChunk(reader); if (done) return false; - if (value?.length) buf = concat([buf, value]); + if (value?.length) body.append(value); } return true; }; for (;;) { if (!(await need(4))) break; - const len = pktLength(buf.subarray(pos, pos + 4)); + const len = pktLength(body.view(pos, pos + 4)); if (len === 0) { pos += 4; break; @@ -361,7 +369,7 @@ export class HostedGitRepo extends DurableObject { if (!(await need(len))) throw new Error('truncated push request'); pos += len; } - const { commands, caps } = parsePushCommands(buf.subarray(0, pos)); + const { commands, caps } = parsePushCommands(body.view(0, pos)); const sideband = caps.includes('side-band-64k'); const progress = (msg: string) => { if (!sideband) return; @@ -370,11 +378,11 @@ export class HostedGitRepo extends DurableObject { // Read up to the pack header so the declared object count can be checked before storing. const packStart = pos; - const hasPack = (await need(PACK_HEADER_BYTES)) || buf.length > packStart; + const hasPack = (await need(PACK_HEADER_BYTES)) || body.length > packStart; let unpackError = hostedGitRefRefusal(this.store.refs(), commands, currentBytes, limits); let packId: number | null = null; if (hasPack) { - const header = buf.subarray(packStart, packStart + PACK_HEADER_BYTES); + const header = body.view(packStart, packStart + PACK_HEADER_BYTES); const incomingObjects = header.length === PACK_HEADER_BYTES ? new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8) @@ -390,7 +398,7 @@ export class HostedGitRepo extends DurableObject { unpackError = refusal; } else { try { - const ingested = await this.store.packs.ingest(buf.subarray(packStart), reader, { + const ingested = await this.store.packs.ingest(body.view(packStart), reader, { maxBytes, sizeHint: Number.isFinite(parseInt(req.headers.get('content-length') ?? '', 10)) ? parseInt(req.headers.get('content-length') ?? '', 10) diff --git a/apps/api/src/selfhost/hosted-git/token-route.ts b/apps/api/src/selfhost/hosted-git/token-route.ts index dc279af990..00050bb77e 100644 --- a/apps/api/src/selfhost/hosted-git/token-route.ts +++ b/apps/api/src/selfhost/hosted-git/token-route.ts @@ -42,6 +42,9 @@ hostedGitTokenRoutes.post('/:id/hosted-git/token', async (c) => { repo: project.artifactsRepoId, scope, userId, + // The same operator setting that bounds workspace and browsing credentials; an absent or + // invalid value falls back to the default inside clampHostedGitTokenTtl. + ttlSeconds: Number.parseInt(c.env.ARTIFACTS_TOKEN_TTL_SECONDS ?? '', 10), }); return c.json({ cloneUrl: project.repository, diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index 8b8f0b8ab4..f7d5d5dd07 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -42,3 +42,5 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink in any of its NTFS forms); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. - The reachable cache is stamped only with the ref version its clone walk started from, unstamps the cache before rewriting it, and lets only the latest of overlapping saves write or stamp; `commitPush` extends the cache only if it is still stamped current at commit time. A push during a clone walk, a second clone's rewrite, or a push during a rewrite therefore cannot leave a stale or partial set marked current; GC invalidates the cache whenever it deletes objects. + +- PackStore adds `packIds`, `packObjectOids` and `dropPack`. Hosted git GC drops whole packs that hold no reachable object and no delta base before it inflates anything, and keeps delta bases only while packs are kept (migration stores reachable objects whole). diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts index 6e27bd4380..5fa50c8e84 100644 --- a/apps/api/src/vendor/dgit/git/packstore.ts +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -295,6 +295,38 @@ export class PackStore { } } + /** SAM: ids of the stored packs. */ + packIds(): number[] { + return this.sql + .exec<{ pack_id: number }>("SELECT pack_id FROM pack_meta ORDER BY pack_id") + .toArray() + .map((r) => r.pack_id); + } + + /** SAM: the oids one pack stores. */ + packObjectOids(packId: number): string[] { + return this.sql + .exec<{ oid: string }>("SELECT oid FROM pack_objects WHERE pack_id = ?", packId) + .toArray() + .map((r) => r.oid); + } + + /** + * SAM: drop one whole pack. GC calls this only for a pack it proved holds no reachable + * object and no delta base, so no object is inflated to reclaim it. + */ + async dropPack(packId: number): Promise { + const r2 = this.backendOf(packId) === "r2"; + this.sql.exec("DELETE FROM pack_meta WHERE pack_id = ?", packId); + this.sql.exec("DELETE FROM pack_data WHERE pack_id = ?", packId); + this.sql.exec("DELETE FROM pack_objects WHERE pack_id = ?", packId); + this.sql.exec("DELETE FROM pack_pending WHERE pack_id = ?", packId); + // the pack id can be handed out again by the next ingest: drop cached rows for it + this.chunks.clear(); + this.backend.clear(); + if (r2) await this.deleteR2Packs([packId]); + } + countObjects(): number { return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM pack_objects").one().n; } diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index e9fe2810d0..265ce9f930 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -29,6 +29,7 @@ import { import { buildReceivePackRequest,buildSeedPack } from '../../src/services/artifacts/seed-readme'; import { HOSTED_GIT_TEST_BASE_DOMAIN, + HOSTED_GIT_TEST_TOKEN_TTL_SECONDS, type HostedGitRuntime, startHostedGitRuntime, } from './support/hosted-git-runtime'; @@ -593,9 +594,15 @@ describe('member clone credentials (POST /api/projects/:id/hosted-git/token)', ( method: 'POST', headers: { 'x-test-user-id': owner }, }); - const body = (await res.json()) as { token: string; cloneUrl: string; host: string }; + const requestedAt = Date.now(); + const body = (await res.json()) as { token: string; cloneUrl: string; host: string; expiresAt: string }; expect(res.status, JSON.stringify(body)).toBe(200); expect(body.cloneUrl).toBe(project.repository); + // The personal credential honors the operator's ARTIFACTS_TOKEN_TTL_SECONDS (900 s here), + // like workspace and browsing credentials, rather than the one-hour default. + const lifetimeSeconds = (Date.parse(body.expiresAt) - requestedAt) / 1000; + expect(lifetimeSeconds).toBeGreaterThan(HOSTED_GIT_TEST_TOKEN_TTL_SECONDS - 60); + expect(lifetimeSeconds).toBeLessThanOrEqual(HOSTED_GIT_TEST_TOKEN_TTL_SECONDS + 1); const work = await freshDir('member'); await gitOk(['clone', localRemote(body.cloneUrl, body.token), work]); await writeFile(join(work, 'human.txt'), 'from a laptop\n'); @@ -819,6 +826,56 @@ describe('repository cleanup through real SQLite', () => { expect((await info()).objects).toBe(before.objects); }); + it('reclaims a rejected push pack even when migrating the reachable packs exceeds the budget', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'GC budget'); + const token = await mintToken(project, 'write'); + const work = await freshDir('gc-budget'); + await gitOk(['clone', localRemote(project.repository, token), work]); + // A reachable 5 MiB blob (a few KB packed) that GC would have to inflate to migrate. + await writeFile(join(work, 'big.txt'), 'b'.repeat(5 * 1024 * 1024)); + await gitOk(['add', 'big.txt'], work); + await gitOk(['commit', '-q', '-m', 'big'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/main'], work); + const info = async () => + (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { objects: number }; + const beforeRejected = await info(); + const { pack, commitOid } = await buildSeedPack({ projectName: 'Rejected under budget' }); + const rejected = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, + body: buildReceivePackRequest(commitOid, 'main', pack) as BodyInit, + }); + expect(await rejected.text()).toContain('ng refs/heads/main'); + expect((await info()).objects).toBeGreaterThan(beforeRejected.objects); + const gcStateOf = async (p: CreatedProject) => + (await (await runtime.fetch(`/__test/gc-state/${p.artifactsRepoId}`)).json()) as { pending: string }; + const setting = "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxInflatedBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"; + await runtime.DATABASE.prepare(setting).bind(JSON.stringify(2 * 1024 * 1024), Date.now()).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + // Migration inflates the 5 MiB blob past the 2 MiB budget and fails; the rejected pack + // was already dropped whole, without inflating anything. + const has = async (oid: string) => + ((await (await runtime.fetch(`/__test/has/${project.artifactsRepoId}/${oid}`)).json()) as { has: boolean }).has; + expect(await has(commitOid)).toBe(true); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + // GC failed on the budget (the work is retried), yet the rejected pack is gone. A failed + // migration can leave loose copies of objects it already moved, so object counts would + // not show this; the next successful GC removes those copies. + expect(await has(commitOid)).toBe(false); + expect((await gcStateOf(project)).pending).toBe('1'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxInflatedBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + // With the default budget the rest of the cleanup completes and the repository still clones. + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect((await info()).objects).toBe(beforeRejected.objects); + const check = await freshDir('gc-budget-check'); + await gitOk(['clone', localRemote(project.repository, token), check]); + expect((await readFile(join(check, 'big.txt'), 'utf8')).length).toBe(5 * 1024 * 1024); + }); + it('reclaims failed-ingest pack rows before the next push quota check', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Failed ingest'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index f66292bb0a..75b4a2f6f9 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -55,6 +55,11 @@ export class HostedGitRepoTest extends HostedGitRepo { }; return new Response('ok'); } + if (new URL(req.url).pathname.startsWith('/__test/has/')) { + const oid = new URL(req.url).pathname.slice('/__test/has/'.length); + const store = (this as unknown as { store: { has: (oid: string) => boolean } }).store; + return Response.json({ has: store.has(oid) }); + } if (new URL(req.url).pathname === '/__test/gc-state') { return Response.json({ pending: this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'").toArray()[0]?.value, alarm: await this.ctx.storage.getAlarm() }); } @@ -127,6 +132,11 @@ app.delete('/__test/repository/:repo', async (c) => { return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/', { method: 'DELETE' }); }); +app.get('/__test/has/:repo/:oid', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns.get(ns.idFromName(c.req.param('repo'))).fetch(`https://hosted-git/__test/has/${c.req.param('oid')}`); +}); + app.post('/__test/fail-read/:repo/:oid', (c) => { const ns = c.env.HOSTED_GIT!; return ns.get(ns.idFromName(c.req.param('repo'))).fetch(`https://hosted-git/__test/fail-read/${c.req.param('oid')}`); diff --git a/apps/api/tests/hosted-git/support/hosted-git-runtime.ts b/apps/api/tests/hosted-git/support/hosted-git-runtime.ts index d0ce9f554d..a80013358d 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-runtime.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-runtime.ts @@ -28,6 +28,7 @@ const { Miniflare } = createRequire(import.meta.resolve('@cloudflare/vitest-pool ); export const HOSTED_GIT_TEST_BASE_DOMAIN = 'sam.test.example'; +export const HOSTED_GIT_TEST_TOKEN_TTL_SECONDS = 900; export interface HostedGitRuntime { /** e.g. http://127.0.0.1:41234 */ @@ -91,6 +92,8 @@ export async function startHostedGitRuntime( ENCRYPTION_KEY: randomBytes(32).toString('base64'), ARTIFACTS_ENABLED: 'true', HOSTED_GIT_BACKEND: 'durable-object', + // Non-default, so tests can see every credential route honor the operator's lifetime. + ARTIFACTS_TOKEN_TTL_SECONDS: String(HOSTED_GIT_TEST_TOKEN_TTL_SECONDS), JWT_PRIVATE_KEY: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), JWT_PUBLIC_KEY: publicKey.export({ type: 'spki', format: 'pem' }).toString(), }, diff --git a/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts index a2981eaac5..0ba9220f6f 100644 --- a/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts +++ b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts @@ -89,3 +89,17 @@ it('rejects an oversized advertisement with a readable response', async () => { expect(response.status).toBe(413); expect(await response.text()).toContain('advertisement exceeds'); }); + +describe('ls-refs ref-prefix count bound (Codex r4636317748)', () => { + it('honors up to the bound and answers unfiltered past it, as git does', async () => { + const { MAX_LS_REFS_PREFIXES } = + await import('../../../src/selfhost/hosted-git/hosted-git-ls-refs'); + const prefixes = (n: number) => + Array.from({ length: n }, (_, i) => `ref-prefix refs/heads/p${i}/`); + expect(lsRefsPrefixes(lsRefsRequest(...prefixes(MAX_LS_REFS_PREFIXES)))).toHaveLength( + MAX_LS_REFS_PREFIXES + ); + // One more and the filter is skipped, so its cost is bounded by the cap, not the request size. + expect(lsRefsPrefixes(lsRefsRequest(...prefixes(MAX_LS_REFS_PREFIXES + 1)))).toBeNull(); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-body.test.ts b/apps/api/tests/unit/selfhost/hosted-git-body.test.ts new file mode 100644 index 0000000000..014bbe964a --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-body.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; + +import { ChunkBuffer } from '../../../src/selfhost/hosted-git/hosted-git-body'; + +describe('ChunkBuffer (Codex r4636751965)', () => { + it('copies O(total) bytes when a 1 MiB command section arrives one byte at a time', () => { + const total = 1024 * 1024; + const buffer = new ChunkBuffer(); + const one = new Uint8Array([0x41]); + for (let i = 0; i < total; i++) buffer.append(one); + expect(buffer.length).toBe(total); + expect(buffer.view(total - 1)).toEqual(one); + // Re-copying everything read so far on each chunk would be ~total^2 / 2 (5.5e11) bytes. + expect(buffer.copied).toBeLessThan(4 * total); + }); + + it('keeps an initial body and clamps views to what has been read', () => { + const buffer = new ChunkBuffer(new Uint8Array([1, 2, 3])); + buffer.append(new Uint8Array([4, 5])); + expect([...buffer.view()]).toEqual([1, 2, 3, 4, 5]); + expect([...buffer.view(3, 99)]).toEqual([4, 5]); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 2bc2fea00c..1ea318fe6d 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -581,6 +581,7 @@ describe('reachable cache stamping and GC', () => { get: async () => null, packs: { baseOids: () => [], + packIds: () => [], countObjects: () => 0, totalPackBytes: () => 0, lookup: () => null, @@ -662,3 +663,91 @@ describe('reachable cache writers check validity when they write', () => { expect(steady.invalidateReachable).not.toHaveBeenCalled(); }); }); + +describe('GC reclaims packs without inflating and drops delta-only bases', () => { + /** + * A fake object store with packs and loose objects. A ref points at commit C; C's tree T holds + * blob B2, which is stored as a delta on blob B1 (unreachable). Pack 1 holds C, T, B2 and B1; + * pack 2 is a rejected push's pack holding only unreachable X. + */ + function gcFixture(opts: { noHeadroom?: boolean } = {}) { + const repo = new Repo(); + const b1 = repo.blob('base-blob'); + const b2 = repo.blob('delta-blob'); + const tree = repo.tree('gc-tree', [treeEntry('100644', 'f', b2)]); + const commit = repo.commit('gc-commit', tree); + const x = repo.blob('rejected'); + repo.refs.set('refs/heads/main', commit); + const packs = new Map([ + [1, [commit, tree, b2, b1]], + [2, [x]], + ]); + const loose = new Map(); + const dropped: number[] = []; + const migrated: string[] = []; + const reads: string[] = []; + const store = { + ...(repo.store() as unknown as Record), + objectCount: () => [...packs.values()].flat().length + loose.size, + get: async (oid: string) => { + reads.push(oid); + return repo.objects.get(oid) ?? null; + }, + packs: { + baseOids: () => [b1], + packIds: () => [...packs.keys()], + packObjectOids: (id: number) => packs.get(id) ?? [], + dropPack: async (id: number) => { + dropped.push(id); + packs.delete(id); + }, + countObjects: () => [...packs.values()].flat().length, + totalPackBytes: () => (opts.noHeadroom ? 11 * 1024 ** 3 : 0), + lookup: (oid: string) => ([...packs.values()].some((o) => o.includes(oid)) ? {} : null), + reset: () => packs.clear(), + }, + dbSize: () => 0, + put: (oid: string) => { + migrated.push(oid); + loose.set(oid, true); + }, + allOids: () => [...loose.keys()], + deleteObject: (oid: string) => loose.delete(oid), + invalidateReachable: () => undefined, + } as unknown as GitStore; + return { store, ids: { b1, b2, tree, commit, x }, dropped, migrated, reads, loose }; + } + + it('drops a pack with nothing reachable before reading any pack object', async () => { + const { runHostedGitGc } = await import('../../../src/selfhost/hosted-git/hosted-git-gc'); + const f = gcFixture(); + let readsAtDrop = -1; + const packs = (f.store as unknown as { packs: { dropPack: (id: number) => Promise } }) + .packs; + const drop = packs.dropPack; + packs.dropPack = async (id) => { + readsAtDrop = f.reads.filter((oid) => oid === f.ids.b2).length; + await drop(id); + }; + await runHostedGitGc(f.store); + expect(f.dropped).toEqual([2]); + // The rejected pack went before migration inflated any blob. + expect(readsAtDrop).toBe(0); + }); + + it('does not keep a delta-only base after migrating, but keeps a loose base while packs stay', async () => { + const { runHostedGitGc } = await import('../../../src/selfhost/hosted-git/hosted-git-gc'); + const migrating = gcFixture(); + await runHostedGitGc(migrating.store); + expect(migrating.migrated.sort()).toEqual( + [migrating.ids.commit, migrating.ids.tree, migrating.ids.b2].sort() + ); + expect(migrating.loose.has(migrating.ids.b1)).toBe(false); + + const kept = gcFixture({ noHeadroom: true }); + kept.loose.set(kept.ids.b1, true); // a loose base that pack deltas still use + const result = await runHostedGitGc(kept.store); + expect(result.skipped).toBe(true); + expect(kept.loose.has(kept.ids.b1)).toBe(true); + }); +}); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 1fd2156344..87ae72b6ee 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -219,9 +219,10 @@ push checks quota. Defaults are 64 MiB per push, 30,000 objects 10,000 refs and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation per request, delta depth 100 and 120 seconds per git operation. Operators can lower these limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. -Known limit: GC inflates every object it moves, under the same decompression budget, so it -cannot finish while more than `repositories.maxInflatedBytes` of pushed content waits for -collection. Unreclaimed packs then count toward the storage limit. Tracked in +GC first drops whole packs that hold nothing reachable (for example a rejected push) without +inflating them. Known limit: moving the remaining reachable packed objects to loose storage +inflates each one under the same decompression budget, so that step cannot finish while more than +`repositories.maxInflatedBytes` of reachable pushed content waits for collection. Tracked in `tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md`. Clone/push credentials expire and runtime credentials also require the same active workspace and callback generation. Deleting a project removes its hosted repository. At the ref limit, delete old refs in a separate diff --git a/packages/repo-hosting/src/repo-browse/fetch-http-client.ts b/packages/repo-hosting/src/repo-browse/fetch-http-client.ts index 5f248dac49..acdf426408 100644 --- a/packages/repo-hosting/src/repo-browse/fetch-http-client.ts +++ b/packages/repo-hosting/src/repo-browse/fetch-http-client.ts @@ -28,13 +28,21 @@ async function* streamChunks( ): AsyncGenerator { if (!stream) return; const reader = stream.getReader(); + let finished = false; try { for (;;) { const { done, value } = await reader.read(); - if (done) return; + if (done) { + finished = true; + return; + } if (value) yield value; } } finally { + // A consumer that stops early (isomorphic-git abandons the iterator when pack parsing + // throws) must cancel the response, or its producer, such as a hosted repository's + // upload slot, stays held until the stream is garbage collected. + if (!finished) await reader.cancel().catch(() => undefined); reader.releaseLock(); } } diff --git a/packages/repo-hosting/tests/unit/fetch-http-client.test.ts b/packages/repo-hosting/tests/unit/fetch-http-client.test.ts new file mode 100644 index 0000000000..f13239b7e3 --- /dev/null +++ b/packages/repo-hosting/tests/unit/fetch-http-client.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createFetchHttpClient } from '../../src/repo-browse/fetch-http-client'; + +/** A response whose stream records whether it was cancelled (Codex r4636466068). */ +function trackedResponse(chunks: number) { + const cancel = vi.fn(); + let sent = 0; + const body = new ReadableStream({ + pull(controller) { + if (sent++ < chunks) controller.enqueue(new Uint8Array([sent])); + else controller.close(); + }, + cancel, + }); + return { response: new Response(body), cancel }; +} + +describe('createFetchHttpClient response body', () => { + it('cancels the upstream response when the consumer abandons the iterator early', async () => { + const { response, cancel } = trackedResponse(10); + const client = createFetchHttpClient(async () => response); + const res = await client.request({ url: 'https://repo.example/info/refs', method: 'GET' }); + const body = res.body as AsyncIterableIterator; + expect((await body.next()).done).toBe(false); + await body.return?.(undefined); // what a for-await `break` or a thrown parse error does + expect(cancel).toHaveBeenCalledOnce(); + }); + + it('does not cancel a response read to the end', async () => { + const { response, cancel } = trackedResponse(3); + const client = createFetchHttpClient(async () => response); + const res = await client.request({ url: 'https://repo.example/info/refs', method: 'GET' }); + let seen = 0; + for await (const chunk of res.body as AsyncIterableIterator) seen += chunk.length; + expect(seen).toBe(3); + expect(cancel).not.toHaveBeenCalled(); + }); +}); diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index 48b768db31..fbe97e7f97 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -137,3 +137,16 @@ Deferred to the backlog: path depth, and accepting uppercase-hex oids. Each guar - LOW: the `.gitmodules` symlink check now covers `gitmod~1` and `.gitmodules:` streams. Unit tests cover overlapping saves (only the latest stamps; the superseded save stops after one batch), the commit-time re-check with a control, and the NTFS forms. Each guard was mutated once and its test went red. The admission HIGHs were independently verified closed; these last cache fixes have discriminating tests but no further review round. + +## Codex threads on dc8e9e4c (00:40 UTC) + +Seven Codex findings were reconciled: +- **P1 r4636317748:** at most 256 `ref-prefix` arguments are honored; past that the answer is unfiltered, as git does. +- **P2 r4636466068:** an abandoned upstream fetch stream is now cancelled, so an upload slot is released. +- **P1 r4636595142 (partly addressed):** GC drops whole unreferenced packs before inflating anything, which reclaims rejected-push packs even when migration exceeds the budget. Resumable migration is in the backlog. +- **P2 r4636595147:** delta bases are kept only while packs are kept, so migration no longer preserves delta-only bases. +- **P2 r4636595152 (deferred):** delta depth at ingest is in the backlog. +- **P2 r4636751965:** `ChunkBuffer` grows geometrically, so command-section copying is linear. +- **P2 r4636751970:** the personal token route honors `ARTIFACTS_TOKEN_TTL_SECONDS`; the test runtime now sets 900 s and asserts the expiry. + +Tests: prefix cap, cancel-on-abandon with a read-to-end control, `ChunkBuffer` copy bound for 1 MiB arriving one byte at a time, GC whole-pack drop before any read, base retention in both GC modes, a real-git rejected pack reclaimed under a 2 MiB budget, and the TTL route. Every guard was mutated once and its test went red; with exact-size growth the buffer test took 95 s and failed. diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md index ba91d00171..1666fdb7c5 100644 --- a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -8,7 +8,7 @@ The adversarial review of the push admission path in PR #2907 (H2, SAM-hosted gi - highly compressible blobs (14 blobs of 15 MiB stored in about 0.4 MiB); - more than 128 MiB of inflated pack content accumulated between collections. - GC then fails on every attempt, garbage packs are never reclaimed, and the repository drifts towards `maxRepoBytes`, where every push is refused. The reviewer reproduced this at 268 MB of a 268.4 MB cap. Raising the budget only moves the bound, since a compression bomb can exceed any inflation or deadline cap. + Since #2907, GC drops whole packs with nothing reachable and no delta base before inflating anything, so a rejected push's pack is always reclaimed. Migrating the reachable packed objects can still exceed the budget. GC then fails on every attempt, garbage mixed into reachable packs (after a force push) is never reclaimed, and the repository drifts towards `maxRepoBytes`, where every push is refused. The reviewer reproduced this at 268 MB of a 268.4 MB cap. Raising the budget only moves the bound, since a compression bomb can exceed any inflation or deadline cap. 2. **Delta depth is enforced on read but not at ingest** (review M4). `packstore.ts` resolves deltas eagerly at ingest without checking `maxDeltaDepth`, so a pack built with `--depth=250` is accepted. Cold reads then throw `delta chain exceeds depth`, and a shallow clone aborts with `early EOF` until GC rewrites the objects loose. The exception is thrown inside the upload response stream and is not caught. 3. **GC holds the input gate for the whole sweep** (review M5, the part not fixed in #2907). `gc()` runs under `blockConcurrencyWhile` for up to `workTimeoutMs` (120 s), blocking every other request to that repository, reads included. 4. **Pushes over heavy history without a reachable cache** (re-verification F1, the part not fixed in #2907). @@ -36,7 +36,7 @@ Who can trigger them: ## Acceptance Criteria -- [ ] GC reclaims unreachable packs without inflating reachable objects (copy raw pack entries, or drop packs whose objects no ref reaches), and completes for a repository whose reachable content inflates past `maxInflatedBytes`. A real-git test proves it. +- [ ] GC completes migration for a repository whose reachable packed content inflates past `maxInflatedBytes` (copy raw pack entries, or make migration resumable across alarms). A real-git test proves it. Whole unreferenced packs are already dropped without inflating. - [ ] GC work is deadline-bounded and resumable, with throughput stated at the 30,000-object / 256 MiB envelope (`.claude/rules/81-work-bounds-must-state-throughput.md`). - [ ] Ingest records delta depth and refuses a pack whose chains exceed `maxDeltaDepth`. A real-git test pushes `--depth=250` and is refused, and a normal pack is accepted. - [ ] Errors raised while streaming an upload-pack response end the stream cleanly. From 9d4887dd7ff995255fb979214bbde921070ca1c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:32:20 +0000 Subject: [PATCH 57/65] fix(selfhost): enforce the repository storage cap after the pack is stored Codex r4636923076: the push byte budget covered the raw pack but not its index rows and page overhead, so a push near maxRepoBytes could commit with the repository over its cap. processReceive re-checks dbSize() after ingest (rule 69: the final write enforces capacity); a push that crossed the cap is refused and its pack dropped at once. Co-Authored-By: Claude Opus 5.5 --- .../selfhost/hosted-git/hosted-git-repo.ts | 11 +++- apps/api/src/selfhost/hosted-git/limits.ts | 14 +++++ .../hosted-git/hosted-git-conformance.test.ts | 57 +++++++++++++++++++ deploy/selfhost/README.md | 2 + .../2026-11-19-selfhost-hosted-git-h2.md | 4 ++ 5 files changed, 87 insertions(+), 1 deletion(-) diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index 7f344694ba..b25b1b7e5b 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -51,6 +51,7 @@ import { hostedGitPushRefusal, hostedGitPushTooLargeMessage, hostedGitRefRefusal, + hostedGitStoredOverCapMessage, } from './limits'; import { resolveHostedGitLimits } from './policy'; import { HostedGitUploads } from './uploads'; @@ -408,7 +409,15 @@ export class HostedGitRepo extends DurableObject { flush: () => this.ctx.storage.sync(), collisionDetect: false, }); - packId = ingested.packId; + // Final reservation: the byte budget covered the raw pack, not its index rows and + // page overhead. Refuse the push and drop its pack if the stored total crossed the cap. + const stored = this.store.dbSize(); + if (stored > limits.maxRepoBytes) { + await this.store.packs.dropPack(ingested.packId); + unpackError = hostedGitStoredOverCapMessage(stored, limits); + } else { + packId = ingested.packId; + } } catch (err) { // Ingest writes chunks before checksum/index validation. Reclaim those rows now, // before the next push's quota check; retain an alarm if storage cleanup itself fails. diff --git a/apps/api/src/selfhost/hosted-git/limits.ts b/apps/api/src/selfhost/hosted-git/limits.ts index e11162c8d2..5e6ec6f77a 100644 --- a/apps/api/src/selfhost/hosted-git/limits.ts +++ b/apps/api/src/selfhost/hosted-git/limits.ts @@ -57,6 +57,20 @@ export function hostedGitPushRefusal( } /** The most bytes this push may stream: the push cap, or less when the repository is nearly full. */ +/** + * The refusal when a pack that fit the raw byte budget pushed stored size over the cap once its + * index rows and page overhead were written (enforced at the final write, after ingest). + */ +export function hostedGitStoredOverCapMessage( + storedBytes: number, + limits: HostedGitLimits +): string { + return ( + `SAM: push refused: storing this pack would bring this repository to ${mib(storedBytes)}, ` + + `over its ${mib(limits.maxRepoBytes)} storage limit` + ); +} + export function hostedGitPushByteBudget(currentBytes: number, limits: HostedGitLimits): number { return Math.max(0, Math.min(limits.maxPushBytes, limits.maxRepoBytes - currentBytes)); } diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 265ce9f930..70da22d1c8 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -876,6 +876,63 @@ describe('repository cleanup through real SQLite', () => { expect((await readFile(join(check, 'big.txt'), 'utf8')).length).toBe(5 * 1024 * 1024); }); + it('refuses and drops a pack whose index overhead takes stored size past the cap (Codex r4636923076)', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Cap at final write'); + const token = await mintToken(project, 'write'); + const work = await freshDir('cap-final'); + await gitOk(['clone', localRemote(project.repository, token), work]); + // Thousands of tiny objects: the index rows dwarf the compressed pack, beyond free pages. + await mkdir(join(work, 'many'), { recursive: true }); + for (let i = 0; i < 3000; i++) await writeFile(join(work, 'many', `f${i}`), `${i} ${randomBytes(4).toString('hex')}\n`); + await gitOk(['add', 'many'], work); + await gitOk(['commit', '-q', '-m', 'noise'], work); + const commit = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + const objects = (await gitOk(['rev-list', '--objects', commit, '^HEAD~1'], work)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(' ')[0]!); + const pack = spawnSync('git', ['pack-objects', '--stdout'], { + cwd: work, + input: `${objects.join('\n')}\n`, + maxBuffer: 16 * 1024 * 1024, + }).stdout; + const info = async () => + (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { bytes: number }; + const send = () => + runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, + body: buildReceivePackRequest(commit, 'noise', pack) as BodyInit, + }); + const setCap = async (cap: number) => { + await runtime.DATABASE.prepare( + "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxRepoBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value" + ) + .bind(JSON.stringify(cap), Date.now()) + .run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + }; + const before = await info(); + try { + // The raw pack fits the byte budget exactly; its index rows and pages do not. + await setCap(before.bytes + pack.length); + const refused = await (await send()).text(); + expect(refused).toContain('over its'); + expect(refused).toContain('storage limit'); + expect((await gitOk(['ls-remote', localRemote(project.repository, token)])).stdout).not.toContain( + 'refs/heads/noise' + ); + // The pack was dropped at once, not left holding bytes until GC. + expect((await info()).bytes).toBeLessThanOrEqual(before.bytes + pack.length); + // Control: with headroom for the index the same push is accepted. + await setCap(before.bytes + pack.length + 4 * 1024 * 1024); + expect(await (await send()).text()).toContain('ok refs/heads/noise'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxRepoBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + it('reclaims failed-ingest pack rows before the next push quota check', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Failed ingest'); const token = await mintToken(project, 'write'); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 87ae72b6ee..1fa2ac9230 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -219,6 +219,8 @@ push checks quota. Defaults are 64 MiB per push, 30,000 objects 10,000 refs and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation per request, delta depth 100 and 120 seconds per git operation. Operators can lower these limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. +The storage limit is checked again after a pack and its index are stored; a push that crosses it +is refused and its pack dropped at once. GC first drops whole packs that hold nothing reachable (for example a rejected push) without inflating them. Known limit: moving the remaining reachable packed objects to loose storage inflates each one under the same decompression budget, so that step cannot finish while more than diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md index fbe97e7f97..cfd86d61cc 100644 --- a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/active/2026-11-19-selfhost-hosted-git-h2.md @@ -150,3 +150,7 @@ Seven Codex findings were reconciled: - **P2 r4636751970:** the personal token route honors `ARTIFACTS_TOKEN_TTL_SECONDS`; the test runtime now sets 900 s and asserts the expiry. Tests: prefix cap, cancel-on-abandon with a read-to-end control, `ChunkBuffer` copy bound for 1 MiB arriving one byte at a time, GC whole-pack drop before any read, base retention in both GC modes, a real-git rejected pack reclaimed under a 2 MiB budget, and the TTL route. Every guard was mutated once and its test went red; with exact-size growth the buffer test took 95 s and failed. + +## Codex r4636923076 on 1bbf2aeb (01:00 UTC) + +The byte budget covered the raw pack, not its index rows and page overhead. Following rule 69, `processReceive` now re-checks `dbSize()` after ingest. A push that crossed the cap is refused, and its pack is dropped immediately with `dropPack`. Real-git test: 3,000 tiny objects with a cap of the current size plus the raw pack size is refused, and the ref and bytes are not kept. The control with headroom is accepted. Removing the check turns the test red. Main 20675016f, a workflow action bump, was merged. From fc56885676bb0996320d81cb9ba00e94b57db573 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:44:40 +0000 Subject: [PATCH 58/65] task: archive H2 hosted git with final BOX evidence Co-Authored-By: Claude Opus 5.5 --- tasks/{active => archive}/2026-11-19-selfhost-hosted-git-h2.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-19-selfhost-hosted-git-h2.md (100%) diff --git a/tasks/active/2026-11-19-selfhost-hosted-git-h2.md b/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md similarity index 100% rename from tasks/active/2026-11-19-selfhost-hosted-git-h2.md rename to tasks/archive/2026-11-19-selfhost-hosted-git-h2.md From dd22fb57277ba2c1ff580d71746bafb44a975aa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 00:44:53 +0000 Subject: [PATCH 59/65] task: record H2 final BOX evidence Co-Authored-By: Claude Opus 5.5 --- .../2026-11-19-selfhost-hosted-git-h2.md | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md b/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md index cfd86d61cc..f40e8dee0b 100644 --- a/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md +++ b/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md @@ -24,7 +24,8 @@ Use existing L16 selection, extend its optional token context and fetch/import c - [x] Draft PR then ready; CodeRabbit requested and explicit skip recorded; CI tracked below - [x] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off - [x] BOX existing bucket-mode deploy adds selfhost-hosted-git-v1; create project; OpenCode free reply; agent push verified; cleanup and BOX FREE -- [ ] Merge main; all gates current head; announce merging/merged SHA; production success; idea SHIPPED +- [x] Merge main (917077fef, then 20675016f); all gates on the current head +- [ ] Announce merging/merged SHA; production success; idea SHIPPED (tracked in the PR and on the channel) ## Acceptance @@ -94,8 +95,8 @@ Previous owner 01M7SR1B79 stopped after repeated provider content-filter refusal - Deferred with justification to `tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md`: MEDIUM-3 (GC inflates migrated objects under the same budget, so it cannot finish past 128 MiB of uncollected inflated content; needs a raw-copy GC redesign; documented as a known limit in the README), MEDIUM-4 (delta depth not checked at ingest; git defaults to 50), MEDIUM-5 rest (GC holds the input gate), LOW-7..10. Every deferred item needs a write token for that repository and is confined to it. - Tests: unit hosted-git-closure-walk (memo at 1201 commits / 2001 commands, parse errors) and hosted-git-push-admission (seeding reads zero tips at 1201 refs, edge types, branch rule, D/F, no-op delete, alarm arming); real git: mixed failing/valid sibling with cache, malformed commit, validation fault after ingest queues GC (one-shot read-fault hook), large tips under a 14 MiB budget, edge types, no-op delete and D/F. Every guard was mutated once and the intended tests went red (memo, parse catch, GC on throw, non-transactional walk, peel seeding, child-vs-parent blame, duplicate-edge check, D/F, branch rule, no-op delete, first-edge type). - Request-body helpers moved to `hosted-git-body.ts` so `hosted-git-repo.ts` stays under 500 lines; GC queueing is one helper (`queueHostedGitGc`, `armHostedGitGcAlarm`). -- [ ] Fresh CI green, 0 open threads, Codex re-requested on final head -- [ ] Final BOX smoke on the exact final head over main (closes the L22c "box from main runs an agent session" criterion deferred to H2 by Raphaël) +- [x] Codex reviews every push automatically; 15 findings across heads fixed or deferred with tracked follow-ups; 0 open threads +- [x] Final BOX smoke on 9d8a0802 (#2907 over main 20675016f), which closes the L22c "box from main runs an agent session" criterion Raphaël deferred to H2 ## Independent re-verification of f9eb945ef (23:20 UTC) @@ -154,3 +155,16 @@ Tests: prefix cap, cancel-on-abandon with a read-to-end control, `ChunkBuffer` c ## Codex r4636923076 on 1bbf2aeb (01:00 UTC) The byte budget covered the raw pack, not its index rows and page overhead. Following rule 69, `processReceive` now re-checks `dbSize()` after ingest. A push that crossed the cap is refused, and its pack is dropped immediately with `dropPack`. Real-git test: 3,000 tiny objects with a cap of the current size plus the raw pack size is refused, and the ref and bytes are not kept. The control with headroom is accepted. Removing the check turns the test red. Main 20675016f, a workflow action bump, was merged. + +## Final BOX smoke (00:30-00:45 UTC, 2026-11-20) + +The run used head 9d8a08029933863020011b6f0d0e7a62f12b3804. The only later commit moves this task file, so runtime is identical. +- **Upgrade:** in-place bucket-mode `pnpm selfhost:upgrade` from e7ac643b1, EXIT=0 and healthy, with no D1 migrations. The generated celld config has HostedGitRepo and the selfhost-hosted-git-v1 tag. +- **Project:** hosted-git project 01M7V67QTF30PEZ8G8EJ4SM8KX created 201, signed in as agent-test by email OTP through the box mail collector. +- **Agent:** task 01M7V681KWFSR8N9H33N5XPB71 (OpenCode, opencode/big-pickle, free) on a fresh node replied "pong" and pushed sam/ping-reply-pong-create-5xpb71. +- **Separate clone:** a cookie-free clone from the agent workspace with a read-scoped member token shows commit e7400ab74a65a152e842a99a2ebc8203d71751ae, h2-proof.txt = pong, and `git fsck --strict` passes. Unauthenticated info/refs returns 401. +- **Cleanup:** + - Resources: session stop 200, node DELETE 200, project DELETE 200 then 404; nodes [], repository 401, and the GCP inventory shows only sam-box. + - The box's standing agent-test credential from R18 was used, not changed. + - Session signed out, box scratch removed, own metadata key absent and firewall rule 404. + - The box was left healthy at 9d8a0802 with a clean checkout. BOX FREE posted at channel sequence 424. From af3009196fd6a2bd1f1d756152e9fe7914c5f399 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 02:04:19 +0000 Subject: [PATCH 60/65] fix(selfhost): resolve Codex findings on upload lists, token minting, caps, smoke - Deduplicate and cap upload-pack wants, haves and shallow lines while parsing, so a 16 MiB request cannot queue ~335k synchronous store lookups (r4637122054, r4637332208). - The personal clone/push token route refuses agent sign-in sessions, like other credential-minting routes (r4637122062). - The pre-parse request bound is the push limit plus the separately capped command section, so a lowered push limit still admits a packless deletion (r4637032838). - The final storage-cap check reserves the ref rows the push adds, through one helper shared with the ref-only admission check (r4637332217). - Drop the hosted-git smoke script's import path; import is unsupported in this slice (r4637032843). Co-Authored-By: Claude Opus 5.5 --- .../selfhost/hosted-git/hosted-git-repo.ts | 13 ++++- apps/api/src/selfhost/hosted-git/limits.ts | 21 ++++++- .../src/selfhost/hosted-git/token-route.ts | 5 +- apps/api/src/vendor/dgit/git/protocol.ts | 24 +++++++- .../hosted-git/hosted-git-conformance.test.ts | 32 +++++++++++ .../hosted-git/support/hosted-git-entry.ts | 57 +++++++++++++++---- .../hosted-git-push-admission.test.ts | 35 ++++++++++++ scripts/selfhost/hosted-git-smoke.sh | 13 ----- 8 files changed, 168 insertions(+), 32 deletions(-) diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index b25b1b7e5b..62733f4f75 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -47,6 +47,7 @@ import { import { filterLsRefsResponse, lsRefsPrefixes } from './hosted-git-ls-refs'; import { type HostedGitLimits, + hostedGitNewRefBytes, hostedGitPushByteBudget, hostedGitPushRefusal, hostedGitPushTooLargeMessage, @@ -291,7 +292,9 @@ export class HostedGitRepo extends DurableObject { private async receive(req: Request): Promise { const limits = await resolveHostedGitLimits(this.settingsEnv); const declared = parseInt(req.headers.get('content-length') ?? '', 10); - if (Number.isFinite(declared) && declared > limits.maxPushBytes) { + // The command section has its own cap (MAX_COMMAND_SECTION_BYTES) and ingest budgets the pack, + // so a lowered push limit still admits a packless deletion that frees space. + if (Number.isFinite(declared) && declared > limits.maxPushBytes + MAX_COMMAND_SECTION_BYTES) { return new Response(`error: ${hostedGitPushTooLargeMessage(limits.maxPushBytes)}\n`, { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' }, @@ -341,7 +344,10 @@ export class HostedGitRepo extends DurableObject { let body: ChunkBuffer; if (req.headers.get('content-encoding')?.includes('gzip')) { body = new ChunkBuffer( - gunzipLimited(await readBodyBounded(req, limits.maxPushBytes), limits.maxPushBytes) + gunzipLimited( + await readBodyBounded(req, limits.maxPushBytes + MAX_COMMAND_SECTION_BYTES), + limits.maxPushBytes + MAX_COMMAND_SECTION_BYTES + ) ); } else { reader = req.body?.getReader() ?? null; @@ -411,7 +417,8 @@ export class HostedGitRepo extends DurableObject { }); // Final reservation: the byte budget covered the raw pack, not its index rows and // page overhead. Refuse the push and drop its pack if the stored total crossed the cap. - const stored = this.store.dbSize(); + // The ref rows this push adds are written after this check, so reserve them here too. + const stored = this.store.dbSize() + hostedGitNewRefBytes(this.store.refs(), commands); if (stored > limits.maxRepoBytes) { await this.store.packs.dropPack(ingested.packId); unpackError = hostedGitStoredOverCapMessage(stored, limits); diff --git a/apps/api/src/selfhost/hosted-git/limits.ts b/apps/api/src/selfhost/hosted-git/limits.ts index 5e6ec6f77a..4370af6cfb 100644 --- a/apps/api/src/selfhost/hosted-git/limits.ts +++ b/apps/api/src/selfhost/hosted-git/limits.ts @@ -79,6 +79,25 @@ export function hostedGitPushTooLargeMessage(maxBytes: number): string { return `SAM: push refused: the pack is larger than the ${mib(maxBytes)} limit for one push to a SAM-hosted repository; push in smaller pieces`; } +/** SQLite page reserved for each new ref, including index overhead. */ +const REF_RESERVATION_BYTES = 4096; + +/** Bytes to reserve for the refs a push would create (deletions earn nothing). */ +export function hostedGitNewRefBytes( + existing: readonly { name: string }[], + commands: readonly { ref: string; next: string }[] +): number { + const refs = new Set(existing.map((ref) => ref.name)); + let additions = 0; + for (const command of commands) { + if (command.next !== '0'.repeat(40) && !refs.has(command.ref)) { + additions++; + refs.add(command.ref); + } + } + return additions * REF_RESERVATION_BYTES; +} + /** Check ref-only pushes too. Reserve a SQLite page per new ref, including index overhead. */ export function hostedGitRefRefusal( existing: readonly { name: string }[], @@ -101,7 +120,7 @@ export function hostedGitRefRefusal( if (!writes) return null; if (refs.size > limits.maxRepoRefs) return `SAM: push refused: repository exceeds its ${limits.maxRepoRefs}-ref limit`; - if (currentBytes + additions * 4096 >= limits.maxRepoBytes) + if (currentBytes + additions * REF_RESERVATION_BYTES >= limits.maxRepoBytes) return 'SAM: push refused: repository storage limit leaves no room for ref updates'; return null; } diff --git a/apps/api/src/selfhost/hosted-git/token-route.ts b/apps/api/src/selfhost/hosted-git/token-route.ts index 00050bb77e..b63e045621 100644 --- a/apps/api/src/selfhost/hosted-git/token-route.ts +++ b/apps/api/src/selfhost/hosted-git/token-route.ts @@ -11,7 +11,7 @@ import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; import * as schema from '../../db/schema'; -import { getUserId } from '../../middleware/auth'; +import { assertNotAgentSignInSession, getUserId } from '../../middleware/auth'; import { errors } from '../../middleware/error'; import { requireProjectCapability } from '../../middleware/project-auth'; import type { HostedGitEnv as Env } from './env'; @@ -21,6 +21,9 @@ import { mintHostedGitToken } from './tokens'; const hostedGitTokenRoutes = new Hono<{ Bindings: Env }>(); hostedGitTokenRoutes.post('/:id/hosted-git/token', async (c) => { + // A personal clone/push credential outlives the session that mints it, so an agent sign-in + // session (hard-expiring, workload identity) may not create one. + assertNotAgentSignInSession(c); const userId = getUserId(c); const projectId = c.req.param('id'); const scope = c.req.query('scope') === 'write' ? 'write' : 'read'; diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 893e6a1208..679e2b32a0 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -189,6 +189,12 @@ interface UploadRequest { caps: Set; } +/** + * SAM: most distinct wants, haves or shallow lines one upload request may list. Above SAM's + * 30,000-object and 10,000-ref repository caps, so no legitimate request reaches it. + */ +export const MAX_UPLOAD_OIDS = 32768; + export function parseUploadRequest(body: Uint8Array): UploadRequest { const parser = new PktParser(body); const req: UploadRequest = { @@ -200,6 +206,18 @@ export function parseUploadRequest(body: Uint8Array): UploadRequest { deepen: 0, caps: new Set(), }; + // SAM: each listed oid later costs a synchronous store lookup, so duplicates are dropped + // and each list is capped while parsing; a 16 MiB request could otherwise queue ~335k + // lookups. Past the cap extra haves/shallows are ignored (negotiation stays correct, the + // pack is just larger) and extra wants cannot be advertised refs anyway. + const seenWants = new Set(); + const seenHaves = new Set(); + const seenShallows = new Set(); + const addUnique = (list: string[], seen: Set, oid: string) => { + if (list.length >= MAX_UPLOAD_OIDS || seen.has(oid)) return; + seen.add(oid); + list.push(oid); + }; for (let p = parser.read(); p !== null; p = parser.read()) { if (p.kind !== "line") continue; const line = p.text; @@ -208,13 +226,13 @@ export function parseUploadRequest(body: Uint8Array): UploadRequest { } else if (line === "no-progress" || line === "symrefs" || line === "peel") { req.caps.add(line); } else if (line.startsWith("want ")) { - req.wants.push(line.slice(5, 45)); + addUnique(req.wants, seenWants, line.slice(5, 45)); // capabilities ride on the first want line for (const cap of line.slice(45).trim().split(" ")) if (cap) req.caps.add(cap); } else if (line.startsWith("have ")) { - req.haves.push(line.slice(5, 45)); + addUnique(req.haves, seenHaves, line.slice(5, 45)); } else if (line.startsWith("shallow ")) { - req.clientShallows.push(line.slice(8, 48)); + addUnique(req.clientShallows, seenShallows, line.slice(8, 48)); } else if (line.startsWith("deepen ")) { req.deepen = parseInt(line.slice(7), 10) || 0; } else if (line === "done") { diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 70da22d1c8..cf0aef5ffc 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -610,6 +610,13 @@ describe('member clone credentials (POST /api/projects/:id/hosted-git/token)', ( await gitOk(['commit', '-m', 'human'], work); await gitOk(['push', 'origin', 'HEAD'], work); + // An agent sign-in session cannot mint a credential that outlives it (Codex r4637122062). + const agentSession = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token?scope=read`, { + method: 'POST', + headers: { 'x-test-user-id': owner, 'x-test-agent-sign-in': '1' }, + }); + expect(agentSession.status).toBe(403); + const stranger = await createEmailOnlyUser(); const denied = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token`, { method: 'POST', @@ -876,6 +883,31 @@ describe('repository cleanup through real SQLite', () => { expect((await readFile(join(check, 'big.txt'), 'utf8')).length).toBe(5 * 1024 * 1024); }); + it('lets a packless ref deletion through a lowered push limit (Codex r4637032838)', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Delete under limit'); + const token = await mintToken(project, 'write'); + const work = await freshDir('delete-under-limit'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['push', 'origin', 'HEAD:refs/heads/to-delete'], work); + await runtime.DATABASE.prepare( + "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxPushBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value" + ) + .bind(JSON.stringify(1), Date.now()) + .run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + await gitOk(['push', 'origin', '--delete', 'to-delete'], work); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/to-delete'); + // Control: a push that carries a pack is still held to the 1-byte limit. + await gitOk(['commit', '--allow-empty', '-q', '-m', 'blocked'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/blocked'], work); + expect(refused.code).not.toBe(0); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxPushBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + it('refuses and drops a pack whose index overhead takes stored size past the cap (Codex r4636923076)', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Cap at final write'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index 75b4a2f6f9..5586663118 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -34,19 +34,33 @@ export class HostedGitRepoTest extends HostedGitRepo { await this.ctx.storage.deleteAlarm(); return new Response('ok'); } - if (new URL(req.url).pathname === '/__test/alarm' || new URL(req.url).pathname === '/__test/alarm-fail') { - const store = (this as unknown as { store: { get: (...args: unknown[]) => Promise } }).store; + if ( + new URL(req.url).pathname === '/__test/alarm' || + new URL(req.url).pathname === '/__test/alarm-fail' + ) { + const store = ( + this as unknown as { store: { get: (...args: unknown[]) => Promise } } + ).store; const get = store.get; - if (new URL(req.url).pathname.endsWith('-fail')) store.get = async () => { throw new Error('injected transient read failure'); }; + if (new URL(req.url).pathname.endsWith('-fail')) + store.get = async () => { + throw new Error('injected transient read failure'); + }; await this.ctx.storage.deleteAlarm(); - try { await this.alarm(); } finally { store.get = get; } + try { + await this.alarm(); + } finally { + store.get = get; + } return new Response('ok'); } if (new URL(req.url).pathname.startsWith('/__test/fail-read/')) { // One-shot: the next read of this object throws, as a storage fault or an exhausted work // budget would, so a push fails after its pack was ingested but before any ref decision. const oid = new URL(req.url).pathname.slice('/__test/fail-read/'.length); - const store = (this as unknown as { store: { get: (oid: string, ...rest: unknown[]) => Promise } }).store; + const store = ( + this as unknown as { store: { get: (oid: string, ...rest: unknown[]) => Promise } } + ).store; const get = store.get; store.get = async (target: string, ...rest: unknown[]) => { if (target !== oid) return get.call(store, target, ...rest); @@ -61,7 +75,12 @@ export class HostedGitRepoTest extends HostedGitRepo { return Response.json({ has: store.has(oid) }); } if (new URL(req.url).pathname === '/__test/gc-state') { - return Response.json({ pending: this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'").toArray()[0]?.value, alarm: await this.ctx.storage.getAlarm() }); + return Response.json({ + pending: this.ctx.storage.sql + .exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'") + .toArray()[0]?.value, + alarm: await this.ctx.storage.getAlarm(), + }); } return super.fetch(req); } @@ -74,7 +93,15 @@ const projects = new Hono<{ Bindings: Env }>(); projects.use('*', async (c, next) => { const userId = c.req.header('x-test-user-id'); if (!userId) return c.json({ error: 'UNAUTHORIZED' }, 401); - c.set('auth' as never, { user: { id: userId, role: 'user', status: 'active' } } as never); + // `x-test-agent-sign-in: 1` stands in for a workload-identity agent sign-in session. + const agentSignIn = c.req.header('x-test-agent-sign-in') === '1'; + c.set( + 'auth' as never, + { + user: { id: userId, role: 'user', status: 'active' }, + session: { id: `test-session-${userId}`, agentSignIn, hardExpiresAt: null }, + } as never + ); await next(); }); registerProjectCreateRoute(projects); @@ -129,20 +156,28 @@ app.get('/__test/gc-state/:repo', async (c) => { }); app.delete('/__test/repository/:repo', async (c) => { const ns = c.env.HOSTED_GIT!; - return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/', { method: 'DELETE' }); + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch('https://hosted-git/', { method: 'DELETE' }); }); app.get('/__test/has/:repo/:oid', (c) => { const ns = c.env.HOSTED_GIT!; - return ns.get(ns.idFromName(c.req.param('repo'))).fetch(`https://hosted-git/__test/has/${c.req.param('oid')}`); + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch(`https://hosted-git/__test/has/${c.req.param('oid')}`); }); app.post('/__test/fail-read/:repo/:oid', (c) => { const ns = c.env.HOSTED_GIT!; - return ns.get(ns.idFromName(c.req.param('repo'))).fetch(`https://hosted-git/__test/fail-read/${c.req.param('oid')}`); + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch(`https://hosted-git/__test/fail-read/${c.req.param('oid')}`); }); app.post('/__test/alarm/:repo/:mode', (c) => { const ns = c.env.HOSTED_GIT!; - return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/alarm' + (c.req.param('mode') === 'fail' ? '-fail' : '')); + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch('https://hosted-git/__test/alarm' + (c.req.param('mode') === 'fail' ? '-fail' : '')); }); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 1ea318fe6d..7595de7761 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -751,3 +751,38 @@ describe('GC reclaims packs without inflating and drops delta-only bases', () => expect(kept.loose.has(kept.ids.b1)).toBe(true); }); }); + +describe('upload request lists and ref reservations', () => { + it('deduplicates and caps wants, haves and shallow lines while parsing (Codex r4637122054, r4637332208)', async () => { + const { MAX_UPLOAD_OIDS, parseUploadRequest } = + await import('../../../src/vendor/dgit/git/protocol'); + const { pkt, FLUSH } = await import('../../../src/vendor/dgit/git/pktline'); + const { concat } = await import('../../../src/vendor/dgit/git/util'); + const a = 'a'.repeat(40); + const lines = [pkt(`want ${a} side-band-64k\n`)]; + for (let i = 0; i < 1000; i++) + lines.push(pkt(`want ${a}\n`), pkt(`have ${a}\n`), pkt(`shallow ${a}\n`)); + for (let i = 0; i < MAX_UPLOAD_OIDS + 5; i++) + lines.push(pkt(`have ${i.toString(16).padStart(40, '0')}\n`)); + const req = parseUploadRequest(concat([...lines, FLUSH])); + expect(req.wants).toEqual([a]); + expect(req.clientShallows).toEqual([a]); + expect(req.haves).toHaveLength(MAX_UPLOAD_OIDS); + expect(new Set(req.haves).size).toBe(MAX_UPLOAD_OIDS); + expect(req.caps.has('side-band-64k')).toBe(true); + }); + + it('reserves a page per new ref and nothing for updates or deletions (Codex r4637332217)', async () => { + const { hostedGitNewRefBytes } = await import('../../../src/selfhost/hosted-git/limits'); + const existing = [{ name: 'refs/heads/main' }]; + expect( + hostedGitNewRefBytes(existing, [ + { ref: 'refs/heads/main', next: 'b'.repeat(40) }, + { ref: 'refs/heads/new', next: 'c'.repeat(40) }, + { ref: 'refs/heads/new', next: 'd'.repeat(40) }, + { ref: 'refs/heads/gone', next: ZERO }, + { ref: 'refs/tags/v1', next: 'e'.repeat(40) }, + ]) + ).toBe(2 * 4096); + }); +}); diff --git a/scripts/selfhost/hosted-git-smoke.sh b/scripts/selfhost/hosted-git-smoke.sh index e9e18030b2..c9fa5d6090 100755 --- a/scripts/selfhost/hosted-git-smoke.sh +++ b/scripts/selfhost/hosted-git-smoke.sh @@ -8,8 +8,6 @@ # SAM_API_TOKEN an API token of an email-only account (Settings -> API tokens), exchanged # for a session cookie via POST /api/auth/token-login. Never printed. # SAM_INSECURE=1 optional: skip TLS verification (SAM_TLS_MODE=internal boxes) -# SMOKE_IMPORT_URL optional: also create a project imported from this public repository -# (github.com, gitlab.com, codeberg.org or bitbucket.org), then clone it # SMOKE_RUN_TASK=1 optional: also submit an agent task that commits and pushes a branch from # a workspace, then wait for that branch (SMOKE_TASK_TIMEOUT_S, default 1200) # @@ -77,17 +75,6 @@ step "unauthenticated clone is refused" if "${GIT[@]}" clone -q "$remote" "${WORK}/anon" 2>/dev/null; then fail "anonymous clone succeeded"; fi echo "refused as expected" -if [[ -n "${SMOKE_IMPORT_URL:-}" ]]; then - step "import ${SMOKE_IMPORT_URL}" - imported="$(python3 -c 'import json,os,sys; print(json.dumps({"name": sys.argv[1], "repoProvider": "artifacts", "importUrl": os.environ["SMOKE_IMPORT_URL"]}))' "${name}-import" | - "${CURL[@]}" -X POST -H 'content-type: application/json' --data @- "${API}/api/projects")" - imported_id="$(json "['id']" <<<"$imported")" - imported_remote="$(json "['repository']" <<<"$imported")" - itoken="$("${CURL[@]}" -X POST "${API}/api/projects/${imported_id}/hosted-git/token" | json "['token']")" - "${GIT[@]}" clone -q "$(authed "$imported_remote" "$itoken")" "${WORK}/imported" - echo "imported HEAD $(git -C "${WORK}/imported" log -1 --format='%h %s')" -fi - if [[ "${SMOKE_RUN_TASK:-}" == "1" ]]; then step "workspace task clones and pushes (provisions a node; minutes)" "${CURL[@]}" -X POST -H 'content-type: application/json' \ From 7b2b41f56693debfc3656109c715c58d88b972aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 02:26:11 +0000 Subject: [PATCH 61/65] fix(selfhost): screen pushed objects with SHA-1 collision detection Push ingest hashed objects with collision detection off, so an object carrying a SHA-1 collision-attack block could be admitted under its colliding oid. Enable the vendored SHA-1DC for untrusted pushes, as git does; the push is refused before any ref changes. Cost: ~130 MiB/s, bounded by maxInflatedBytes (about 1 s at the cap). Tests: the detector flags both SHAttered blocks and not a one-bit control; a real git push whose object SHA-1DC flags is refused with no ref, and an unflagged retry is accepted. The push test fails with detection off. Co-Authored-By: Claude Opus 5.5 --- .../selfhost/hosted-git/hosted-git-repo.ts | 6 +- .../hosted-git/hosted-git-conformance.test.ts | 21 +++++++ .../hosted-git/support/hosted-git-entry.ts | 47 ++++++++++++++++ .../unit/selfhost/hosted-git-sha1dc.test.ts | 55 +++++++++++++++++++ deploy/selfhost/README.md | 2 + 5 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts index 62733f4f75..2c593be723 100644 --- a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -413,7 +413,11 @@ export class HostedGitRepo extends DurableObject { cache: new ObjCache(INGEST_CACHE_BYTES), onProgress: progress, flush: () => this.ctx.storage.sync(), - collisionDetect: false, + // Pushes are untrusted: screen every object with SHA-1DC as git does, so an object + // carrying a collision-attack block is refused before any ref can point at it. The + // JS hasher runs at about 130 MiB/s; inflated bytes per push are already capped by + // maxInflatedBytes (128 MiB default), so this adds about 1 s at the cap. + collisionDetect: true, }); // Final reservation: the byte budget covered the raw pack, not its index rows and // page overhead. Refuse the push and drop its pack if the stored total crossed the cap. diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index cf0aef5ffc..7695547729 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -1276,6 +1276,27 @@ describe('push connectivity admission (closure must be complete per command)', ( await assertCleanClone(remote); }); + it('refuses a push whose object SHA-1DC flags as a collision attack, before any ref', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Collision screen'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('collision'); + await gitOk(['clone', remote, work]); + await commitFile(work, 'collide.txt'); + const blob = await rev(work, 'HEAD:collide.txt'); + // The detector's verdict for this one object is forced (see flagCollisionOnce): a real git + // object cannot carry the published SHAttered blocks. + await runtime.fetch(`/__test/flag-collision/${project.artifactsRepoId}/${blob}`, { method: 'POST' }); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/collide'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain(`object ${blob.slice(0, 12)} triggered SHA-1 collision detection`); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/collide'); + expect((await gcState(project)).pending).toBe('1'); + // Control: the same push, unflagged, is accepted, so the refusal came from the detector alone. + await gitOk(['push', 'origin', 'HEAD:refs/heads/collide'], work); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).toContain('refs/heads/collide'); + }); + it('queues GC for an ingested pack when validation fails before any ref decision', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Closure validate fault'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts index 5586663118..1b51e2757c 100644 --- a/apps/api/tests/hosted-git/support/hosted-git-entry.ts +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -22,6 +22,42 @@ import { hostedGitTokenRoutes } from '../../../src/selfhost/hosted-git/token-rou import { type HostedGitScope, mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; import { invalidateAdminSettings } from '../../../src/services/admin-settings-resolution'; import { signCurrentWorkspaceCallbackToken } from '../../../src/services/jwt'; +import { Sha1Dc } from '../../../src/vendor/dgit/git/sha1'; + +/** + * Test-only: SHA-1DC reports a collision for the next object hashed to `target`. A real git + * object cannot carry a published collision (its `type size\0` header shifts the attack blocks + * off the chaining state they were built for), so this stands in for the detector's verdict; + * tests/unit/selfhost/hosted-git-sha1dc.test.ts proves the detector on the SHAttered blocks. + * The flag reaches push ingest only when it hashes through SHA-1DC: with collision detection + * off, objects hash through crypto.subtle and this hook is never consulted. + */ +function flagCollisionOnce(target: string): void { + const proto = Sha1Dc.prototype as unknown as { + digest: (this: object) => Uint8Array; + }; + const collision = Object.getOwnPropertyDescriptor(Sha1Dc.prototype, 'collision')!; + const digest = proto.digest; + const restore = () => { + proto.digest = digest; + Object.defineProperty(Sha1Dc.prototype, 'collision', collision); + }; + const flagged = new WeakSet(); + proto.digest = function (this: object) { + const out = digest.call(this); + if (Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('') === target) + flagged.add(this); + return out; + }; + Object.defineProperty(Sha1Dc.prototype, 'collision', { + configurable: true, + get(this: object) { + if (!flagged.has(this)) return collision.get!.call(this) as boolean; + restore(); + return true; + }, + }); +} /** Test-only: run the GC alarm on demand (production schedules it 5 minutes after a push). */ export class HostedGitRepoTest extends HostedGitRepo { @@ -69,6 +105,10 @@ export class HostedGitRepoTest extends HostedGitRepo { }; return new Response('ok'); } + if (new URL(req.url).pathname.startsWith('/__test/flag-collision/')) { + flagCollisionOnce(new URL(req.url).pathname.slice('/__test/flag-collision/'.length)); + return new Response('ok'); + } if (new URL(req.url).pathname.startsWith('/__test/has/')) { const oid = new URL(req.url).pathname.slice('/__test/has/'.length); const store = (this as unknown as { store: { has: (oid: string) => boolean } }).store; @@ -175,6 +215,13 @@ app.post('/__test/fail-read/:repo/:oid', (c) => { .fetch(`https://hosted-git/__test/fail-read/${c.req.param('oid')}`); }); +app.post('/__test/flag-collision/:repo/:oid', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch(`https://hosted-git/__test/flag-collision/${c.req.param('oid')}`); +}); + app.post('/__test/alarm/:repo/:mode', (c) => { const ns = c.env.HOSTED_GIT!; return ns diff --git a/apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts b/apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts new file mode 100644 index 0000000000..44be01876e --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts @@ -0,0 +1,55 @@ +import { createHash } from 'node:crypto'; + +import { describe, expect, it } from 'vitest'; + +import { Sha1Dc } from '../../../src/vendor/dgit/git/sha1'; + +/** + * The vendored SHA-1DC detector that hosted-git push ingest screens every object with + * (`collisionDetect: true` in hosted-git-repo.ts). The fixtures are the first 320 bytes of the + * two SHAttered PDFs (shattered.io, also git's t/t0013): a shared prefix and the two + * near-collision blocks, which hash to the same SHA-1. tests/hosted-git covers the push path. + */ +const SHATTERED_1 = + 'JVBERi0xLjMKJeLjz9MKCgoxIDAgb2JqCjw8L1dpZHRoIDIgMCBSL0hlaWdodCAzIDAgUi9UeXBlIDQgMCBSL1N1YnR5cGUgNSAwIFIvRmlsdGVyIDYgMCBSL0NvbG9yU3BhY2UgNyAwIFIvTGVuZ3RoIDggMCBSL0JpdHNQZXJDb21wb25lbnQgOD4+CnN0cmVhbQr/2P/+ACRTSEEtMSBpcyBkZWFkISEhISGFL+wJIzl1nDmxocY8TJfh//4Bc0bckWa2fhGPApq2IbJWD/nKZ8yox/hbqEx5AwwrPeIY+G2zqQkB1d9FwU8m/t+z3DjpasIv571yjw5FvOBG0jxXD+sUE5i7VS71oKgr4zH+pIA3uLXXHw4zLt+TrDUA603cDezBqGR5DHgsdiFWYN0wl5HQa9CvP5jNpLxGKbE='; +const SHATTERED_2 = + 'JVBERi0xLjMKJeLjz9MKCgoxIDAgb2JqCjw8L1dpZHRoIDIgMCBSL0hlaWdodCAzIDAgUi9UeXBlIDQgMCBSL1N1YnR5cGUgNSAwIFIvRmlsdGVyIDYgMCBSL0NvbG9yU3BhY2UgNyAwIFIvTGVuZ3RoIDggMCBSL0JpdHNQZXJDb21wb25lbnQgOD4+CnN0cmVhbQr/2P/+ACRTSEEtMSBpcyBkZWFkISEhISGFL+wJIzl1nDmxocY8TJfh//4Bf0bck6a2fgE7ApqqHbJWC0XKZ9aIx/hLjEx5H+ArPfYU+G2xaQkBxWtFwVMK/t+3YDjpcnIv561yjw5JBOBGwjBXD+nUE5ir4S71vJQr4zVCpIAtmLXXDyozLsN/rDUU503cDyzBqHTNDHgwWiFWZGEwl4lga9C/P5jNqARGKaE='; + +const bytes = (b64: string) => new Uint8Array(Buffer.from(b64, 'base64')); + +function hash(data: Uint8Array): { oid: string; collision: boolean } { + const h = new Sha1Dc().reset().update(data); + const oid = Buffer.from(h.digest()).toString('hex'); + return { oid, collision: h.collision }; +} + +describe('SHA-1DC collision detection', () => { + it('flags both halves of the SHAttered collision without changing the SHA-1', () => { + const one = bytes(SHATTERED_1); + const two = bytes(SHATTERED_2); + expect(Buffer.from(one).equals(Buffer.from(two))).toBe(false); + const a = hash(one); + const b = hash(two); + expect(a.oid).toBe(b.oid); + expect(a.oid).toBe(createHash('sha1').update(one).digest('hex')); + expect(a.collision).toBe(true); + expect(b.collision).toBe(true); + }); + + it('does not flag the same bytes with one bit changed in a collision block', () => { + const data = bytes(SHATTERED_1); + data[200]! ^= 1; + const h = hash(data); + expect(h.collision).toBe(false); + expect(h.oid).toBe(createHash('sha1').update(data).digest('hex')); + }); + + it('resets the verdict between objects', () => { + const h = new Sha1Dc().reset().update(bytes(SHATTERED_1)); + h.digest(); + expect(h.collision).toBe(true); + h.reset().update(new TextEncoder().encode('blob 6\0hello\n')); + h.digest(); + expect(h.collision).toBe(false); + }); +}); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index ab8c36ed12..afe606c491 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -220,6 +220,8 @@ per request, delta depth 100 and 120 seconds per git operation. Operators can lo limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. The storage limit is checked again after a pack and its index are stored; a push that crosses it is refused and its pack dropped at once. +Like git, push ingest hashes every object with SHA-1 collision detection (SHA-1DC) and refuses +a push carrying a SHA-1 collision-attack block before any ref changes. GC first drops whole packs that hold nothing reachable (for example a rejected push) without inflating them. Known limit: moving the remaining reachable packed objects to loose storage inflates each one under the same decompression budget, so that step cannot finish while more than From e04adb9c42a50cf29bd984eedd1cf184355ebe77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 02:30:03 +0000 Subject: [PATCH 62/65] test(selfhost): cover SHA-1DC on delta-resolved push objects Security delta LOW 1: the collision push test covered only the buffered full-object path. A thin-pack edit of a large file now pushes a delta-resolved blob that SHA-1DC flags; the push is refused with no ref. Reverting cd on the two delta hash sites alone turns the test red. Co-Authored-By: Claude Opus 5.5 --- .../hosted-git/hosted-git-conformance.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 7695547729..06f19e543e 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -1295,6 +1295,22 @@ describe('push connectivity admission (closure must be complete per command)', ( // Control: the same push, unflagged, is accepted, so the refusal came from the detector alone. await gitOk(['push', 'origin', 'HEAD:refs/heads/collide'], work); expect((await gitOk(['ls-remote', 'origin'], work)).stdout).toContain('refs/heads/collide'); + + // A delta-resolved object is screened too: git sends this edit of a large file as a thin-pack + // delta against the blob the server already has. + const big = Array.from({ length: 400 }, (_, i) => `line ${i} ${'x'.repeat(40)}`).join('\n'); + await writeFile(join(work, 'big.txt'), `${big}\n`); + await gitOk(['add', 'big.txt'], work); + await gitOk(['commit', '-m', 'big'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/collide'], work); + await writeFile(join(work, 'big.txt'), `${big}\nappended\n`); + await gitOk(['commit', '-am', 'edit'], work); + const edited = await rev(work, 'HEAD:big.txt'); + await runtime.fetch(`/__test/flag-collision/${project.artifactsRepoId}/${edited}`, { method: 'POST' }); + const deltaRefused = await git(['push', 'origin', 'HEAD:refs/heads/collide-delta'], work); + expect(deltaRefused.code).not.toBe(0); + expect(deltaRefused.stderr).toContain(`object ${edited.slice(0, 12)} triggered SHA-1 collision detection`); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/collide-delta'); }); it('queues GC for an ingested pack when validation fails before any ref decision', async () => { From 023a40e68f505faa11aabf0ac9d0181b46d97645 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 02:33:07 +0000 Subject: [PATCH 63/65] task: record SHA-1DC ingest LOW notes in hosted-git hardening backlog Co-Authored-By: Claude Opus 5.5 --- .../backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md index 1666fdb7c5..3ddd12a25b 100644 --- a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -23,6 +23,9 @@ The adversarial review of the push admission path in PR #2907 (H2, SAM-hosted gi - **Command lines dropped silently.** Unmatched command pkt-lines are skipped with no `ng`, and invalid UTF-8 ref bytes alias to U+FFFD. - **Gzip buffering.** The gzip push path buffers about 3× `maxPushBytes`. - **Quadratic copying.** `need()` concatenates repeatedly while reading the command section. +7. **SHA-1DC ingest notes** (security delta review of the SHA-1DC change in #2907): + - **Shared streaming hasher.** The streamed full-object path in `packstore.ts` feeds the module-level `streamSha` across awaits, so a concurrent ingest in the same isolate could reset it mid-object. This is unreachable on celld today: `maxObjectBytes` (16 MiB max) is below the 32 MiB streaming threshold. Use a per-entry `Sha1Dc` before either limit changes. + - **R2 raw object leak.** If an R2-backed ingest fails before it writes any pack rows, `cleanupOrphans` cannot find the raw object. The problem predates the SHA-1DC change, and celld stores packs in SQLite. ## Context @@ -46,4 +49,5 @@ Who can trigger them: - [ ] A push forking from an old, heavy commit succeeds within the budget. A real-git test proves it, and a stale or poisoned cache cannot vouch for a missing object. - [ ] Decide whether to bound tree depth or total path length; 1,500 nested directories break checkout of the default branch. - [ ] Optionally accept uppercase-hex oids in commit and tag headers, as git does (`isOid` is lowercase-only). +- [ ] Give the streamed ingest path its own SHA-1DC hasher, and reclaim R2 raw objects of packs that fail before any rows (item 7). - [ ] Optionally reject the remaining fsck error-level shapes that default clients tolerate but `transfer.fsckObjects=true` clients refuse: unsorted trees, malformed idents, CR in headers. From ee54ce19b69f46902f338baf9eb0c22cee29cd92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 02:45:29 +0000 Subject: [PATCH 64/65] fix(projects): reject default branches git refuses with a 400 A default branch that passed the character check but not git check-ref-format (foo.lock, .hidden, a..b, trailing.) initialized the hosted repository, then the seed push was refused as a funny refname and project creation returned 500. Move the push validator's ref-name rules into lib/git-ref-name.ts (no deps, safe for the Worker graph) and use the same predicate in project creation, so a branch SAM accepts can always be pushed. The conformance test creates projects with each name (400, no project row) and a nested-branch control that seeds and serves; it returns 500 with the route guard removed. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/lib/git-ref-name.ts | 32 +++++++++++++++++ .../api/src/routes/projects/project-create.ts | 8 +++++ apps/api/src/vendor/dgit/UPSTREAM.md | 2 +- apps/api/src/vendor/dgit/git/protocol.ts | 10 ++---- .../hosted-git/hosted-git-conformance.test.ts | 33 +++++++++++++++++ apps/api/tests/unit/lib/git-ref-name.test.ts | 35 +++++++++++++++++++ 6 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 apps/api/src/lib/git-ref-name.ts create mode 100644 apps/api/tests/unit/lib/git-ref-name.test.ts diff --git a/apps/api/src/lib/git-ref-name.ts b/apps/api/src/lib/git-ref-name.ts new file mode 100644 index 0000000000..2a2f844c5e --- /dev/null +++ b/apps/api/src/lib/git-ref-name.ts @@ -0,0 +1,32 @@ +/** + * Git ref-name admission shared by hosted-git push validation (`validatePush` in the vendored + * dgit protocol) and project creation, which names the branch the seed push writes. One + * predicate, so a branch SAM accepts can always be pushed. + * + * Rules follow `git check-ref-format` (https://git-scm.com/docs/git-check-ref-format) plus SAM's + * conservative bounds: no whitespace, control, quote or HTML characters and at most 255 + * characters in total. This module has no dependencies, so the Worker graph may import it. + */ +// eslint-disable-next-line no-control-regex -- git check-ref-format rejects ASCII control bytes +const BAD_REF_CHARS = /[\s~^:?*[\\'"<>&`\x00-\x1f\x7f]/; +const MAX_REF_NAME_LENGTH = 255; + +/** True when `ref` (a full name such as `refs/heads/main`) is a ref name git and SAM accept. */ +export function isValidGitRefName(ref: string): boolean { + return ( + ref.startsWith('refs/') && + ref.length <= MAX_REF_NAME_LENGTH && + !ref.includes('..') && + !BAD_REF_CHARS.test(ref) && + !ref.includes('@{') && + !ref.includes('//') && + !ref.endsWith('/') && + !ref.endsWith('.') && + !ref.split('/').some((c) => c.startsWith('.') || c.endsWith('.lock')) + ); +} + +/** True when `branch` (a short name such as `main`) names a valid `refs/heads/` ref. */ +export function isValidGitBranchName(branch: string): boolean { + return branch.length > 0 && isValidGitRefName(`refs/heads/${branch}`); +} diff --git a/apps/api/src/routes/projects/project-create.ts b/apps/api/src/routes/projects/project-create.ts index 672851fb90..400f06226a 100644 --- a/apps/api/src/routes/projects/project-create.ts +++ b/apps/api/src/routes/projects/project-create.ts @@ -6,6 +6,7 @@ import { type Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; +import { isValidGitBranchName } from '../../lib/git-ref-name'; import { log } from '../../lib/logger'; import { toProjectResponse } from '../../lib/mappers'; import { ulid } from '../../lib/ulid'; @@ -127,6 +128,13 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): 'defaultBranch contains invalid characters. Only alphanumeric, hyphens, underscores, slashes, and dots are allowed (max 255 chars).' ); } + // The repository's first push writes this branch; refuse names git itself rejects + // (`foo.lock`, `.hidden`, `a..b`, `trailing.`) here rather than fail the seed push. + if (!isValidGitBranchName(defaultBranch)) { + throw errors.badRequest( + 'defaultBranch is not a valid git branch name (see git check-ref-format).' + ); + } // Create Artifacts repo — name includes projectId for uniqueness. // Must be sanitized: Artifacts rejects uppercase/spaces (the ULID projectId diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index f7d5d5dd07..b5fed53504 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -35,7 +35,7 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - PackStore exposes its existing incomplete-pack sweep as `cleanupOrphans`, so failed uploads can reclaim quota immediately and GC can retry storage cleanup independently of another admitted push. -- Ref admission rejects `.lock` suffixes on every path component and a final dot, matching Git check-ref-format; the full rule matrix also retains SAM conservative character and length bounds. +- Ref admission rejects `.lock` suffixes on every path component and a final dot, matching Git check-ref-format; the full rule matrix also retains SAM conservative character and length bounds. The predicate lives in `apps/api/src/lib/git-ref-name.ts` (`isValidGitRefName`), which project creation also uses, so a default branch SAM accepts can always be pushed. - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 679e2b32a0..9bcf9467e0 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -5,6 +5,7 @@ import { concat, isOid, ZERO_OID, te } from "./util"; import { pkt, FLUSH, PktParser } from "./pktline"; import { GitStore } from "./store"; import { PackWriter } from "./pack"; +import { isValidGitRefName } from "../../../lib/git-ref-name"; import { OidSet } from "./oidset"; import { MultipartCapture, MultipartPackUpload } from "./multipart"; import { GitParseError, parseCommit, parseTag, parseTree, isGitlinkMode, isTreeMode, TYPE_NUM, NUM_TYPE, ObjType } from "./objects"; @@ -1125,9 +1126,6 @@ export function parsePushCommands(section: Uint8Array): { commands: PushCommand[ return { commands, caps }; } -/** Characters git's check_ref_format rejects, plus HTML-dangerous ones. */ -const BAD_REF = /[\s~^:?*\[\\'"<>&`\x00-\x1f\x7f]/; - /** * Every object in the closure of `tip` is present, so setting a ref to it * cannot brick the repo. A thin/broken pack that fails to close over its new @@ -1496,11 +1494,7 @@ export async function validatePush( decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "unpacker error" }); continue; } - const bad = !cmd.ref.startsWith("refs/") || cmd.ref.includes("..") || BAD_REF.test(cmd.ref) - || cmd.ref.endsWith(".lock") || cmd.ref.includes("@{") || cmd.ref.includes("//") - || cmd.ref.endsWith("/") || cmd.ref.endsWith(".") || cmd.ref.length > 255 - || cmd.ref.split("/").some((c) => c.startsWith(".") || c.endsWith(".lock")); - if (bad) { + if (!isValidGitRefName(cmd.ref)) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "funny refname" }); continue; } diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index 06f19e543e..a825d0ff4e 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -1276,6 +1276,39 @@ describe('push connectivity admission (closure must be complete per command)', ( await assertCleanClone(remote); }); + it('refuses a default branch git rejects with a 400, before any repository exists', async () => { + const userId = await createEmailOnlyUser(); + const create = (defaultBranch: string) => + runtime.fetch('/api/projects', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test-user-id': userId }, + body: JSON.stringify({ name: `Branch ${defaultBranch}`, repoProvider: 'artifacts', defaultBranch }), + }); + for (const branch of ['foo.lock', '.hidden', 'a..b', 'trailing.']) { + const res = await create(branch); + const body = await res.text(); + expect(res.status, `${branch}: ${body}`).toBe(400); + expect(body).toContain('not a valid git branch name'); + } + const projects = await runtime.DATABASE.prepare('SELECT count(*) AS n FROM projects WHERE user_id = ?') + .bind(userId) + .first<{ n: number }>(); + expect(projects?.n).toBe(0); + // Control: a nested branch name that passes check-ref-format creates and seeds the repository. + const ok = await create('feature/seeded'); + expect(ok.status, await ok.clone().text()).toBe(201); + const { id } = (await ok.json()) as { id: string }; + const row = await runtime.DATABASE.prepare( + 'SELECT repository, artifacts_repo_id AS repo, default_branch AS branch FROM projects WHERE id = ?' + ) + .bind(id) + .first<{ repository: string; repo: string; branch: string }>(); + expect(row?.branch).toBe('feature/seeded'); + const token = await mintToken({ artifactsRepoId: row!.repo, ownerId: userId }, 'read'); + const refs = await gitOk(['ls-remote', localRemote(row!.repository, token)]); + expect(refs.stdout).toContain('refs/heads/feature/seeded'); + }); + it('refuses a push whose object SHA-1DC flags as a collision attack, before any ref', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Collision screen'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/unit/lib/git-ref-name.test.ts b/apps/api/tests/unit/lib/git-ref-name.test.ts new file mode 100644 index 0000000000..9813048d2f --- /dev/null +++ b/apps/api/tests/unit/lib/git-ref-name.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; + +import { isValidGitBranchName, isValidGitRefName } from '../../../src/lib/git-ref-name'; + +describe('git ref-name admission', () => { + it.each(['main', 'feature/x', 'sam/fix-123', 'release-2026.11', 'v1.0/hotfix', 'a.b'])( + 'accepts branch %s', + (branch) => { + expect(isValidGitBranchName(branch)).toBe(true); + } + ); + + it.each([ + ['foo.lock', 'a .lock component'], + ['dir.lock/x', 'an intermediate .lock component'], + ['.hidden', 'a component starting with a dot'], + ['x/.hidden', 'a later component starting with a dot'], + ['a..b', 'two consecutive dots'], + ['trailing.', 'a trailing dot'], + ['trailing/', 'a trailing slash'], + ['a//b', 'an empty component'], + ['a@{b', 'the @{ sequence'], + ['has space', 'whitespace'], + ['a~b', 'a check-ref-format metacharacter'], + ['', 'an empty name'], + ['x'.repeat(250), 'more than 255 characters as a full ref'], + ])('rejects %j (%s)', (branch) => { + expect(isValidGitBranchName(branch)).toBe(false); + }); + + it('requires a full ref under refs/', () => { + expect(isValidGitRefName('refs/heads/main')).toBe(true); + expect(isValidGitRefName('heads/main')).toBe(false); + }); +}); From f433bb941419f869c21ebad4979dac2433fd3665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 03:14:56 +0000 Subject: [PATCH 65/65] fix(selfhost): refuse every command for a ref a push names twice A raw push could update refs/heads/a, delete refs/heads/a with the old value, and create refs/heads/a/b. The D/F pre-pass freed 'a' for the matching delete, so a/b was accepted; at commit the update won and the delete lost its CAS, leaving both refs stored, which breaks clones. As git refuses multiple updates of one ref in a transaction, every command for a duplicated ref is now refused, and those deletes free no name. Tests: unit (validate + commit, refs unchanged) and real receive-pack (ng for both a commands and a/b, clean clone); both go red with duplicate detection removed. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/vendor/dgit/UPSTREAM.md | 2 +- apps/api/src/vendor/dgit/git/protocol.ts | 19 +++++++++++++- .../hosted-git/hosted-git-conformance.test.ts | 25 +++++++++++++++++++ .../hosted-git-push-admission.test.ts | 22 ++++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md index b5fed53504..ef544b9276 100644 --- a/apps/api/src/vendor/dgit/UPSTREAM.md +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -39,7 +39,7 @@ SQL identifiers use static allowlisted statements, and variable-sized bind lists - Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. -- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts, rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink in any of its NTFS forms); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts (a ref named by more than one command is refused for all of them, so a deletion that would lose its CAS cannot free a nested name), rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink in any of its NTFS forms); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. - The reachable cache is stamped only with the ref version its clone walk started from, unstamps the cache before rewriting it, and lets only the latest of overlapping saves write or stamp; `commitPush` extends the cache only if it is still stamped current at commit time. A push during a clone walk, a second clone's rewrite, or a push during a rewrite therefore cannot leave a stale or partial set marked current; GC invalidates the cache whenever it deletes objects. diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts index 9bcf9467e0..809b314f73 100644 --- a/apps/api/src/vendor/dgit/git/protocol.ts +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -1481,9 +1481,22 @@ export async function validatePush( } return false; }; + // SAM: a ref named by more than one command is refused for all of them, as git + // refuses multiple updates of one ref in a transaction. Otherwise a deletion that + // loses its CAS to an earlier update of the same ref would still have freed the + // name for a nested ref here, leaving both stored. + const seen = new Set(); + const duplicated = new Set(); + for (const cmd of commands) { + if (seen.has(cmd.ref)) duplicated.add(cmd.ref); + seen.add(cmd.ref); + } for (const r of existing) trackRef(r.name, 1); for (const cmd of commands) { - if (cmd.next === ZERO_OID && refNames.has(cmd.ref) && store.getRef(cmd.ref) === cmd.old) { + if ( + cmd.next === ZERO_OID && !duplicated.has(cmd.ref) && refNames.has(cmd.ref) + && store.getRef(cmd.ref) === cmd.old + ) { trackRef(cmd.ref, -1); } } @@ -1498,6 +1511,10 @@ export async function validatePush( decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "funny refname" }); continue; } + if (duplicated.has(cmd.ref)) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "multiple updates for ref not allowed" }); + continue; + } const current = store.getRef(cmd.ref) ?? ZERO_OID; if (current !== cmd.old) { decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "fetch first" }); diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts index a825d0ff4e..1819768d78 100644 --- a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -1515,6 +1515,31 @@ describe('push connectivity admission (closure must be complete per command)', ( await assertCleanClone(remote); }); + it('refuses every command for a ref named twice, so a losing delete cannot free a nested name', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Duplicate ref commands'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('dup-ref'); + await gitOk(['clone', remote, work]); + const main = await rev(work, 'HEAD'); + await commitFile(work, 'next.txt'); + const next = await rev(work, 'HEAD'); + await gitOk(['push', 'origin', 'HEAD:refs/heads/next'], work); + expect(await receive(project, token, [[ZERO, main, 'refs/heads/a']])).toContain('ok refs/heads/a'); + // Update a, delete a (would lose its CAS to the update), then create a/b nested under it. + const out = await receive(project, token, [ + [main, next, 'refs/heads/a'], + [main, ZERO, 'refs/heads/a'], + [ZERO, main, 'refs/heads/a/b'], + ]); + expect(out).toContain('ng refs/heads/a multiple updates for ref not allowed'); + expect(out).toContain('ng refs/heads/a/b ref name conflicts with an existing ref'); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${main}\trefs/heads/a\n`); + expect(refs).not.toContain('refs/heads/a/b'); + await assertCleanClone(remote); + }); + it('without a reachable cache, a valid push from a shallow clone is accepted', async () => { const project = await createHostedProject(await createEmailOnlyUser(), 'Closure shallow control'); const token = await mintToken(project, 'write'); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts index 7595de7761..667c6dcfa8 100644 --- a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -225,6 +225,28 @@ describe('push admission: directory/file ref conflicts', () => { expect(plan.decisions[1]).toMatchObject({ reject: 'ref name conflicts with an existing ref' }); }); + it('refuses every command for a ref the push names twice, so a losing delete frees no name', async () => { + const repo = new Repo(); + const a = repo.simple('a'); + const b = repo.simple('b', [a]); + repo.refs.set('refs/heads/a', a); + // Update a, delete a (loses its CAS to the update at commit), create a/b under it. + const out = commitPush( + repo.store(), + await decide(repo, [ + [a, b, 'refs/heads/a'], + [a, ZERO, 'refs/heads/a'], + [ZERO, a, 'refs/heads/a/b'], + ]) + ); + expect(out.results.map((r) => (r.ok ? 'ok' : r.msg))).toEqual([ + 'multiple updates for ref not allowed', + 'multiple updates for ref not allowed', + 'ref name conflicts with an existing ref', + ]); + expect([...repo.refs]).toEqual([['refs/heads/a', a]]); + }); + it('allows replacing a ref with a nested one when the same push deletes it', async () => { const repo = new Repo(); const c = repo.simple('c');