From 6c14f5d76db8f6e6689a2ed130163c69c05a0982 Mon Sep 17 00:00:00 2001 From: agentbox Date: Thu, 5 Nov 2026 11:30:31 +0000 Subject: [PATCH] Initial commit: Gitea CI jobs in gVisor with sandboxed Docker --- .env.example | 20 ++ .gitignore | 3 + README.md | 353 +++++++++++++++++++++++++++++++++ docker-compose.yml | 64 ++++++ runner/Dockerfile | 31 +++ runner/act-runner-run.sh | 16 ++ runner/config.yaml | 33 +++ runner/daemon.json | 20 ++ runner/docker-run.sh | 9 + runner/gvisor-entrypoint.sh | 84 ++++++++ runner/start-dind.sh | 43 ++++ runner/start-sandboxed-dind.sh | 33 +++ scripts/e2e-test.sh | 158 +++++++++++++++ scripts/workflow-compose.yml | 53 +++++ scripts/workflow-docker.yml | 54 +++++ scripts/workflow-gvisor.yml | 52 +++++ scripts/workflow-resource.yml | 58 ++++++ 17 files changed, 1084 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 runner/Dockerfile create mode 100644 runner/act-runner-run.sh create mode 100644 runner/config.yaml create mode 100644 runner/daemon.json create mode 100644 runner/docker-run.sh create mode 100644 runner/gvisor-entrypoint.sh create mode 100644 runner/start-dind.sh create mode 100644 runner/start-sandboxed-dind.sh create mode 100755 scripts/e2e-test.sh create mode 100644 scripts/workflow-compose.yml create mode 100644 scripts/workflow-docker.yml create mode 100644 scripts/workflow-gvisor.yml create mode 100644 scripts/workflow-resource.yml diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..6e58444 --- /dev/null +++ b/.env.example @@ -0,0 +1,20 @@ +# Copy to .env and adjust. + +# Host ports exposed by the DinD host. +GITEA_HTTP_PORT=3000 +GITEA_SSH_PORT=2222 + +# Gitea external hostname. Keep "gitea" unless you set ROOT_URL to a public URL. +GITEA_DOMAIN=gitea +GITEA_ROOT_URL=http://gitea:3000/ + +GITEA_RUNNER_NAME=gvisor-runner + +# Option 1: paste a registration token generated by: +# docker compose exec -u git gitea gitea actions generate-runner-token +GITEA_RUNNER_REGISTRATION_TOKEN= + +# Option 2: leave the token empty and provide an EXISTING Gitea admin account. +# The runner will fetch a global registration token through the API. +GITEA_ADMIN_USER= +GITEA_ADMIN_PASSWORD= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..623b9ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.env +data/ +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..b8091b6 --- /dev/null +++ b/README.md @@ -0,0 +1,353 @@ +# gitea-ci-in-gvisor + +A self-contained Gitea Actions deployment where CI jobs run in **gVisor** +sandboxes instead of sharing the host Docker socket. + +It replaces the common but unsafe pattern of: + +```text +act_runner container -> /var/run/docker.sock from the host +``` + +with: + +```text +Gitea -> act_runner -> private Docker daemon -> runsc -> CI job +``` + +Jobs that need Docker for e2e tests get a **separate, sandboxed Docker daemon**. +They never receive the runner's privileged Docker socket. + +## Architecture + +### Container nesting + +```text +physical host +└── dind container [runc] Docker host at tcp://dind + ├── gitea container [runc] + └── runner container [runc] privileged + ├── job container [runsc] gVisor sandbox + └── gvisor-dind container [runsc-net] separate gVisor sandbox + └── compose / e2e service container [runc] inside gvisor-dind's sandbox +``` + +Only container nesting is shown above. The runner's `act_runner` and inner +`dockerd` are processes inside the runner container, not nested containers. + +### Network and Docker access + +```text +job container + │ DOCKER_HOST=tcp://127.0.0.1:2375 + ▼ +runner container loopback + ▼ +gvisor-dind :2375 [inside its own gVisor sandbox] + ├── dockerd + └── nested e2e containers [runc, but still inside gVisor] + +job container also reaches: + ├── gitea:3000 + ├── internet + └── 127.0.0.1:2375 (the sandboxed daemon only) +``` + +The runner's own privileged Docker daemon listens on a Unix socket only. Jobs +have neither that socket nor a TCP API for it. + +### Runtimes + +```json +{ + "default-runtime": "runsc", + "runtimes": { + "runsc": { + "path": "/usr/local/bin/runsc", + "runtimeArgs": ["--platform=systrap", "--network=host"] + }, + "runsc-net": { + "path": "/usr/local/bin/runsc", + "runtimeArgs": [ + "--platform=systrap", + "--net-raw", + "--allow-packet-socket-write" + ] + } + } +} +``` + +- `runsc` is used for CI jobs. Jobs share the runner network namespace so they + can resolve `gitea` and reach the internet, but have no raw-socket or + packet-write permission. +- `runsc-net` is used only for `gvisor-dind`. It uses gVisor's own network stack + so Docker can create bridge networks inside its sandbox. Docker 28 needs raw + sockets and packet writes there. +- Both entries use the same `runsc` binary and `systrap` platform. They are not + different gVisor installations. + +## Quick start + +Requirements: Docker with the `runc` runtime, Docker Compose, and outbound +network access for images. + +```bash +cp .env.example .env +# edit .env if needed + +docker build -t gitea-gvisor-runner:latest runner +docker compose up -d --no-build +``` + +The Compose file explicitly sets `runtime: runc` for Gitea and the runner. +This matters if the target Docker host defaults to `runsc`; only the nested +sandboxes should use gVisor. + +Open Gitea on `http://:3000` and create the first admin account, +or use the CLI: + +```bash +docker compose exec -u git gitea gitea admin user create \ + --username ciadmin --password 'CiAdminPass12345' \ + --email ciadmin@example.com --admin --must-change-password=false +``` + +### Runner registration + +Two options: + +1. Put an explicit registration token in `.env`: + + ```bash + docker compose exec -u git gitea gitea actions generate-runner-token + # GITEA_RUNNER_REGISTRATION_TOKEN=... + docker compose up -d --no-build --force-recreate runner + ``` + +2. Leave the token empty and provide an existing admin account: + + ```bash + GITEA_ADMIN_USER=ciadmin + GITEA_ADMIN_PASSWORD=CiAdminPass12345 + ``` + + The runner fetches a global token through the Gitea API. The token is only + used for the first registration; it persists in the `runner-data` volume. + +## Runner labels + +Defined in `runner/config.yaml`: + +| Label | Image | Purpose | +| --- | --- | --- | +| `ubuntu-latest` | `node:22-bookworm` | bash/Node and general CI | +| `gvisor` | `alpine:3.20` | small jobs; use `shell: sh` | +| `docker` | `docker:28-cli` | Docker CLI, Compose, e2e tests | + +The runner capacity is fixed at **1**. Recreate the runner after changing +labels. To force re-registration, remove `.runner` from the `runner-data` +volume. + +## Tests + +The test script creates a temporary Gitea repository, pushes a workflow through +the API, and waits for the result. + +```bash +# Basic isolation: gVisor kernel, hidden privileged socket, sandboxed Docker API +./scripts/e2e-test.sh + +# Docker inside the sandboxed daemon +WORKFLOW=scripts/workflow-docker.yml SHOW_LOGS=1 ./scripts/e2e-test.sh + +# A real Compose stack inside the sandboxed daemon +WORKFLOW=scripts/workflow-compose.yml SHOW_LOGS=1 ./scripts/e2e-test.sh + +# Disk, memory, and CPU stress +WORKFLOW=scripts/workflow-resource.yml SHOW_LOGS=1 ./scripts/e2e-test.sh +``` + +`GITEA_URL` defaults to `http://localhost:3000`. For the reference DinD test +environment: + +```bash +GITEA_URL=http://dind:3000 ./scripts/e2e-test.sh +``` + +### Known Compose limitation + +Docker's embedded DNS at `127.0.0.11` depends on Docker-managed iptables, which +is disabled inside gVisor. Nested Compose service names therefore do **not** +resolve automatically. + +The Compose test uses a static IP and `extra_hosts`: + +```yaml +services: + web: + networks: + testnet: + ipv4_address: 172.31.0.10 + probe: + extra_hosts: + - "web:172.31.0.10" +``` + +For real e2e Compose files, use one of: + +- `extra_hosts` with static IPs +- explicit container IPs +- host networking inside the sandbox +- a custom DNS design + +## Security model + +### What is protected + +- No host Docker socket is mounted into jobs. +- The runner's privileged Docker daemon has no TCP listener. +- Jobs run in gVisor, not directly on the host kernel. +- The job-accessible Docker daemon (`gvisor-dind`) is itself in a separate + gVisor sandbox. +- Nested Docker containers controlled by a job remain inside that sandbox. +- Direct access from jobs to the outer Docker host gateway is rejected, except + DNS. This closes an otherwise trivial escape when the host exposes its Docker + API on the bridge address. +- Job runtime has no `--net-raw` or AF_PACKET write permission. + +### Escape paths considered + +| Path | Result | +| --- | --- | +| `/var/run/docker.sock` in job | absent | +| runner Docker TCP API | disabled | +| `gvisor-dind` API | reachable, but it is a separate sandbox | +| outer host gateway | blocked by iptables, DNS excepted | +| host filesystem/devices | no host bind mounts; gVisor virtualizes | +| raw packet sniffing/spoofing | disabled for jobs | +| registration token/admin password | not injected into jobs | +| resource exhaustion | **not prevented**; add quotas if needed | +| shared tool cache | **poisonable** by a malicious job; use ephemeral runners | + +### Residual risk + +The primary boundary is **gVisor itself**. A runsc/sentry escape could reach +the privileged runner container. Keep gVisor current, prefer KVM where +practical, and use a dedicated or disposable Docker host for high-assurance CI. + +The gateway firewall only covers the default gateway address. Other host/service +IPs may still be reachable. Use a dedicated runner network, host firewall +rules, and never expose an unauthenticated Docker API to containers. + +## Compatibility and limitations + +### Docker versions + +The runner is based on `gitea/act_runner:0.6.1-dind` (Docker 28.5.2), and the +sandboxed daemon uses `docker:28-dind`. This deliberately avoids Docker 29's +containerd-snapshotter/overlayfs complications. + +If upgrading to Docker 29+: + +- disable the containerd snapshotter with + `--feature containerd-snapshotter=false` and verify overlay2 on a disk-backed + volume, or +- use `vfs` if overlay2 still cannot mount, or +- use a RAM-backed tmpfs only if bounded image/build storage is acceptable. + +The deployment uses a real disk volume for `/var/lib/docker`; arbitrary job +storage should not be capped by runner RAM. + +### gVisor cgroups + +`runsc` needs to enable cgroup controllers on the root of its cgroup namespace. +On cgroup v2, a root containing processes cannot do that. The runner entrypoint +moves PID 1 into a child cgroup so the namespace root is empty. Docker CPU and +memory limits then apply to the sandbox. + +On cgroup v1 this step is a no-op. + +### Nested Docker networking + +`gvisor-dind` starts Docker with `--iptables=false --ip6tables=false`. +`runner/start-dind.sh` adds a manual SNAT rule so nested containers have +outbound internet. + +Consequences: + +- Docker-managed NAT and embedded DNS are unavailable. +- Bridge networking works inside gVisor's own network stack. +- Nested containers need IPs/`extra_hosts`/host networking for service names. + +### Performance + +Rough numbers from the reference DinD host (16 vCPU, 30 GiB RAM). These are +short microbenchmarks, not guarantees: + +| Workload | `runc` baseline | gVisor job | Nested Docker under `gvisor-dind` | +| --- | ---: | ---: | ---: | +| 2 GiB write | 2.7 GB/s | 2.5 GB/s | 2.4 GB/s | +| 2 GiB read | 18.6 GB/s | ~14 GB/s | 13.4 GB/s | +| 2 GiB memory touch | ~1.9 s | ~2–3 s | ~2.0 s | +| BusyBox awk 10M loop | 5.18 s | ~9.3 s | 5.25 s | + +I/O and memory are close to native. CPU/syscall-heavy work pays gVisor overhead. +Benchmark the actual CI image rather than extrapolating. + +## Known workarounds and their reasons + +These are intentional but not invisible: + +1. **PID 1 moved into a child cgroup** — required for cgroup v2 + runsc. +2. **Custom s6 readiness wait** — stock notify-on-check can time out during slow + nested Docker startup. +3. **Custom dockerd wrapper** — keeps the privileged runner daemon on a Unix + socket only; the stock dind entrypoint adds TCP. +4. **Manual SNAT** — Docker iptables cannot initialize inside gVisor. +5. **Loopback TCP for the sandboxed daemon** — Unix socket files created inside + a gVisor sandbox cannot usefully be shared through a Docker volume. +6. **Separate `runsc` / `runsc-net` runtimes** — Docker-in-gVisor needs raw + socket support and gVisor's own network stack, while jobs do not. +7. **Docker 28 pin** — avoids Docker 29 containerd-snapshotter/overlayfs + incompatibilities. +8. **Gateway reject rule** — blocks the outer Docker host API, which was + reachable from the shared runner network namespace. +9. **Static IP + `extra_hosts` in the Compose test** — works around missing + nested Docker DNS. +10. **`docker build` instead of `docker compose build` in the test script** — + the test environment's Compose plugin is older than its buildx plugin. + +## Repository layout + +```text +. +├── docker-compose.yml Gitea + privileged runner +├── .env.example +├── runner/ +│ ├── Dockerfile act_runner + runsc + sandboxed dind setup +│ ├── daemon.json runsc and runsc-net runtime entries +│ ├── config.yaml labels, capacity, DOCKER_HOST +│ ├── gvisor-entrypoint.sh cgroup setup, token fetch, gateway block +│ ├── docker-run.sh runner dockerd, Unix socket only +│ ├── act-runner-run.sh wait for Docker, start sandboxed daemon +│ ├── start-sandboxed-dind.sh launch gvisor-dind under runsc-net +│ └── start-dind.sh gVisor-aware dockerd startup + SNAT +└── scripts/ + ├── e2e-test.sh API-driven end-to-end test + ├── workflow-gvisor.yml basic isolation + ├── workflow-docker.yml Docker-in-sandbox test + ├── workflow-compose.yml Compose-in-sandbox test + └── workflow-resource.yml disk/memory/CPU stress +``` + +## Production hardening checklist + +- Do not expose the host Docker API over TCP to the runner network. +- Keep Gitea, the runner, and the outer Docker host patched. +- Keep gVisor current; use KVM where practical. +- Put the runner on a dedicated network/host. +- Add per-job CPU/memory/disk limits if workflows are untrusted. +- Use ephemeral runners or clear `act-toolcache` between tenants. +- Treat the runner container itself as privileged infrastructure, not as a + security boundary for the host. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ed3f8ff --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,64 @@ +name: gitea-gvisor + +services: + gitea: + image: gitea/gitea:1.27.3 + # The target Docker host may default to runsc. Gitea and the runner's + # privileged dockerd must stay on runc; only nested job sandboxes use runsc. + runtime: runc + restart: unless-stopped + environment: + USER_UID: "1000" + USER_GID: "1000" + GITEA__database__DB_TYPE: sqlite3 + GITEA__security__INSTALL_LOCK: "true" + GITEA__actions__ENABLED: "true" + GITEA__server__DOMAIN: ${GITEA_DOMAIN:-gitea} + GITEA__server__SSH_DOMAIN: ${GITEA_DOMAIN:-gitea} + # Reachable from job containers, which share the runner's network + # namespace. Override with the public URL if the web UI must use it. + GITEA__server__ROOT_URL: ${GITEA_ROOT_URL:-http://gitea:3000/} + GITEA__server__HTTP_PORT: "3000" + volumes: + - gitea-data:/data + ports: + - "${GITEA_HTTP_PORT:-3000}:3000" + - "${GITEA_SSH_PORT:-2222}:22" + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://localhost:3000/api/healthz || exit 1"] + interval: 5s + timeout: 5s + retries: 60 + start_period: 20s + + runner: + build: + context: ./runner + image: gitea-gvisor-runner:latest + runtime: runc + restart: unless-stopped + # dockerd needs privileged mode to create the nested job containers. The job + # containers themselves always run under runsc/gVisor. + privileged: true + environment: + GITEA_INSTANCE_URL: http://gitea:3000 + GITEA_RUNNER_NAME: ${GITEA_RUNNER_NAME:-gvisor-runner} + # Either set a token explicitly, or set GITEA_ADMIN_USER/PASSWORD and let + # the runner fetch one from the Gitea API. + GITEA_RUNNER_REGISTRATION_TOKEN: ${GITEA_RUNNER_REGISTRATION_TOKEN:-} + GITEA_ADMIN_USER: ${GITEA_ADMIN_USER:-} + GITEA_ADMIN_PASSWORD: ${GITEA_ADMIN_PASSWORD:-} + DOCKER_HOST: unix:///var/run/docker.sock + volumes: + - runner-data:/data + # Real disk-backed Docker storage: no memory-limited tmpfs, so arbitrary + # image and build sizes are possible. + - runner-docker:/var/lib/docker + depends_on: + gitea: + condition: service_healthy + +volumes: + gitea-data: + runner-data: + runner-docker: diff --git a/runner/Dockerfile b/runner/Dockerfile new file mode 100644 index 0000000..e02400c --- /dev/null +++ b/runner/Dockerfile @@ -0,0 +1,31 @@ +FROM gitea/act_runner:0.6.1-dind + +# gVisor release used to sandbox every CI job container. +ARG GVISOR_RELEASE=release-20261102.0 + +RUN apk add --no-cache curl tar bzip2 \ + && curl -fsSL "https://github.com/google/gvisor/releases/download/${GVISOR_RELEASE}/gvisor-x86_64.tar.bz2" \ + | tar -xj -C /usr/local/bin \ + && chmod +x /usr/local/bin/runsc \ + /usr/local/bin/containerd-shim-runsc-v1 \ + /usr/local/bin/gvisor-bin/* \ + && runsc --version + +COPY daemon.json /etc/docker/daemon.json +COPY config.yaml /etc/act_runner/config.yaml +COPY gvisor-entrypoint.sh /usr/local/bin/gvisor-entrypoint.sh +COPY act-runner-run.sh /etc/s6/act_runner/run +COPY docker-run.sh /etc/s6/docker/run +COPY start-sandboxed-dind.sh /usr/local/bin/start-sandboxed-dind.sh +COPY start-dind.sh /opt/gvisor-dind/start-dind.sh +RUN chmod +x /usr/local/bin/gvisor-entrypoint.sh \ + /usr/local/bin/start-sandboxed-dind.sh \ + /etc/s6/act_runner/run \ + /etc/s6/docker/run \ + /opt/gvisor-dind/start-dind.sh + +ENV CONFIG_FILE=/etc/act_runner/config.yaml + +# Keep the base image's s6 supervision (starts dockerd, then act_runner). +ENTRYPOINT ["/usr/local/bin/gvisor-entrypoint.sh"] +CMD ["s6-svscan", "/etc/s6"] diff --git a/runner/act-runner-run.sh b/runner/act-runner-run.sh new file mode 100644 index 0000000..3ebf65c --- /dev/null +++ b/runner/act-runner-run.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -eu + +# The stock image waits for the Docker s6 service to report "ready". On slow +# nested hosts s6-notifyoncheck can time out before dockerd finishes starting, +# leaving act_runner blocked forever. Wait for the daemon itself instead. +while ! docker info >/dev/null 2>&1; do + sleep 1 +done + +# Start the Docker daemon that CI jobs are allowed to use. It is itself inside +# a gVisor sandbox and is completely separate from the privileged runner +# daemon. +/usr/local/bin/start-sandboxed-dind.sh + +exec /usr/local/bin/run.sh diff --git a/runner/config.yaml b/runner/config.yaml new file mode 100644 index 0000000..71532b1 --- /dev/null +++ b/runner/config.yaml @@ -0,0 +1,33 @@ +log: + level: info + +runner: + file: .runner + # The runner is intentionally single-slot. This avoids jobs racing for the + # same nested Docker daemon and its workspace volumes. + capacity: 1 + timeout: 3h + labels: + - "ubuntu-latest:docker://node:22-bookworm" + - "gvisor:docker://alpine:3.20" + - "docker:docker://docker:28-cli" + envs: + # Jobs talk only to the sandboxed Docker daemon, never the runner's own + # privileged daemon. + DOCKER_HOST: tcp://127.0.0.1:2375 + +cache: + enabled: true + +container: + # Share the runner container's network namespace. This lets job containers + # resolve the Compose service name "gitea" and is useful for actions/checkout. + network: host + privileged: false + # "-" means: use the local Docker daemon for runner internals, but never + # expose the runner's privileged socket to jobs. + docker_host: "-" + force_pull: false + +host: + workdir_parent: diff --git a/runner/daemon.json b/runner/daemon.json new file mode 100644 index 0000000..c2e0bae --- /dev/null +++ b/runner/daemon.json @@ -0,0 +1,20 @@ +{ + "default-runtime": "runsc", + "runtimes": { + "runsc": { + "path": "/usr/local/bin/runsc", + "runtimeArgs": [ + "--platform=systrap", + "--network=host" + ] + }, + "runsc-net": { + "path": "/usr/local/bin/runsc", + "runtimeArgs": [ + "--platform=systrap", + "--net-raw", + "--allow-packet-socket-write" + ] + } + } +} diff --git a/runner/docker-run.sh b/runner/docker-run.sh new file mode 100644 index 0000000..df3d4c9 --- /dev/null +++ b/runner/docker-run.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -eu + +# Do not use the stock dind entrypoint here: it always adds a TCP listener. +# Jobs use host networking so they can resolve the "gitea" Compose service and +# reach the internet, which would also expose tcp://127.0.0.1:2375 to them. +# Keep the daemon on its private unix socket only. +find /run /var/run -iname 'docker*.pid' -delete 2>/dev/null || true +exec dockerd --host=unix:///var/run/docker.sock diff --git a/runner/gvisor-entrypoint.sh b/runner/gvisor-entrypoint.sh new file mode 100644 index 0000000..34ca546 --- /dev/null +++ b/runner/gvisor-entrypoint.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -eu + +# --------------------------------------------------------------------------- +# cgroup v2 workaround for nested dockerd + runsc +# +# runsc creates a cgroup for each sandbox and must enable controllers on the +# root of its cgroup namespace. On cgroup v2, a cgroup with processes in it +# cannot have domain controllers enabled ("no internal process" rule). The +# container runtime puts this container's processes in the namespace root, so +# runsc gets EBUSY on cgroup.subtree_control. +# +# Moving PID 1 into a child cgroup makes the namespace root empty. Every s6 +# service (dockerd, containerd, act_runner) inherits that child, so jobs can +# still receive real CPU/memory limits from Docker. +# --------------------------------------------------------------------------- +if [ -f /sys/fs/cgroup/cgroup.controllers ]; then + mkdir -p /sys/fs/cgroup/init + echo "$$" > /sys/fs/cgroup/init/cgroup.procs 2>/dev/null || true +fi + +# --------------------------------------------------------------------------- +# Block direct access to the outer Docker host from CI jobs. +# +# Jobs share the runner's network namespace, and the default gateway is the +# Docker host that runs this runner. If that host exposes a Docker API (or any +# other administrative service) on its bridge address, a workflow could use it +# to escape the sandbox entirely. Keep DNS to the gateway working, but reject +# other direct traffic to the gateway IP. Outbound traffic to the internet is +# unaffected because its destination is not the gateway address. +# +# Set BLOCK_HOST_GATEWAY=0 to disable this (not recommended). +# --------------------------------------------------------------------------- +if [ "${BLOCK_HOST_GATEWAY:-1}" = "1" ]; then + gateway=$(ip route 2>/dev/null | awk '/^default / {print $3; exit}') + if [ -n "${gateway:-}" ]; then + if command -v iptables >/dev/null 2>&1; then + IPTABLES=iptables + elif command -v iptables-legacy >/dev/null 2>&1; then + IPTABLES=iptables-legacy + else + IPTABLES="" + fi + if [ -n "${IPTABLES}" ]; then + if ! "$IPTABLES" -C OUTPUT -d "$gateway" -j REJECT >/dev/null 2>&1; then + "$IPTABLES" -I OUTPUT -d "$gateway" -p udp --dport 53 -j ACCEPT 2>/dev/null || true + "$IPTABLES" -I OUTPUT -d "$gateway" -p tcp --dport 53 -j ACCEPT 2>/dev/null || true + "$IPTABLES" -A OUTPUT -d "$gateway" -j REJECT 2>/dev/null || true + echo "Blocked direct CI access to Docker-host gateway ${gateway} (DNS allowed)." + fi + fi + fi +fi + +# --------------------------------------------------------------------------- +# Optional zero-touch registration. +# +# If no explicit registration token was supplied, use an existing Gitea admin +# account to fetch a global runner registration token from the API. This keeps +# the token out of the Compose file and works with a normal admin-created user. +# --------------------------------------------------------------------------- +if [ -z "${GITEA_RUNNER_REGISTRATION_TOKEN:-}" ] \ + && [ -n "${GITEA_ADMIN_USER:-}" ] \ + && [ -n "${GITEA_ADMIN_PASSWORD:-}" ]; then + echo "Waiting for Gitea to issue a runner registration token..." + i=0 + while [ "$i" -lt 60 ]; do + response=$(curl -fsS \ + -u "${GITEA_ADMIN_USER}:${GITEA_ADMIN_PASSWORD}" \ + -X POST \ + "${GITEA_INSTANCE_URL%/}/api/v1/admin/actions/runners/registration-token" \ + 2>/dev/null || true) + token=$(printf '%s' "$response" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') + if [ -n "$token" ]; then + export GITEA_RUNNER_REGISTRATION_TOKEN="$token" + echo "Obtained a runner registration token from the Gitea API." + break + fi + i=$((i + 1)) + sleep 2 + done +fi + +exec "$@" diff --git a/runner/start-dind.sh b/runner/start-dind.sh new file mode 100644 index 0000000..a881ea0 --- /dev/null +++ b/runner/start-dind.sh @@ -0,0 +1,43 @@ +#!/bin/sh +set -eu + +# This script runs *inside* a gVisor sandbox. It starts a Docker daemon whose +# containers also live inside that same sandbox. Jobs connect to this daemon +# through a shared unix-socket volume; they never see the privileged runner +# daemon's socket. + +# In gVisor, `ip route show default` returns all routes, not only the default. +route=$(ip route show default | grep '^default ' | head -n1 || true) +dev="" +addr="" +if [ -n "$route" ]; then + dev=$(printf '%s\n' "$route" | sed -E 's/.* dev ([^ ]+).*/\1/') + addr=$(ip -o -4 addr show dev "$dev" | awk '{print $4}' | cut -d/ -f1) +fi + +# Nested containers use the daemon's bridge network. Because dockerd is started +# with iptables disabled (required by gVisor), add the SNAT rule ourselves so +# those containers can reach the internet. +if [ -n "$dev" ] && [ -n "$addr" ]; then + echo 1 > /proc/sys/net/ipv4/ip_forward + if command -v iptables-legacy >/dev/null 2>&1; then + IPTABLES=iptables-legacy + else + IPTABLES=iptables + fi + "$IPTABLES" -t nat -A POSTROUTING -o "$dev" -j SNAT --to-source "$addr" -p tcp + "$IPTABLES" -t nat -A POSTROUTING -o "$dev" -j SNAT --to-source "$addr" -p udp +fi + +rm -f /var/run/docker.sock + +# The TCP listener is published only on the runner container's loopback. A +# unix socket created inside a gVisor sandbox cannot usefully be shared through +# a Docker volume, so jobs reach this daemon over loopback TCP instead. +exec dockerd \ + --host=unix:///var/run/docker.sock \ + --host=tcp://0.0.0.0:2375 \ + --tls=false \ + --iptables=false \ + --ip6tables=false \ + "$@" diff --git a/runner/start-sandboxed-dind.sh b/runner/start-sandboxed-dind.sh new file mode 100644 index 0000000..2bc9c3b --- /dev/null +++ b/runner/start-sandboxed-dind.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Runs inside the runner container (not inside gVisor). It asks the runner's +# private dockerd to launch a second, gVisor-sandboxed Docker daemon and shares +# only that daemon's socket volume with CI jobs. + +docker volume create gvisor-dind-data >/dev/null + +docker rm -f gvisor-dind >/dev/null 2>&1 || true +docker run -d \ + --name gvisor-dind \ + --restart unless-stopped \ + --runtime=runsc-net \ + --privileged \ + -p 127.0.0.1:2375:2375 \ + -v gvisor-dind-data:/var/lib/docker \ + -v /opt/gvisor-dind/start-dind.sh:/opt/gvisor-dind/start-dind.sh:ro \ + --entrypoint /opt/gvisor-dind/start-dind.sh \ + docker:28-dind >/dev/null + +echo "Waiting for the sandboxed Docker daemon..." +for _ in $(seq 1 120); do + if docker exec gvisor-dind docker info >/dev/null 2>&1; then + echo "Sandboxed Docker daemon is ready." + exit 0 + fi + sleep 1 +done + +echo "Sandboxed Docker daemon did not become ready" >&2 +docker logs --tail 120 gvisor-dind >&2 || true +exit 1 diff --git a/scripts/e2e-test.sh b/scripts/e2e-test.sh new file mode 100755 index 0000000..cf0eab4 --- /dev/null +++ b/scripts/e2e-test.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +set -euo pipefail + +# End-to-end check for the gVisor-backed Gitea runner. +# +# Run from the deployment directory: +# ./scripts/e2e-test.sh +# +# Environment overrides: +# GITEA_URL default http://localhost:3000 +# ADMIN_USER default ciadmin +# ADMIN_PASSWORD default CiAdminPass12345 +# REPO default gvisor-e2e- + +cd "$(dirname "$0")/.." + +GITEA_URL="${GITEA_URL:-http://localhost:3000}" +GITEA_URL="${GITEA_URL%/}" +ADMIN_USER="${ADMIN_USER:-ciadmin}" +ADMIN_PASSWORD="${ADMIN_PASSWORD:-CiAdminPass12345}" +REPO="${REPO:-gvisor-e2e-$(date +%s)}" +WORKFLOW="${WORKFLOW:-scripts/workflow-gvisor.yml}" +SHOW_LOGS="${SHOW_LOGS:-0}" + +api() { + curl -fsS -u "${ADMIN_USER}:${ADMIN_PASSWORD}" "$@" +} + +echo "==> Building the runner image" +docker build -t gitea-gvisor-runner:latest runner >/dev/null + +echo "==> Starting Gitea" +docker compose up -d --no-build gitea >/dev/null + +echo "==> Waiting for Gitea at ${GITEA_URL}" +for _ in $(seq 1 90); do + if curl -fsS "${GITEA_URL}/api/healthz" >/dev/null 2>&1; then + break + fi + sleep 2 +done +curl -fsS "${GITEA_URL}/api/healthz" >/dev/null + +echo "==> Creating admin user (ignore error if it already exists)" +docker compose exec -T -u git gitea gitea admin user create \ + --username "${ADMIN_USER}" \ + --password "${ADMIN_PASSWORD}" \ + --email "${ADMIN_USER}@example.com" \ + --admin --must-change-password=false >/dev/null 2>&1 || true + +echo "==> Starting runner (auto-registers through the Gitea API)" +GITEA_ADMIN_USER="${ADMIN_USER}" \ +GITEA_ADMIN_PASSWORD="${ADMIN_PASSWORD}" \ +docker compose up -d --no-build --force-recreate runner >/dev/null + +echo "==> Waiting for the runner to come online" +online=0 +for _ in $(seq 1 90); do + if api "${GITEA_URL}/api/v1/admin/actions/runners" | grep -q '"status":"online"'; then + online=1 + break + fi + sleep 2 +done +if [ "${online}" != 1 ]; then + docker compose logs --tail 100 runner + echo "Runner did not come online" >&2 + exit 1 +fi + +echo "==> Creating repository ${ADMIN_USER}/${REPO}" +api -H 'Content-Type: application/json' \ + -d "{\"name\":\"${REPO}\",\"private\":false,\"auto_init\":false}" \ + "${GITEA_URL}/api/v1/user/repos" >/dev/null 2>&1 || true + +tmp="$(mktemp -d)" +trap 'rm -rf "${tmp}"' EXIT +export GIT_CONFIG_GLOBAL="${tmp}/gitconfig" +git config --global user.name "gVisor CI Test" +git config --global user.email "gvisor-ci@example.com" +git config --global init.defaultBranch main + +# URL-encode the password minimally for HTTP basic auth in the remote URL. +remote="http://${ADMIN_USER}:${ADMIN_PASSWORD}@${GITEA_URL#http://}/${ADMIN_USER}/${REPO}.git" + +echo "==> Pushing workflow to ${ADMIN_USER}/${REPO}" +git clone -q "${remote}" "${tmp}/repo" 2>/dev/null || { + mkdir -p "${tmp}/repo" + git -C "${tmp}/repo" init -q + git -C "${tmp}/repo" remote add origin "${remote}" +} +mkdir -p "${tmp}/repo/.gitea/workflows" +cp "${WORKFLOW}" "${tmp}/repo/.gitea/workflows/gvisor-isolation.yml" +git -C "${tmp}/repo" add .gitea/workflows/gvisor-isolation.yml +git -C "${tmp}/repo" commit -q -m "test: run a job inside gVisor" +git -C "${tmp}/repo" push -q origin HEAD:main + +echo "==> Waiting for the workflow run" +run_id="" +status="" +conclusion="" +for _ in $(seq 1 180); do + runs_json=$(api "${GITEA_URL}/api/v1/repos/${ADMIN_USER}/${REPO}/actions/runs" || true) + read -r run_id status conclusion <<< "$(printf '%s' "${runs_json}" | python3 -c ' +import json, sys +try: + data = json.load(sys.stdin) +except Exception: + print("") + raise SystemExit(0) +runs = data.get("workflow_runs", data.get("runs", [])) +if runs: + r = runs[0] + print(r.get("id", ""), r.get("status", ""), r.get("conclusion", "")) +')" + if [ -n "${run_id}" ] && [ "${status}" = "completed" ]; then + break + fi + sleep 2 +done + +if [ -z "${run_id}" ]; then + echo "No workflow run was created" >&2 + docker compose logs --tail 120 runner + exit 1 +fi + +echo "==> Workflow run ${run_id}: status=${status} conclusion=${conclusion}" +jobs_json=$(api "${GITEA_URL}/api/v1/repos/${ADMIN_USER}/${REPO}/actions/runs/${run_id}/jobs" || true) +printf '%s' "${jobs_json}" | python3 -m json.tool || true + +job_id=$(printf '%s' "${jobs_json}" | python3 -c ' +import json, sys +try: + data = json.load(sys.stdin) +except Exception: + print("") + raise SystemExit(0) +jobs = data.get("jobs", data if isinstance(data, list) else []) +print(jobs[0]["id"] if jobs else "") +') + +if [ "${conclusion}" != "success" ] || [ "${SHOW_LOGS}" = "1" ]; then + if [ "${conclusion}" != "success" ]; then + echo "Workflow failed; fetching logs" >&2 + else + echo "==> Job logs" + fi + if [ -n "${job_id}" ]; then + api "${GITEA_URL}/api/v1/repos/${ADMIN_USER}/${REPO}/actions/jobs/${job_id}/logs" || true + fi +fi + +if [ "${conclusion}" != "success" ]; then + exit 1 +fi + +echo "==> PASS: the workflow ran successfully inside gVisor" diff --git a/scripts/workflow-compose.yml b/scripts/workflow-compose.yml new file mode 100644 index 0000000..b1718bc --- /dev/null +++ b/scripts/workflow-compose.yml @@ -0,0 +1,53 @@ +name: sandboxed-compose-e2e + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + compose-e2e: + runs-on: docker + steps: + - name: Write a real Compose file + shell: sh + run: | + set -eu + cat > docker-compose.yml <<'YAML' + services: + web: + image: nginx:alpine + networks: + testnet: + ipv4_address: 172.31.0.10 + + probe: + image: alpine:3.20 + depends_on: + - web + networks: + - testnet + # Docker's embedded DNS at 127.0.0.11 needs Docker-managed + # iptables, which is disabled inside gVisor. Map the service + # name explicitly instead. + extra_hosts: + - "web:172.31.0.10" + command: sh -c "wget -qO- --timeout=10 http://web:80 | grep -q 'Welcome to nginx'" + + networks: + testnet: + ipam: + config: + - subnet: 172.31.0.0/24 + YAML + docker compose config >/dev/null + + - name: Up, probe, down + shell: sh + run: | + set -eu + docker compose up -d web + docker compose run --rm probe + docker compose ps + docker compose down -v + echo "OK: Compose stack ran inside the sandboxed Docker daemon" diff --git a/scripts/workflow-docker.yml b/scripts/workflow-docker.yml new file mode 100644 index 0000000..05af708 --- /dev/null +++ b/scripts/workflow-docker.yml @@ -0,0 +1,54 @@ +name: sandboxed-docker-e2e + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + docker-e2e: + # docker:28-cli has the Docker CLI; DOCKER_HOST is injected by the runner + # and points at the gVisor-sandboxed daemon, not the runner's own daemon. + runs-on: docker + steps: + - name: Talk to the sandboxed Docker daemon + shell: sh + run: | + set -eu + docker info | grep -E 'Server Version|Storage Driver|Cgroup Version' + docker run --rm alpine:3.20 sh -c ' + grep -qi gvisor /proc/version + echo "nested kernel: $(uname -r)" + cat /proc/version + ' + + - name: Nested containers have networking + shell: sh + run: | + set -eu + docker rm -f gvisor-e2e-web >/dev/null 2>&1 || true + docker network rm gvisor-e2e-net >/dev/null 2>&1 || true + docker network create gvisor-e2e-net >/dev/null + docker run -d --name gvisor-e2e-web --network gvisor-e2e-net nginx:alpine >/dev/null + web_ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' gvisor-e2e-web) + test -n "${web_ip}" + for i in $(seq 1 30); do + if docker run --rm --network gvisor-e2e-net alpine:3.20 \ + wget -qO- --timeout=2 "http://${web_ip}:80" 2>/dev/null | grep -q "Welcome to nginx"; then + break + fi + sleep 1 + done + docker run --rm --network gvisor-e2e-net alpine:3.20 \ + wget -qO- --timeout=5 "http://${web_ip}:80" | grep -q "Welcome to nginx" + docker run --rm alpine:3.20 sh -c \ + 'wget -qO- --timeout=10 http://example.com >/dev/null' + docker rm -f gvisor-e2e-web >/dev/null + docker network rm gvisor-e2e-net >/dev/null + + - name: The privileged runner socket is still hidden + shell: sh + run: | + set -eu + test ! -S /var/run/docker.sock + echo "OK: /var/run/docker.sock is not present" diff --git a/scripts/workflow-gvisor.yml b/scripts/workflow-gvisor.yml new file mode 100644 index 0000000..fa1fdef --- /dev/null +++ b/scripts/workflow-gvisor.yml @@ -0,0 +1,52 @@ +name: gvisor-isolation + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + verify: + # This label is mapped in runner/config.yaml to alpine:3.20. Every job + # container is created by the nested dockerd with default-runtime=runsc. + runs-on: gvisor + steps: + - name: Prove the job runs on the gVisor kernel + shell: sh + run: | + set -eu + echo "uname: $(uname -a)" + echo "proc/version: $(cat /proc/version)" + grep -qi gvisor /proc/version + echo "OK: workflow is running inside gVisor" + + - name: The privileged runner socket is hidden; only the sandboxed daemon is reachable + shell: sh + run: | + set -eu + if [ -S /var/run/docker.sock ]; then + echo "ERROR: the privileged runner Docker socket leaked into the job" >&2 + exit 1 + fi + # TCP 2375 belongs to the separate gVisor-sandboxed Docker daemon. + test "$(wget -qO- --timeout=5 http://127.0.0.1:2375/_ping)" = "OK" + echo "OK: privileged socket hidden; sandboxed Docker daemon is reachable" + + - name: Prove service DNS and network access work + shell: sh + run: | + set -eu + wget -qO- --timeout=10 http://gitea:3000/api/healthz >/dev/null + echo "OK: the job can reach Gitea by service name" + + - name: Prove the outer Docker host API is not reachable + shell: sh + run: | + set -eu + gateway=$(ip route | awk '/^default / {print $3; exit}') + echo "gateway=${gateway}" + if wget -qO- --timeout=3 "http://${gateway}:2375/version" >/dev/null 2>&1; then + echo "ERROR: the outer Docker host API is reachable from the job" >&2 + exit 1 + fi + echo "OK: outer Docker host API blocked; Gitea/internet still work" diff --git a/scripts/workflow-resource.yml b/scripts/workflow-resource.yml new file mode 100644 index 0000000..0532433 --- /dev/null +++ b/scripts/workflow-resource.yml @@ -0,0 +1,58 @@ +name: gvisor-resource-test + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + resource-test: + runs-on: gvisor + steps: + - name: Environment + shell: sh + run: | + set -eu + grep -qi gvisor /proc/version + echo "kernel: $(uname -r)" + echo "nproc: $(nproc)" + free -m || true + df -h . + + - name: Disk I/O (2 GiB write + read) + shell: sh + run: | + set -eu + echo "Writing 2 GiB to the job workspace..." + sync + dd if=/dev/zero of=./gvisor-disk-test bs=1M count=2048 2>&1 | tail -1 + sync + echo "Reading 2 GiB back..." + dd if=./gvisor-disk-test of=/dev/null bs=1M 2>&1 | tail -1 + ls -lh ./gvisor-disk-test + rm -f ./gvisor-disk-test + + - name: Memory allocation (2 GiB) + shell: sh + run: | + set -eu + start=$(date +%s) + # BusyBox awk: create 2048 one-MiB strings and touch them so the + # allocation really happens inside the gVisor sandbox. + awk 'BEGIN { + for (i = 0; i < 2048; i++) a[i] = sprintf("%01048576s", ""); + # Touch every string so the pages really stay resident. + for (i = 0; i < 2048; i++) if (length(a[i]) != 1048576) exit 1; + printf "allocated=%d MiB\n", 2048; + }' + end=$(date +%s) + echo "elapsed_s=$((end - start))" + + - name: CPU scheduling (1 core, then 4 parallel workers) + shell: sh + run: | + set -eu + echo "Single-core awk integer loop:" + time awk 'BEGIN { for (i = 0; i < 10000000; i++) x += i; print x }' + echo "Four parallel awk loops:" + time sh -c 'for i in 1 2 3 4; do awk "BEGIN { for (i = 0; i < 5000000; i++) x += i; print x }" & done; wait'