From 6f2c4511873ee2af9232ff7fc17496581a7cc826 Mon Sep 17 00:00:00 2001 From: agentbox Date: Thu, 5 Nov 2026 11:51:11 +0000 Subject: [PATCH] Match compose layout to production dind + runner deployment --- .env.example | 20 - .gitignore | 5 +- README.md | 470 +++++++------------- dind-runsc/resolv.conf | 2 + docker-compose.yml | 99 ++--- gvisor/images/basic/docker/Dockerfile | 6 + gvisor/images/basic/docker/start-dockerd.sh | 72 +++ runner/Dockerfile | 31 -- runner/act-runner-run.sh | 16 - runner/config.yaml | 14 +- 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-gvisor.yml | 6 +- 17 files changed, 303 insertions(+), 785 deletions(-) delete mode 100644 .env.example create mode 100644 dind-runsc/resolv.conf create mode 100644 gvisor/images/basic/docker/Dockerfile create mode 100755 gvisor/images/basic/docker/start-dockerd.sh delete mode 100644 runner/Dockerfile delete mode 100644 runner/act-runner-run.sh delete mode 100644 runner/daemon.json delete mode 100644 runner/docker-run.sh delete mode 100644 runner/gvisor-entrypoint.sh delete mode 100644 runner/start-dind.sh delete mode 100644 runner/start-sandboxed-dind.sh delete mode 100755 scripts/e2e-test.sh diff --git a/.env.example b/.env.example deleted file mode 100644 index 6e58444..0000000 --- a/.env.example +++ /dev/null @@ -1,20 +0,0 @@ -# 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 index 623b9ab..403a07a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ .env -data/ +gitea/ +dind-data/ +runner/.runner +runner/.cache/ *.log diff --git a/README.md b/README.md index 505268c..b1c2501 100644 --- a/README.md +++ b/README.md @@ -1,353 +1,215 @@ # gitea-ci-in-gvisor -A self-contained Gitea Actions deployment where CI jobs run in **gVisor** -sandboxes instead of sharing the host Docker socket. +Gitea Actions deployment with a **gVisor-sandboxed Docker-in-Docker daemon** for +CI jobs. The runner talks to that daemon over a private Compose network; it does +not receive a host Docker socket. -It replaces the common but unsafe pattern of: +This repository mirrors the deployment layout used on the target host: ```text -act_runner container -> /var/run/docker.sock from the host +Gitea (Caddy + gitea networks) + │ + ├── act_runner (gitea + ci networks) + │ │ Docker API: tcp://dind:2375 + │ ▼ + └── dind (ci network, runtime: runsc-docker) + │ Docker daemon inside gVisor + ▼ + CI job containers ``` -with: - -```text -Gitea -> act_runner -> private Docker daemon -> runsc-host -> 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 +## Container nesting ```text physical host -└── dind container [runc] Docker host at tcp://dind - ├── gitea container [runc] - └── runner container [runc] privileged - ├── job container [runsc-host] gVisor sandbox - └── gvisor-dind container [runsc-docker] separate gVisor sandbox - └── compose / e2e service container [runc] inside gvisor-dind's sandbox +├── gitea container [host default runtime] networks: caddy, gitea +├── runner container [host default runtime] networks: gitea, ci +└── dind container [runsc-docker] network: ci + └── CI job container [runc inside gVisor] created by dind ``` -Only container nesting is shown above. The runner's `act_runner` and inner -`dockerd` are processes inside the runner container, not nested containers. +The target host defaults to `runsc`, so Gitea and the runner also run under +gVisor unless the host configuration says otherwise. `dind` explicitly requests +the `runsc-docker` runtime because it runs Docker inside the sandbox. -### Network and Docker access +## Compose layout ```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] +networks: + caddy external + gitea bridge + ci bridge -job container also reaches: - ├── gitea:3000 - ├── internet - └── 127.0.0.1:2375 (the sandboxed daemon only) +services: + server Gitea, on caddy + gitea + dind gVisor Docker-in-Docker, on ci + runner act_runner, on gitea + ci ``` -The runner's own privileged Docker daemon listens on a Unix socket only. Jobs -have neither that socket nor a TCP API for it. +### Persistent paths -### Runtimes +```text +./gitea -> /data Gitea data +./dind-data -> /var/lib/docker dind storage +./dind-runsc/resolv.conf -> /etc/resolv.conf:ro dind DNS +./runner -> /data act_runner config/state +/etc/timezone -> /etc/timezone:ro Gitea timezone +/etc/localtime -> /etc/localtime:ro Gitea timezone +``` -```json -{ - "default-runtime": "runsc-host", - "runtimes": { - "runsc-host": { - "path": "/usr/local/bin/runsc", - "runtimeArgs": ["--platform=systrap", "--network=host"] - }, - "runsc-docker": { - "path": "/usr/local/bin/runsc", - "runtimeArgs": [ - "--platform=systrap", - "--net-raw", - "--allow-packet-socket-write" - ] +The Gitea HTTP port is intentionally not published; it is expected to be +fronted by Caddy through the external `caddy` network. SSH is published on +host port `222`. + +## Requirements + +- Docker with the `runsc-docker` runtime configured on the host. +- The host `daemon.json` must define a runtime equivalent to: + + ```json + { + "runtimes": { + "runsc-docker": { + "path": "/usr/bin/runsc", + "runtimeArgs": [ + "--net-raw", + "--allow-packet-socket-write" + ] + } } } -} -``` + ``` -- `runsc-host` 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-docker` 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. +- An external Docker network named `caddy`. +- A Caddy configuration that routes the public Gitea hostname to the `gitea` + container on port 3000. +- `./dind-runsc/resolv.conf` with usable DNS servers. -## Quick start - -Requirements: Docker with the `runc` runtime, Docker Compose, and outbound -network access for images. +## Usage ```bash -cp .env.example .env -# edit .env if needed +# Create the external reverse-proxy network once. +docker network create caddy -docker build -t gitea-gvisor-runner:latest runner -docker compose up -d --no-build +# Build the gVisor dind image and start the stack. +docker compose up -d --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: +Check the stack: ```bash -docker compose exec -u git gitea gitea admin user create \ - --username ciadmin --password 'CiAdminPass12345' \ - --email ciadmin@example.com --admin --must-change-password=false +docker compose ps +docker compose logs -f dind +docker compose logs -f runner ``` ### Runner registration -Two options: +`./runner` is mounted as `/data` and must contain: -1. Put an explicit registration token in `.env`: +- `config.yaml` — act_runner configuration (included here). +- `.runner` — registration state, created on first registration. - ```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`: +If the runner has not been registered yet, provide a registration token on the +first boot. One way is to add this to the `runner` service temporarily: ```yaml -services: - web: - networks: - testnet: - ipv4_address: 172.31.0.10 - probe: - extra_hosts: - - "web:172.31.0.10" +environment: + GITEA_RUNNER_REGISTRATION_TOKEN: ``` -For real e2e Compose files, use one of: +Then start the runner once, confirm `./runner/.runner` exists, and remove the +token from the Compose environment again. -- `extra_hosts` with static IPs -- explicit container IPs -- host networking inside the sandbox -- a custom DNS design +The public Gitea instance is expected at: + +```text +https://gitea.ct.cozytren.ch +``` + +## Runner configuration + +`runner/config.yaml` defines: + +- capacity `1` +- labels: + - `ubuntu-latest` → `node:22-bookworm` + - `gvisor` → `alpine:3.20` + - `docker` → `docker:28-cli` +- runner-side Docker host: `tcp://dind:2375` +- job environment: `DOCKER_HOST=tcp://127.0.0.1:2375` +- job networking: `host` inside the dind sandbox + +Jobs run with host networking inside the gVisor sandbox, so loopback points at +the dind daemon listening inside that sandbox. The runner itself reaches dind +through the `ci` network. + +Example workflows are in `scripts/`: + +```text +scripts/workflow-gvisor.yml basic gVisor / isolation checks +scripts/workflow-docker.yml Docker CLI inside the sandbox +scripts/workflow-compose.yml a Compose stack inside the sandbox +scripts/workflow-resource.yml disk / memory / CPU stress +``` + +## dind storage and overlayfs + +The dind image comes from the gVisor Docker-in-gVisor example under +`gvisor/images/basic/docker`. + +By default, `start-dockerd.sh` mounts a RAM-backed tmpfs at `/var/lib/docker`: + +```text +DOCKER_TMPFS_SIZE=5G +``` + +That is the gVisor-recommended path for Docker 29 overlayfs, but it limits +image/build storage to 5 GiB. + +To use the disk-backed `./dind-data` volume instead, uncomment: + +```yaml +command: --no-overlay +``` + +The startup script then disables Docker 29's containerd snapshotter so it can +fall back to a non-overlay storage path. Verify that the selected storage driver +works inside your gVisor version before relying on large builds. + +## Networking details + +- `dind` has no published Docker API port. +- `runner` reaches `dind:2375` only over the private `ci` network. +- CI jobs reach the dind daemon at `127.0.0.1:2375` because they share the dind + sandbox network namespace. +- `dind` has a custom `resolv.conf` mounted read-only. Keep it aligned with the + DNS setup of the deployment host. +- Docker’s embedded DNS inside nested user-defined networks can be limited + because Docker-managed iptables is disabled inside gVisor. The Compose test + uses a static IP plus `extra_hosts` for this reason. ## Security model -### What is protected +- No host `/var/run/docker.sock` is mounted into the runner or CI jobs. +- The Docker daemon used by CI is itself inside a gVisor sandbox. +- The Docker API is not published on a host port; it is reachable only from the + `ci` Compose network. +- CI job containers are created by the sandboxed dind daemon and remain inside + that gVisor sandbox. +- The `dind` container needs `cap_add: ALL` so Docker can operate inside the + sandbox. Those capabilities are perceived inside gVisor, not granted on the + host kernel. +- The remaining security boundary is gVisor itself. Use a current gVisor + release, a dedicated Docker host, and host firewall rules for untrusted CI. -- 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-host` / `runsc-docker` 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 +## Files ```text -. -├── docker-compose.yml Gitea + privileged runner -├── .env.example -├── runner/ -│ ├── Dockerfile act_runner + runsc + sandboxed dind setup -│ ├── daemon.json runsc-host and runsc-docker 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-docker -│ └── 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 +docker-compose.yml +runner/config.yaml +gvisor/images/basic/docker/Dockerfile +gvisor/images/basic/docker/start-dockerd.sh +dind-runsc/resolv.conf +scripts/workflow-*.yml ``` - -## 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/dind-runsc/resolv.conf b/dind-runsc/resolv.conf new file mode 100644 index 0000000..8967ec1 --- /dev/null +++ b/dind-runsc/resolv.conf @@ -0,0 +1,2 @@ +nameserver 1.1.1.1 +nameserver 9.9.9.9 diff --git a/docker-compose.yml b/docker-compose.yml index ed3f8ff..71fd933 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,64 +1,55 @@ -name: gitea-gvisor +networks: + caddy: + external: true + gitea: + driver: bridge + ci: + driver: bridge 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 + server: + image: docker.gitea.com/gitea + container_name: gitea + #environment: + # - USER_UID=1000 + # - USER_GID=1000 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" + networks: + - caddy + - gitea volumes: - - gitea-data:/data + - ./gitea:/data + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro 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 + # - "3000:3000" + - "222:22" + + dind: + build: + context: ./gvisor/images/basic/docker + runtime: runsc-docker + environment: + DOCKER_TLS_CERTDIR: "" + DOCKER_TMPFS_SIZE: 5G + cap_add: + - ALL + volumes: + - ./dind-data:/var/lib/docker + - ./dind-runsc/resolv.conf:/etc/resolv.conf:ro + #command: --no-overlay + # No published TCP Docker API port. + networks: + - ci runner: - build: - context: ./runner - image: gitea-gvisor-runner:latest - runtime: runc + image: docker.gitea.com/act_runner:latest restart: unless-stopped - # dockerd needs privileged mode to create the nested job containers. The job - # containers themselves always run under runsc/gVisor. - privileged: true + networks: + - gitea + - ci 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 + CONFIG_FILE: /data/config.yaml + GITEA_INSTANCE_URL: https://gitea.ct.cozytren.ch 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: + - ./runner:/data diff --git a/gvisor/images/basic/docker/Dockerfile b/gvisor/images/basic/docker/Dockerfile new file mode 100644 index 0000000..9ad7fec --- /dev/null +++ b/gvisor/images/basic/docker/Dockerfile @@ -0,0 +1,6 @@ +FROM docker:29-dind + +RUN apk add --no-cache bash iproute2 iptables + +COPY start-dockerd.sh /start-dockerd.sh +ENTRYPOINT ["/start-dockerd.sh"] diff --git a/gvisor/images/basic/docker/start-dockerd.sh b/gvisor/images/basic/docker/start-dockerd.sh new file mode 100755 index 0000000..9390067 --- /dev/null +++ b/gvisor/images/basic/docker/start-dockerd.sh @@ -0,0 +1,72 @@ +#!/bin/bash + +# Copyright 2024 The gVisor Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -xe -o pipefail + +USE_OVERLAY_DRIVER=true +while [[ $# -gt 0 ]]; do + case $1 in + --no-overlay) + USE_OVERLAY_DRIVER=false + shift + ;; + *) + shift + ;; + esac +done + +# When dockerd uses the overlay storage driver, it will try to mount an overlay +# filesystem under /var/lib/docker. gVisor only supports tmpfs as an upper +# layer, so we mount a tmpfs if it isn't already present. +if [[ "${USE_OVERLAY_DRIVER}" == "true" ]]; then + current_fs=$(stat -f -c %T /var/lib/docker 2>/dev/null || echo "none") + if [[ "${current_fs}" != "tmpfs" ]]; then + mkdir -p /var/lib/docker + mount -t tmpfs -o size="${DOCKER_TMPFS_SIZE:-2G}" tmpfs /var/lib/docker + else + echo "/var/lib/docker is already tmpfs, skipping mount." + fi +fi + +EXTRA_DOCKERD_FLAGS=() +docker_version=$(dockerd --version) +# Docker 29+ does not automatically fall back to the vfs driver when it cannot +# mount an overlayfs, so we explicitly disable it when --no-overlay is passed. +if [[ ${docker_version} =~ version\ ([0-9]+) ]] && [[ ${BASH_REMATCH[1]} -ge 29 ]]; then + if [[ "${USE_OVERLAY_DRIVER}" != "true" ]]; then + EXTRA_DOCKERD_FLAGS+=(--feature containerd-snapshotter=false) + fi +fi + +dev=$(ip route show default | sed 's/.*\sdev\s\(\S*\)\s.*$/\1/') +addr=$(ip addr show dev "$dev" | grep -w inet | sed 's/^\s*inet\s\(\S*\)\/.*$/\1/') + +# TODO(gvisor.dev/issues/14011): until we investigate/fix gVisor's handling of +# forwarding fragmented packets, match the host MTU in nested dockerd to make +# it more reliable. +mtu=$(ip -o link show dev "$dev" | sed -n 's/.*mtu \([0-9]*\).*/\1/p') + +IPTABLES="iptables" +if command -v iptables-legacy >/dev/null 2>&1; then + IPTABLES="iptables-legacy" +fi + +echo 1 > /proc/sys/net/ipv4/ip_forward +$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 + +exec dockerd-entrypoint.sh --iptables=false --ip6tables=false ${mtu:+--mtu="$mtu"} -D "${EXTRA_DOCKERD_FLAGS[@]}" diff --git a/runner/Dockerfile b/runner/Dockerfile deleted file mode 100644 index e02400c..0000000 --- a/runner/Dockerfile +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 3ebf65c..0000000 --- a/runner/act-runner-run.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/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 index 71532b1..85e783f 100644 --- a/runner/config.yaml +++ b/runner/config.yaml @@ -3,8 +3,6 @@ log: 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: @@ -12,21 +10,19 @@ runner: - "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. + # Jobs run with host networking inside the gVisor dind sandbox, where + # dockerd listens on loopback. 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. + # The dind service is on the "ci" network. + docker_host: tcp://dind:2375 + # Jobs share dind's sandbox network namespace. 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: diff --git a/runner/daemon.json b/runner/daemon.json deleted file mode 100644 index 8d41703..0000000 --- a/runner/daemon.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "default-runtime": "runsc-host", - "runtimes": { - "runsc-host": { - "path": "/usr/local/bin/runsc", - "runtimeArgs": [ - "--platform=systrap", - "--network=host" - ] - }, - "runsc-docker": { - "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 deleted file mode 100644 index df3d4c9..0000000 --- a/runner/docker-run.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/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 deleted file mode 100644 index 34ca546..0000000 --- a/runner/gvisor-entrypoint.sh +++ /dev/null @@ -1,84 +0,0 @@ -#!/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 deleted file mode 100644 index a881ea0..0000000 --- a/runner/start-dind.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/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 deleted file mode 100644 index ebe4c98..0000000 --- a/runner/start-sandboxed-dind.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/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-docker \ - --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 deleted file mode 100755 index cf0eab4..0000000 --- a/scripts/e2e-test.sh +++ /dev/null @@ -1,158 +0,0 @@ -#!/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-gvisor.yml b/scripts/workflow-gvisor.yml index a0e85f2..4a12785 100644 --- a/scripts/workflow-gvisor.yml +++ b/scripts/workflow-gvisor.yml @@ -32,12 +32,12 @@ jobs: 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 + - name: Prove network access works 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" + wget -qO- --timeout=10 https://gitea.ct.cozytren.ch/api/healthz >/dev/null + echo "OK: the job can reach the public Gitea endpoint" - name: Prove the outer Docker host API is not reachable shell: sh