Compare commits

..
Author SHA1 Message Date
agent 5025152e02 fix: run root guard tests without root privileges
CI / tests-and-images (pull_request) Failing after 14s
Runner smoke test / runner-smoke (pull_request) Successful in 1s
2026-10-16 14:11:19 +03:00
agent d178d64fc2 fix: run host audit guard test as non-root
CI / tests-and-images (pull_request) Failing after 10s
Runner smoke test / runner-smoke (pull_request) Successful in 2s
2026-10-15 15:44:23 +03:00
agent c195beba6d docs: record runner CI rerun diagnostics
CI / tests-and-images (pull_request) Failing after 11s
Runner smoke test / runner-smoke (pull_request) Successful in 4s
2026-10-14 23:49:45 +03:00
agent 7701e77b3d fix: restrict runner log ACL across rotation
CI / tests-and-images (pull_request) Failing after 12s
Runner smoke test / runner-smoke (pull_request) Successful in 4s
2026-10-14 23:47:57 +03:00
agent 73aa147881 ci: validate Caddy without Docker and document BuildKit path
CI / tests-and-images (pull_request) Failing after 13s
Runner smoke test / runner-smoke (pull_request) Successful in 4s
2026-10-14 23:16:03 +03:00
agent e373b81290 fix: align Gitea CI with runner isolation
CI / tests-and-images (pull_request) Failing after 1m17s
Runner smoke test / runner-smoke (pull_request) Successful in 4s
2026-10-14 21:09:37 +03:00
admin ac611cc878 Merge pull request 'Fix rootless Docker HOME for runner' (#45) from fix/rootless-docker-home into main
Runner smoke test / runner-smoke (push) Successful in 3s
CI / tests-and-images (push) Has been cancelled
Reviewed-on: #45
Reviewed-by: agent <agent@vakanaut.ru>
2026-10-14 14:45:57 +00:00
agent 9ec03200fb fix: restart rootless Docker with updated environment
Runner smoke test / runner-smoke (pull_request) Successful in 4s
CI / tests-and-images (pull_request) Has been cancelled
2026-10-14 17:41:24 +03:00
agent 03c5809d69 fix: persist rootless Docker unit environment
Runner smoke test / runner-smoke (pull_request) Successful in 1m0s
CI / tests-and-images (pull_request) Has been cancelled
2026-10-14 11:48:57 +03:00
agent 00922e6c09 fix: make rootless Docker home writable
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 22:18:51 +03:00
admin e6b099cf31 Merge pull request 'Make runner installer safe to resume' (#44) from fix/runner-installer-resume into main
CI / tests-and-images (push) Has been cancelled
Runner smoke test / runner-smoke (push) Has been cancelled
Reviewed-on: #44
Reviewed-by: agent <agent@vakanaut.ru>
2026-10-11 23:22:16 +00:00
agent d8a0646829 Protect runner mount image from CI path replacement
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 02:16:13 +03:00
agent 433c3059b9 Create runner image through a pinned file descriptor
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 02:01:19 +03:00
agent 4110aa54c9 Make runner setup race-safe and resumable
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 01:41:20 +03:00
agent db6ded4075 Harden runner installer path and mount checks
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 01:23:03 +03:00
agent b68421bb5b Make runner installer safe to resume
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 01:16:11 +03:00
admin 223e06ee77 Merge pull request 'Prepare isolated AkylDash infrastructure and repository CI runner' (#43) from feature/infrastructure-deployment-phase-2 into main
CI / tests-and-images (push) Has been cancelled
Runner smoke test / runner-smoke (push) Has been cancelled
Reviewed-on: #43
Reviewed-by: agent <agent@vakanaut.ru>
2026-10-11 21:57:01 +00:00
agent 52027ecf81 Accept empty subordinate ID allocation files
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 00:51:29 +03:00
agent e5a4dab5f3 Fix runner installer ID allocation and guards
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 00:47:19 +03:00
agent e034fdb816 feat(infra): prepare isolated repository CI runner
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
2026-10-12 00:35:42 +03:00
admin a34f516de8 Merge pull request 'Подготовить воспроизводимую инфраструктуру production VPS' (#42) from feature/infrastructure-documentation-and-bootstrap into main
CI / tests-and-images (push) Has been cancelled
Reviewed-on: #42
Reviewed-by: agent <agent@vakanaut.ru>
2026-10-11 20:22:22 +00:00
34 changed files with 1993 additions and 132 deletions

No files matched your search

+35 -5
View File
@@ -7,7 +7,7 @@ on:
jobs:
tests-and-images:
runs-on: ubuntu-latest
runs-on: akyldash-ci
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
@@ -23,19 +23,49 @@ jobs:
run: bash infra/bootstrap/test-host-guard.sh
- name: Check verifier helper argument guard
run: bash infra/bootstrap/test-verify-helper.sh
- name: Check unprivileged guard test helper
run: bash infra/test/test-run-as-unprivileged.sh
- name: Check host audit root guard
run: bash infra/bootstrap/test-audit-host.sh
- name: Check Compose helper allowlist
run: bash infra/deploy/test-compose-helper.sh
- name: Check production config root guard
run: bash infra/deploy/test-production-config-guard.sh
- name: Check runner config and isolation guards
run: |
bash infra/runner/test-runner-config.sh
bash infra/runner/test-ci-container-operations.sh
bash infra/runner/test-runner-log-acl.sh
bash infra/runner/test-install-runner-idempotency.sh
bash infra/runner/test-install-runner-guard.sh
- name: Check infrastructure shell syntax
run: |
bash -n infra/bootstrap/bootstrap-ubuntu-24.04.sh infra/bootstrap/host-guard.sh \
infra/bootstrap/verify.sh infra/bootstrap/verify-helper.sh infra/deploy/install-helper.sh \
infra/bootstrap/test-verify-helper.sh
infra/bootstrap/verify.sh infra/bootstrap/verify-helper.sh infra/bootstrap/audit-host.sh \
infra/deploy/install-helper.sh infra/deploy/compose-helper.sh infra/deploy/test-compose-helper.sh \
infra/deploy/prepare-production-config.sh infra/deploy/test-production-config-guard.sh \
infra/bootstrap/test-audit-host.sh infra/bootstrap/test-verify-helper.sh \
infra/test/run-as-unprivileged.sh infra/test/test-run-as-unprivileged.sh \
infra/runner/install-runner.sh infra/runner/install-runner-lib.sh \
infra/runner/act-runner-healthcheck.sh infra/runner/test-runner-config.sh \
infra/runner/test-ci-container-operations.sh \
infra/runner/test-runner-log-acl.sh \
infra/runner/test-install-runner-idempotency.sh infra/runner/test-install-runner-guard.sh
python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/runner/secure-runner-image.py').read_text())"
- name: Run rollback helper tests
run: python3 -m unittest discover -s infra/deploy -p 'test_*.py' -v
- name: Validate production Compose and Caddyfile
run: |
secret_file=$(mktemp)
trap 'rm -f "$secret_file"' EXIT
caddy_dir=$(mktemp -d)
trap 'rm -f "$secret_file"; rm -rf "$caddy_dir"' EXIT
REVIEW_SECRET_FILE="$secret_file" docker compose --env-file deploy/production/.env.example -f deploy/production/compose.yaml config --quiet
docker run --rm --entrypoint caddy -v "$PWD/deploy/production/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2.11.6-alpine@sha256:881bbc60f9986d5ab8e7cfd6cf7e4ef3c9c0439fef2429d035d065577882f028 validate --config /etc/caddy/Caddyfile --adapter caddyfile
test "$(uname -m)" = x86_64
caddy_archive="$caddy_dir/caddy.tar.gz"
curl --fail --location --retry 3 --output "$caddy_archive" https://github.com/caddyserver/caddy/releases/download/v2.11.6/caddy_2.11.6_linux_amd64.tar.gz
echo '422771007d505ea97efd1177a4905b2c1a471cd426668f2ace3bcda3d8e30b11f9b1610bfb02c6ad60f2a795f56124f2f5eec6409c17d5a0dd4c21a11375fb94 '"$caddy_archive" | sha512sum --check
tar -xzf "$caddy_archive" -C "$caddy_dir" caddy
"$caddy_dir/caddy" validate --config deploy/production/Caddyfile --adapter caddyfile
- name: Build production images
run: |
docker build -f deploy/production/Dockerfile.backend -t akyldash-backend:ci .
+26
View File
@@ -0,0 +1,26 @@
name: Runner smoke test
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
jobs:
runner-smoke:
runs-on: akyldash-ci
steps:
- name: Verify isolated runner boundary
run: |
host_uid=$(awk 'NR == 1 {print $2}' /proc/self/uid_map)
test "$host_uid" -gt 0
test ! -S /var/run/docker.sock
for socket in /run/user/*/docker.sock; do
test ! -S "$socket"
done
test -z "${DOCKER_HOST:-}"
test ! -e /etc/akyldash/production.env
test ! -e /etc/akyldash/review_secret
test ! -e /opt/akyldash/current
printf 'Isolated runner: version=%s host=%s uid-map=%s\n' \
"$GITEA_ACTIONS_RUNNER_VERSION" "$(hostname)" "$host_uid"
+7
View File
@@ -13,6 +13,13 @@ Python, SQLite и OpenSearch. Production пока не развернут.
- SSH alias — `akyldash_vps`; используй только read-only диагностику. Не давай
`codex` общий sudo или доступ к Docker socket. Root-действия требует владелец.
Для Gitea используй `gitea-api`, не читай файлы с учётными данными.
- Репозиторный Gitea Actions runner описан в
[CI_RUNNER.md](docs/operations/CI_RUNNER.md). Регистрация выполняется
владельцем через Settings → Actions → Runners для `admin/akyldash`; токен
вводится интерактивно и не попадает в Git. Runner использует отдельный
rootless Docker daemon; job-контейнеры не получают Docker socket или
production secrets. Не включай production deployment из CI без отдельного
проверенного deploy-helper.
- Локальные проверки: `PYTHONPATH=backend python3 -m unittest discover -s backend -p 'test_*.py' -v` и
`python3 -m unittest discover -s tools/telegram-bot -p 'test_*.py' -v`,
`python3 -m unittest discover -s infra/backup -p 'test_*.py' -v` и
+2
View File
@@ -2,6 +2,8 @@
## Не выпущено
- Runner installer сохраняет `HOME` и XDG-пути в user-unit `docker.service`, перезапускает активный daemon и проверяет окружение его процесса.
- Runner installer защищает image и mountpoint root-owned home-каталогом, оставляет регистрацию и workspace в runner-owned каталоге, безопасно форматирует образ по открытому FD и проверяет `nosuid,nodev`.
- Backend `0.11.3`: ключ подписи поисковых снимков читается из Docker secret-файла, а не из аргументов процесса. Добавлена базовая инфраструктура VPS, Caddy HTTPS proxy с разделёнными Compose-сетями и CI-проверка конфигурации; публикация образов и production-деплой остаются выключены до проверки runner, registry, backup/restore и ограниченного deploy-helper.
- Frontend `0.1.2`: на планшетной ширине экран поиска переходит в одну колонку, чтобы фильтры, результаты и документ помещались в окно.
- Backend `0.11.2`: смена пароля требует текущий пароль и запрещает оставить прежний, включая временный пароль при первом входе.
+15 -7
View File
@@ -14,18 +14,26 @@ account is intentionally outside the `sudo` and `docker` groups because access
to the Docker socket grants root-equivalent control. Run host operations with
the narrowly required `sudo` command; do not use `docker` as `codex` directly.
```bash
sudo install -d -o root -g root -m 0700 /etc/akyldash
sudo install -o root -g root -m 0600 deploy/production/.env.example /etc/akyldash/production.env
sudo sh -c 'umask 077; openssl rand -hex 32 > /etc/akyldash/review_secret'
sudoedit /etc/akyldash/production.env
```
After reviewing the host audit and confirming these files do not already exist,
the owner can create them from the approved checkout with
`sudo bash infra/deploy/prepare-production-config.sh`. The script refuses to
overwrite existing configuration, installs the tracked env example with mode
`0600`, and generates a random review secret with mode `0600`. It does not
start Compose or create volumes. Review and set `DATA_ROOT` in the protected
env file before deployment.
Set `DATA_ROOT` to the approved data directory and ensure the normalized corpus
is at `$DATA_ROOT/minjust-normalized/`. The first host setup is documented in
[`docs/operations/DEPLOYMENT.md`](../../docs/operations/DEPLOYMENT.md); the
root bootstrap installs packages and creates directories, but does not deploy
the application or alter SSH, firewall, user groups, or sudoers.
the application or alter SSH, firewall, user groups, or sudoers. The restricted
`akyldash-compose` helper allows only root-owned Compose `config` and `status`;
service start/stop remains an owner-run root operation.
The repository Gitea Actions runner is an isolated CI worker described in
[`docs/operations/CI_RUNNER.md`](../../docs/operations/CI_RUNNER.md). It has no
production Docker socket, production env files, or application checkout. CI
does not deploy or change production; all deployment remains owner-run.
## First deployment and upgrades
+35 -15
View File
@@ -8,7 +8,8 @@ printing key contents, then check the connection:
```bash
ssh -F ~/.ssh/config -G akyldash_vps | awk '$1 == "hostname" || $1 == "user" || $1 == "port" || $1 == "identityfile" { print }'
test -r ~/.ssh/akyldash_codex && echo 'SSH key is available'
ssh -F ~/.ssh/config -o BatchMode=yes akyldash_vps 'id; hostname'
ssh -F ~/.ssh/config -o BatchMode=yes akyldash_vps id
ssh -F ~/.ssh/config -o BatchMode=yes akyldash_vps hostname -f
gitea-api GET /version
gitea-api GET /repos/admin/akyldash
```
@@ -21,14 +22,27 @@ checks. Never print a private key, token, or complete environment file.
- SSH alias: `akyldash_vps`, user `codex`, host `206.223.249.118`, port `22`.
- SSH configuration: `~/.ssh/config`.
- Identity file: `~/.ssh/akyldash_codex` (path only; never copy its contents).
- `codex` can run unprivileged read-only diagnostics. The audited account has no
non-interactive sudo and must not be added to `sudo` or the `docker` group.
- Host package installation, service setup, firewall changes, secret creation,
backup creation, recovery apply, and deployment require owner approval and a
reviewed root command. After the owner installs the root-owned repository
checkout, `infra/deploy/install-helper.sh` can grant a fixed read-only
verifier and guarded rollback command through sudoers; neither helper is
installed on the audited VPS.
- `codex` can run unprivileged read-only diagnostics and read
`/var/log/akyldash-runner/act_runner.log` through a file ACL. It has no sudo
or Docker group membership; Docker CLI access to the daemon is denied. Do not
add it to either group. The runner installer in PR #46 narrows this to search
permission on the dedicated log directory and read permission on that one
file, preserved by systemd startup and logrotate hooks.
- Bootstrap is complete. Docker and Compose are active, but no root-owned
repository checkout or restricted helper is installed yet. The owner can run
`infra/bootstrap/audit-host.sh` from the reviewed root-owned checkout to
report Docker containers/volumes, protected-file metadata, UFW rules, ports,
and ISPmanager status without showing secret contents or changing state.
- Host package/service configuration, firewall changes, protected env/secret
creation, backup creation, recovery apply, and production deployment require
a reviewed owner/root command. `infra/deploy/install-helper.sh` grants the
fixed verifier, read-only Compose `config`/`status`, and guarded rollback
commands. It does not grant general sudo or Docker access; it is not
installed on the VPS.
- `infra/deploy/prepare-production-config.sh` is an owner-run root operation.
It refuses to overwrite existing files, copies only the tracked env example,
generates a random review secret, and writes both files with mode `0600`.
It does not start Compose or create volumes.
- Never connect to other VPS hosts or Synology as part of this deployment.
This execution environment is WSL2. The repository is on the Windows-mounted
@@ -47,19 +61,25 @@ limitation and do not retrieve it elsewhere.
environment. Never inspect local credential files, print environment values,
or construct HTTP authorization headers.
- The audited API token can read/write this repository and create issues, but
does not have `read:user` or `read:package`. An API `403` caused by a missing
scope is not evidence that the account itself lacks the permission.
does not have `read:user` or `read:package`. Listing repository Actions
runners returns `403` because the API principal is not the repository owner.
An API `403` caused by missing scope/ownership is not evidence that no runner
exists.
- Protected `main` requires one approval. Do not push directly to `main`, merge
automatically, or start a review. Work on a feature branch and use a PR.
- Gitea Actions and package features are enabled for the repository, but runner
availability and package publishing permissions have not been confirmed.
- Gitea Actions and package features are enabled for the repository. The owner
reports the repository-level runner is registered and Idle, and its smoke
workflow passes on `akyldash-ci`; the runner inventory endpoint returns 403
to this non-owner API principal. The registration token remains owner-managed
in the runner's protected state file. Do not re-register or rotate it unless
the owner confirms that action. See [CI_RUNNER.md](CI_RUNNER.md).
## Who can do what
| Role | Operations |
|---|---|
| `codex` over SSH | Read-only host diagnostics; inspect service health and public listeners |
| Restricted verifier | Runs the root-owned read-only drift check; not installed on the audited VPS |
| `codex` over SSH | Unprivileged diagnostics; Docker daemon, UFW rules, and protected paths require the root audit script |
| Restricted helpers | Read-only drift check and Compose `config`/`status`, plus guarded rollback; not installed on the audited VPS |
| Restricted rollback helper | Can restore prior local backend/OpenSearch images from a verified backup after an explicit data-compatibility confirmation; not installed on the audited VPS |
| VPS owner/root | Bootstrap, package installation, SSH/firewall, secret setup, recovery, and approval of production changes |
| Gitea repository writer | Feature branch push and PR creation; protected-main merge needs an approval |
+264
View File
@@ -0,0 +1,264 @@
# AkylDash Gitea Actions runner
## Scope and isolation
The deployment follows the official [Gitea 1.25 act_runner guide](https://docs.gitea.com/1.25/usage/actions/act-runner/)
for repository-scoped registration. Gitea warns that access to a Docker daemon
is root-equivalent; the dedicated rootless daemon is used instead of the
production daemon. The pinned binary and checksum are published in the
[official Gitea download directory](https://dl.gitea.com/gitea-runner/0.2.13/).
The runner is reserved to repository `admin/akyldash`, using the token under
`https://git.vakanaut.ru/admin/akyldash/settings/actions/runners`. Do not use
organization or instance runner settings. Pin the official `act_runner`
`0.2.13` x86_64 binary from `dl.gitea.com`; the installer verifies its SHA-256
before placing it on the host.
CI jobs run in `docker.gitea.com/runner-images:ubuntu-24.04` containers with
capacity 1, per-job limits of 2 CPU, 3 GiB RAM and 512 processes, and a 15 GiB
dedicated ext4 loop-backed Docker data filesystem. The runner account's home
directory is root-owned mode `0711`, so CI cannot rename the image or mountpoint
entries. Docker config remains under `.config`; registration state and the
runner workspace live in `.config/act-runner`, which is runner-owned. The
rootless Docker setup and user service use `.config/act-runner` as writable
`HOME`, `.config` as `XDG_CONFIG_HOME`, and
`.config/act-runner/.local/share` as `XDG_DATA_HOME`. This keeps Docker config
and its systemd user unit in the existing `.config` tree without granting
write access to the protected home.
The runner system service uses `ProtectHome=read-only`. `ProtectHome=yes`
hides `/run/user`, which contains the rootless Docker socket needed by the runner
service; read-only protection keeps that path visible without making home paths
writable. The installer accepts only the known prior unit with this one-line
difference and refuses any other service-unit drift. The rootless Docker daemon
and runner user are separate from production Docker; `codex` is not added to
sudo or Docker groups. Jobs do not receive the rootless Docker socket, the
production Docker socket, production environment/secrets, or arbitrary host
bind mounts. The runner account has no access to `/etc/akyldash` or the
root-owned application checkout. These are host permission boundaries, not a
claim that untrusted project code is safe; review workflow changes and actions
before merging them.
The runner service restarts on failure and boot. Systemd caps the runner
account's shared slice to 2.5 CPU, 4 GiB RAM and 2048 tasks; the rootless
daemon is separately capped to 2 CPU, 4 GiB and 1024 tasks, while each job has
the limits above. Runner logs go to a rotated file (10 MiB, 7 copies). A
systemd timer checks the runner service and the rootless Docker API each minute;
on failure it restarts the fixed runner service. No UFW changes or public
metrics ports are needed. Runner cache is disabled.
The runner daemon log is `/var/log/akyldash-runner/act_runner.log`. The
installer keeps its directory root-owned, grants `codex` only search permission
on that directory, and limits file access to the runner owner plus a named
read-only ACL for `codex`; group and other users have no file access. Systemd
starts with `UMask=0077`, and its fixed `ExecStartPost` command reapplies the
file ACL. Logrotate uses `copytruncate` and reapplies the same ACL after each
rotation. This access is limited to the runner daemon log; it does not grant
access to runner registration state, job workspaces, Docker state, or Gitea
workflow logs. The daemon log records task dispatch metadata, not step output.
The registered project label is `akyldash-ci`, mapped to the pinned
`docker.gitea.com/runner-images:ubuntu-24.04` image. Both `ci.yaml` and
`runner-smoke.yaml` target this exact project label; neither uses the generic
`ubuntu-latest` label. The runner inventory API is owner-only, so the current
API account cannot independently list the registered labels; the owner reports
that the runner is Idle and the smoke workflow succeeds.
The job container receives neither the rootless Docker socket nor the system
Docker socket (`container.docker_host: "-"`). The CI operations have different
engine requirements:
| Operation | Purpose | Engine requirement |
| --- | --- | --- |
| `docker compose ... config --quiet` | Interpolate and validate production Compose configuration | Compose client only; this command does not start containers or contact a daemon. |
| Caddy `validate` | Check the production Caddyfile syntax and directives | Caddy binary only; CI downloads the exact version used by the pinned image and checks its SHA-512. |
| `docker build` for backend and OpenSearch | Exercise Dockerfile instructions, base-image resolution, and the OpenSearch plugin install | A container builder is required; ordinary Python/shell tests cannot replace this check. |
Do not run rootless BuildKit inside the current job container. The official
BuildKit rootless container recipe requires relaxing seccomp/AppArmor and
system path restrictions; its documented no-process-sandbox fallback lets
build steps signal processes in the BuildKit daemon and is explicitly
discouraged. This runner intentionally keeps its job security profile intact.
The recommended image-build path is a separate, disposable BuildKit VM, with
the current runner acting only as a `buildctl` client. Run BuildKit as a
non-root account with its own subordinate UID/GID range and scratch disk; use
mutual TLS over a private network, no Docker socket, no production credentials,
no route to production, one build at a time, and delete the VM and cache after
the job. Keep the test job on `akyldash-ci`; place image builds in a dependent
job on a separate builder label. This keeps arbitrary PR Dockerfile commands
off the runner and production host kernel. Gitea 1.25.5 and act_runner 0.2.13
need no special BuildKit integration: the workflow invokes pinned `buildctl`
against the remote BuildKit API.
For a first sizing estimate, allocate the disposable builder 2 vCPU, 4 GiB RAM,
and 10 GiB temporary disk at concurrency 1. Disable persistent cache or cap it
to 6 GiB with BuildKit garbage collection; remove OCI output archives after
validation. These are starting limits, not measured requirements. Reduce them
only after recording peak memory and disk use for both Dockerfiles. The current
VPS has 7.7 GiB RAM and the runner already has 3 GiB job / 4 GiB account limits,
so colocating a builder there would contend with jobs and share the host kernel;
it is not the recommended deployment.
Provisioning that disposable VM and private network is an owner-level bootstrap
step. It must pin BuildKit and its checksum, create the non-root account and
subuid/subgid mapping, enforce CPU/RAM/disk and single-job limits, expose only a
TLS-authenticated BuildKit endpoint to the runner, issue a short-lived
per-job client certificate, and destroy the VM after the build. Do not enable
`--privileged`, relax seccomp/AppArmor, set
`--oci-worker-no-process-sandbox`, mount either Docker socket, or provide
production secrets. Until this bootstrap is approved and available, keep both
image builds required and expect the full CI job to remain blocked at those
steps.
Production deployment is not automated.
## Installation and registration
Review the root script and host audit output before running it. It installs
`uidmap`, `dbus-user-session`, `curl`, `logrotate`, and Docker's rootless extras;
creates the dedicated system user and selects the first free, shared 65536-ID
range from `/etc/subuid` and `/etc/subgid`; reserves 15 GiB
for runner images/workspaces; and configures systemd services. It starts only
the separate rootless Docker daemon; the runner and health timer stay disabled
until repository registration. It does not change
SSH/UFW, production Docker configuration, application data, or production
secrets. It can be rerun after partial setup: it validates and reuses an
existing runner account, subordinate ID mappings, image, and mount unit. An
existing image must be exactly 15 GiB and contain ext4; a mismatch stops the
installer without resizing or formatting it. The runner account must retain
a non-root system UID below `UID_MIN`, its expected home, primary group, and
sole supplementary group. After validating the account, the installer locks
its home directory to root ownership and mode `0711`; it refuses to rerun while
the runner service is active, so it cannot interrupt a job. The mount
is started only when it is not already active, and an active mount must be the
expected ext4 loop device backed by the runner image with both `nosuid` and
`nodev` active. Runner-home directories and user configuration files are
created in runner-owned subdirectories. Root creates only the first `.config`
entry beneath the already locked home; subsequent directory and config writes
run as `akyldash-runner`. The installer rejects static symlinks and validates
ownership and mode after setup. This also normalizes the `0755` intermediate
directories left by the first installer version. Conflicting files or state
stop the installer for manual inspection. A new image requires at least 25 GiB
free on `/`. Image creation opens each parent component without following
symlinks, creates the image exclusively relative to the opened directory, and
passes the open file descriptor to `mkfs.ext4`; validation checks the same inode
and rejects path replacement. Systemd mounts the image under the root-owned home
entry, which the runner cannot replace after validation.
If the reviewed checkout is not present at the inventoried path, first verify
that the target is absent and clone the reviewed `main` there. Do not overwrite
an existing checkout.
```bash
sudo test ! -e /opt/akyldash/current
sudo git clone --branch main \
--single-branch https://git.vakanaut.ru/admin/akyldash.git \
/opt/akyldash/current
```
From that root-owned reviewed checkout on the VPS:
```bash
sudo bash /opt/akyldash/current/infra/runner/install-runner.sh
```
Then, as a repository owner, open repository **Settings → Actions → Runners**,
create a repository-level runner, and copy its registration token locally. Do
not send the token in chat or save it in the checkout. Register interactively
in a terminal so it is not placed in shell history or process arguments:
```bash
sudo -u akyldash-runner env HOME=/var/lib/akyldash-runner/.config/act-runner \
/usr/local/bin/act_runner \
--config /etc/akyldash-runner/config.yaml register
```
Enter `https://git.vakanaut.ru/`, the token, runner name `akyldash-ci-vps-01`,
and label `akyldash-ci:docker://docker.gitea.com/runner-images:ubuntu-24.04`
when prompted. The config sets the label and capacity; verify them in the
repository runner settings. The token is saved only in the mode-0700 runner
runtime directory, outside Git. Start/enable the runner after registration:
```bash
sudo systemctl enable --now akyldash-act-runner.service
sudo systemctl enable --now akyldash-runner-healthcheck.timer
sudo systemctl status akyldash-act-runner.service
sudo systemctl status akyldash-runner-healthcheck.timer
```
The interactive command's terminal behavior should be confirmed before pasting
the token. If it echoes input, stop and use the repository settings to revoke
that token; do not put it in command-line arguments or environment variables.
## Validation
1. Confirm the runner is **Online** in the repository runner settings, with the
expected name and `akyldash-ci` label.
2. Confirm **Runner smoke test** runs for the open PR (or dispatch it manually).
It checks that production
sockets, files, environment secrets, and writable application paths are not
present in the job container.
3. Confirm the run reports the expected runner, succeeds, and the runner
service and health timer remain active.
4. Confirm both workflows target `akyldash-ci`, and verify the container has no
system or runner-account Docker socket, production secret, writable host
checkout, or privileged execution. Do not add a production deploy workflow
or secrets to this runner until a separate restricted deploy mechanism is
reviewed.
## Upgrade
Update `runner_version` and its expected official SHA-256 together in
`infra/runner/install-runner.sh`, review upstream release compatibility with
the installed Gitea, and open a PR. Do not replace the binary while a job is
active. Stop the runner, install/verify the new binary, then start it and
confirm Online plus a smoke run. Preserve
`/var/lib/akyldash-runner/.config/act-runner/.runner`.
## Recovery and rollback
The runner is disposable: production data and secrets are not on its filesystem.
For a runner process failure, inspect `systemctl status` and
`journalctl -u akyldash-act-runner.service`; restart the fixed runner service.
If installation stops after creating or enabling the mount unit, inspect the
image and mount with `stat`, `blkid`, `findmnt`, and `losetup`, then rerun the
reviewed installer only when the image is 15 GiB ext4 and the active mount is
backed by it. The installer recognizes that state and does not format or
restart the mounted filesystem. If size, filesystem, unit contents, or backing
device differ, stop and resolve the state manually; never format the existing
image as a retry.
For lost/corrupt registration state, stop the service and obtain a fresh
repository-level token from Settings → Actions → Runners. Preserve the 15 GiB
data image and state for diagnosis; re-register only after the repository
owner confirms/revokes the old runner in Gitea. The images/cache can be rebuilt
from the workflow. Never format or remove an existing runner store as an
automatic recovery step.
## Status
The owner reports that the repository-level runner is registered and Idle, and
that `runner-smoke.yaml` succeeds. Read-only checks on 2026-10-14 confirmed the
runner service and health timer are active, the runner account has no
supplementary groups, and the active service uses the rootless Docker socket.
The live service has `ProtectHome=read-only`; the installer still needs the PR
update applied by an owner-run command after merge. Read-only SSH now confirms
that act_runner 0.2.13 declares `[akyldash-ci]` and accepts task 301; its log
does not include workflow step output. The Actions jobs API returns an empty
list for completed run 49, so step details are not available through the
current API account. The repository runner inventory API returns 403 to the
current non-owner API account. PR #46 pins the narrow log ACL and its rotation
hooks; this installer change has not been applied to the VPS. On the updated
PR head `7701e77`, CI run 51 also failed after task 303 was accepted, while
smoke run 52 passed. The daemon log still exposes no job or step detail and
the Actions jobs endpoint is empty for run 51, so its failure remains
unattributed. The owner later provided the full log for task 305 (run 53):
`Check host audit root guard` exited 1 before Docker builds began. The test had
assumed its caller was non-root, but Gitea job commands run as root in this
container. The next run confirmed this guard passed, then failed at
`Check production config root guard` for the same UID assumption; Compose
allowlist validation passed. The production-config and runner-installer tests
had the same flaw. These three tests now use the shared
`infra/test/run-as-unprivileged.sh` helper to test denial as UID 65534 when CI
itself runs as root. The helper has a workflow regression test and prints a
diagnostic if `setpriv` cannot switch user. All production guards remain
unchanged.
+164 -56
View File
@@ -1,31 +1,69 @@
# Infrastructure current state
Last audit: 2026-10-11. Source: read-only SSH session as `codex`, local
repository inspection, and Gitea API. This document separates measured facts
from planned configuration.
Last audit: 2026-10-14. Source: read-only SSH session as `codex`, local
repository inspection, Gitea API, and owner-reported workflow results.
Root-only Docker state, UFW rule details, and protected file metadata remain
unverified.
## VPS facts
- Host: `avprogs.hlab.kz`, `206.223.249.118`, SSH port `22`, user `codex`.
- OS/kernel: Ubuntu Server `24.04.5 LTS`, `6.8.0-142-generic`.
- Resources: 4 vCPU, 7.7 GiB RAM, 3.8 GiB swap, 99 GiB disk with 93 GiB free.
- OS: Ubuntu Server `24.04.5 LTS`; kernel `6.8.0-142-generic` from the prior
inventory audit.
- Resources: 4 vCPU, 7.7 GiB RAM, 3.8 GiB swap, 99 GiB disk with 92 GiB free
at this audit.
- Network: interface `ens3`, IPv4 `206.223.249.118/32`.
- `codex` is UID/GID 1000, groups `codex` and `users`; `sudo -n true` requires
a password. The current WSL2 session verified the SSH alias using the
explicit user config and approved read-only SSH execution.
a password. Docker CLI cannot access `/var/run/docker.sock` as `codex`.
- SSH service is running. The inspected sshd configuration has public-key and
password authentication enabled and `PermitRootLogin yes`; no SSH changes
were made.
- Docker, Docker Compose, Git, Nginx, Caddy, Certbot, application paths, and
application services are absent. Only base OS services and SSH were running.
- Public listeners observed: TCP `22`; DNS listeners are limited to loopback
(`127.0.0.53` and `127.0.0.54`).
- UFW is reported active in the supplied VPS notes, but the audit account could
not independently read its status. Treat firewall state and rules as
unverified.
- `akyldash.kg` resolves to Cloudflare IPv4/IPv6 edge addresses from the VPS.
Both HTTP and HTTPS return Cloudflare `521`; the origin is currently
unreachable through the proxy.
- Bootstrap completed. Docker CE/CLI `29.9.0`, Compose `5.6.0`, containerd
`2.4.1`, and runc `1.5.2` are installed; the system Docker daemon API remains
inaccessible to `codex`.
- `/etc/docker/daemon.json` has the expected `local` log driver and `10m` / `3`
rotation limits. Bootstrap paths exist with root ownership: `/opt/akyldash`
mode `0755`, `/etc/akyldash` and `/var/backups/akyldash` mode `0700`, and
`/var/lib/akyldash/data` mode `0750`.
- `/opt/akyldash/current`, verifier/rollback binaries, and the sudoers file are
absent. `codex` has not received sudo or Docker-group access. Metadata for
`/etc/akyldash/production.env` and `/etc/akyldash/review_secret` could not be
checked because `/etc/akyldash` is root-only.
- TCP listeners observed: SSH `22` and loopback DNS only; no listener on `1500`,
`80`, or `443`. No ISPmanager package or service unit was found through the
unprivileged checks; root can confirm with the audit script below.
- Owner reports UFW is active and allows TCP `22`, `80`, `443`, and `1500`.
Rule details were not independently read; no firewall changes were made.
- Read-only runner checks on 2026-10-14 confirmed `akyldash-runner` is UID 999,
GID 988, with no supplementary groups; the runner service and health timer are
active. Its systemd environment points Docker CLI to
`unix:///run/user/999/docker.sock`; the service's `ExecStartPre` Docker
health check succeeded. The service has `ProtectHome=read-only`,
`ProtectSystem=strict`, `NoNewPrivileges=yes`, `PrivateTmp=yes`, kernel
protections, and `RestrictSUIDSGID=yes`. Its only writable paths are runner
runtime/config, logs, and `/run/user/999`. The temporary live `ProtectHome`
change is not yet in `main` and this PR pins it in the installer.
- `systemd-analyze verify` accepted the active runner unit. `systemd-analyze
security` reports exposure 7.4 (medium) because several optional sandbox
filters are unset; the live process itself runs as UID/GID `999:988`, has
effective and permitted capabilities `0`, and `NoNewPrivs=1`. No
supplementary groups are present.
- The owner granted `codex` ACL access to `/var/log/akyldash-runner/act_runner.log`.
Read-only SSH confirmed the directory is `akyldash-runner:akyldash-runner`
mode `0750` with `codex:r-x`, while the log is `root:root` mode `0644` with
`codex:r--` and `other::r--`. The inspected log contains runner task metadata
only, no workflow step output. The active log is therefore currently
world-readable; PR #46 changes IaC to a root-owned directory, runner-owned
private log, `codex` search/read ACLs only, and ACL reapplication after
service startup and log rotation. No VPS changes were made.
- The unprivileged check did not find `/var/run/docker.sock`; the runner user
is not in `sudo` or `docker` groups. Production secret file metadata remains
root-only and was not independently checked. The Gitea runner inventory API
returns `403` to this non-owner account. The owner reports the registered
runner is **Idle** and `runner-smoke.yaml` succeeds with label `akyldash-ci`.
- `akyldash.kg` resolves to Cloudflare IPv4/IPv6 edge addresses. From the VPS,
HTTP, HTTPS, and `/review` still return Cloudflare `521`; origin TLS and
Cloudflare Full (strict) are not verified.
## Application and Gitea facts
@@ -33,35 +71,96 @@ from planned configuration.
- The repository API reports push permission, Actions and packages enabled, and
PRs enabled. `main` is protected and requires one approval; the current API
principal cannot push or merge directly to `main`.
- The Gitea token lacks `read:user` and `read:package`; runner status and package
publishing permissions could not be checked. This change adds
`.gitea/workflows/ci.yaml`; PR #42's run remains `Waiting to run` at the last
status check, so a compatible runner is not confirmed.
- Nothing is running on the VPS. Repository Compose now describes Caddy
`2.11.6` pinned by digest, Python Search API `0.11.3`, SQLite account/review
data, and OpenSearch `3.7.0` with `analysis-icu`.
- Both repository workflows are active in Gitea. `runner-smoke.yaml` targets
`akyldash-ci`; `ci.yaml` still targets `ubuntu-latest` in `main`, which has no
matching online runner. This PR changes it to the project label.
- The Gitea runner inventory API returns `403` because this API principal is
not the repository owner. The registered runner's label list cannot be read
directly; the owner-reported successful smoke run confirms the custom label
is accepted. Package publishing permissions remain unverified.
- No public application listener is observed on TCP `80`/`443`. Docker
container/volume state still requires the root audit. Repository Compose describes
Caddy `2.11.6` pinned by digest, Python Search API `0.11.3`, SQLite
account/review data, and OpenSearch `3.7.0` with `analysis-icu`.
- The target publishes only Caddy on TCP `80`/`443`. Backend and Caddy share a
proxy network; OpenSearch and backend share a separate internal network, and
the backend has no host port. Caddy certificate storage, OpenSearch, and
application data use persistent volumes/bind mounts. TLS, registry digest
deployment for backend/OpenSearch, backup, rollback helper, and systemd
deployment are not configured on the host.
backend has no host port. Caddy certificate storage, OpenSearch, and
application data use persistent volumes/bind mounts.
- The root-owned repository checkout, production env/secret files, Compose
volumes/containers, backup, verifier/rollback helpers, and application are
not confirmed installed. TLS and registry digest deployment for
backend/OpenSearch are not configured.
- The repository has a cold-backup archive/verification tool and a one-shot
restore apply tool that requires a marked replacement host. Backup/restore
tests use synthetic data; neither tool has run against production. The
archive preflight now permits a clean first deployment to skip backup,
requires backup for existing persistent data even without containers,
allows absent named volumes only in explicit corpus-only initial-deployment
mode, and rejects inaccessible/ambiguous mounts and incomplete/running
service containers. Initial deployment docs require a second verified backup
after index and admin initialization.
archive preflight permits a clean first deployment to skip backup, requires
backup for existing persistent data even without containers, allows absent
named volumes only in explicit corpus-only initial-deployment mode, and
rejects inaccessible/ambiguous mounts and incomplete/running service
containers. Initial deployment docs require a second verified backup after
index and admin initialization.
- Recovery bootstrap has an explicit `--recovery-target` mode that refuses the
inventoried production hostname/IP; its host-identity guard has shell tests.
The mode has not been run on a VPS.
- The repository defines a root-owned read-only verifier, rollback helper, and
owner-run installer with exact sudoers command rules. None is installed on
the VPS.
- An isolated local Compose smoke test built the backend/OpenSearch images,
- The repository defines a root-owned read-only verifier, Compose `config` and
`status` helper, guarded rollback helper, and installer with exact sudoers
command rules. None is installed on the VPS. CI contains no production
deployment job; starting/stopping services remains owner-run.
- A repository-scoped official `act_runner` `0.2.13` installation is managed
in `infra/runner/`: rootless Docker under `akyldash-runner`, 15 GiB ext4
loop-backed image/workspace storage, capacity 1, per-job limits (2 CPU,
3 GiB RAM, 512 processes), account slice limits (2.5 CPU, 4 GiB RAM, 2048
tasks), rotated file logs, and a systemd health timer. Jobs use the
`akyldash-ci` label and do not receive the rootless or production Docker
socket. The owner reports a partial runner installation: the 15 GiB ext4
loop-backed store is active on `/dev/loop0`. The owner reports the runner is
registered and Idle, and the smoke workflow succeeds. This PR makes no VPS
changes. The installer locks the runner home to root ownership
(`0711`) so CI cannot replace the image or mountpoint, while writable config
and runtime state remain in runner-owned subdirectories. It reuses legacy
`0755` config directories, creates the image through a pinned file descriptor,
rejects path replacement, and requires mount options `nosuid,nodev`.
The reported installation blocker is that rootless setup receives this
protected directory as `HOME`; the installer assigns writable runner-owned
HOME/XDG paths, persists them in the `docker.service` user-unit drop-in, and
restarts an active daemon and checks the running process environment. The
runner service's temporary `ProtectHome=read-only` workaround is also
committed to the installer with an exact known-drift migration guard.
- Runner jobs do not receive either Docker socket (`container.docker_host: "-"`)
or production secrets. PR #46 changes Caddyfile validation to use the pinned
Caddy binary directly; `docker compose config --quiet` remains a client-only
static check. The two production image builds still require a builder. The
PR audit rejects nested rootless BuildKit in the job container because it
requires weaker sandbox settings, and recommends a disposable, separately
isolated BuildKit VM reached through a short-lived, TLS-authenticated
`buildctl` connection. No VPS changes were made; image builds remain
unverified until the owner provisions that builder.
- Runner log lines for run 49 show act_runner 0.2.13 with registered label
`[akyldash-ci]` accepted task 301 at 2026-10-15 01:16:11 +05. The main CI
task failed at 01:16:24 +05, and smoke task 302 started immediately after.
These daemon logs do not record the failed step. Gitea 1.25.5's Actions jobs
endpoint returns an empty list for completed run 49; the current API account
cannot use the owner-only jobs endpoint to obtain the log download ID. The
exact failing step is undetermined.
- After pushing PR #46 commit `7701e77`, CI run 51 accepted task 303 at
2026-10-15 01:48:05 +05 and failed 13 seconds later; smoke run 52 accepted
task 304 and succeeded. The runner daemon log again contains only task
dispatch lines. Gitea returns no jobs for run 303, and the owner-only jobs
endpoint remains unavailable to the current API account, so run 51's failed
step is also undetermined. This repeated result does not establish a cause.
- The owner supplied the complete log for task 305 (run 53): the failure was
`Check host audit root guard`, exit 1. Earlier backend (37 tests, 1 skipped),
Telegram (6), backup/restore (16), recovery host identity guard, and verifier
helper guard passed; Docker image builds were not reached. Reproduction with
`EUID=0` and `bash -x` confirmed the test ran the audit as root and then failed
because the expected non-root denial message was absent. Run 55 then confirmed
this test passed after dropping to UID 65534, while the next step,
`Check production config root guard`, failed for the same reason. The
Compose allowlist test passed. Root-context reproductions confirmed both
production-config and runner-installer guard tests had the same latent issue.
All three now use the shared `infra/test/run-as-unprivileged.sh` helper, which
has its own UID regression test. The production security guards are unchanged.
- An isolated local Compose smoke test built backend/OpenSearch images,
reached healthy status for OpenSearch, backend, and Caddy, and returned HTTP
200 for `/review` through Caddy. Its containers, networks, and volumes were
removed afterward. This does not verify VPS startup, DNS, or public TLS.
@@ -71,27 +170,36 @@ from planned configuration.
## Checks not completed
- SSH completed with the user config explicitly selected; plain SSH was blocked
by permissions on a system config include. The private key was not read.
- UFW rules require root and remain unverified.
- Docker Engine version from the server API, container and volume inventory,
protected env/secret metadata, sudoers, and detailed UFW rules require root.
`infra/bootstrap/audit-host.sh` is provided for an owner-run read-only audit.
- The backup archive/restore tool was tested with synthetic local data; a backup
and restore of real production data remain unverified because production is
not deployed.
- Production instructions now use `/etc/akyldash/production.env` and root-run
Docker commands, consistent with the `codex` account's restricted access.
Initial deployment and upgrade backup ordering are documented; no production
host was changed for this PR.
- The Cloudflare edge response was checked, but origin DNS configuration,
Cloudflare Full (strict), certificate validity, Actions runner availability,
registry publishing, and production deployment have not been tested.
- No packages or services were installed or changed on the VPS.
- Cloudflare edge response was checked; origin DNS target, origin certificate,
Full (strict), direct runner-label inventory, registry publishing, and
production deployment have not been verified.
- This audit made no host changes. No package or service was installed by this
audit; the owner performed the initial bootstrap beforehand.
## Next owner actions
1. Review and run the root bootstrap on the dedicated host.
2. Review SSH/password/root policy and firewall rules separately; this change
did not touch them.
3. Set up DNS, origin certificate, reverse proxy, protected secret files, and
initial corpus/index.
4. Confirm a Gitea Actions runner and package permissions, then test CI and
backup/restore before considering automated production deploy.
1. Install the approved root-owned checkout after its PR is reviewed, then run
`sudo bash /opt/akyldash/current/infra/bootstrap/audit-host.sh` and share
the output. The script prints no secret values and does not mutate the host.
2. After reviewing the audit output and confirming the target files are absent,
run
`sudo bash /opt/akyldash/current/infra/deploy/prepare-production-config.sh`;
it refuses to overwrite existing files. Set the approved `DATA_ROOT` and
place the approved corpus/index and Cloudflare origin configuration. Do not
deploy until data/service state and the required backup path are reviewed.
3. Run `sudo bash /opt/akyldash/current/infra/deploy/install-helper.sh` after
reviewing the checkout; it grants only fixed verification, Compose
`config`/`status`, and guarded rollback commands.
4. After PR review and merge, install the reviewed checkout and rerun
`sudo bash /opt/akyldash/current/infra/runner/install-runner.sh` to pin the
effective `ProtectHome=read-only` setting. Then verify both workflows on
`akyldash-ci`; resolve the documented Docker-build isolation gap before
treating image-build CI as complete. Do not re-register the existing runner.
5. Test backup/restore and rollback only with synthetic data in an isolated
environment before any production deployment.
+57 -34
View File
@@ -2,37 +2,53 @@
## Current status
Production deployment is not enabled or tested on the VPS. An isolated local
Compose smoke test passed; the VPS has no Docker, Git,
application data, proxy, registry pull configuration, backup process, or
restricted verification/rollback helpers. Do not deploy until the owner has
completed the root bootstrap, provided a protected secret file and a reviewed
proxy/firewall configuration, and a backup and restore have been tested.
Production deployment is not enabled or tested on the VPS. The owner completed
the root bootstrap: Docker/Compose are active and target directories exist.
The `codex` account cannot access the Docker socket. No root-owned checkout or
restricted helpers are installed; protected env/secret metadata and Docker
container/volume state remain unverified because they require root.
The unprivileged audit sees no listener on `80`, `443`, or `1500`; Cloudflare
still returns `521`. Do not deploy until the owner has reviewed root-only host
state, supplied protected configuration and the approved corpus/index, and
backup/restore have been tested.
## First host preparation
1. Review the current inventory and state, then have the owner run
`sudo bash infra/bootstrap/bootstrap-ubuntu-24.04.sh` from a verified copy
of this branch on the VPS. The script installs Docker Engine/Compose and Git,
sets Docker log rotation, and creates root-owned paths. It refuses other OS
versions and does not change SSH, UFW, sudoers, or user groups. Use
`--recovery-target` only on a replacement host; it refuses the known
production host identity.
2. Install the approved repository checkout at `/opt/akyldash/current`,
root-owned and not group/world-writable. Copy
`deploy/production/.env.example` to `/etc/akyldash/production.env`, set
`DATA_ROOT`, and configure
`/etc/akyldash/production.env` plus `/etc/akyldash/review_secret` outside
Git. The secret file must be root-readable only.
3. After reviewing the root-owned checkout, run
`sudo bash infra/deploy/install-helper.sh`. It installs the backup reader,
read-only verifier, and rollback helper with exact sudoers command rules; it
does not grant general sudo or Docker access.
4. Confirm DNS points through Cloudflare to this origin, then have the owner
review firewall rules and open only TCP `80` and `443` in addition to the
existing SSH access. The Compose Caddy service obtains and renews its HTTPS
certificate automatically; Cloudflare Full (strict) still needs owner-side
verification.
1. The initial root bootstrap is complete. After reviewing and merging the
infrastructure PR, the owner must install that approved `main` checkout at
`/opt/akyldash/current` (the path was absent during the unprivileged audit):
```bash
sudo git clone --branch main --single-branch https://git.vakanaut.ru/admin/akyldash.git /opt/akyldash/current
```
The checkout is root-owned by default. Then run
`sudo bash /opt/akyldash/current/infra/bootstrap/audit-host.sh`. This
read-only audit reports Docker state, protected-file metadata, UFW rules,
listeners, and ISPmanager without printing secret contents. Resolve any
existing containers, volumes, or data before proceeding; do not overwrite
or delete them.
2. After confirming the existing env and secret do not exist and reviewing the
tracked defaults, run
`sudo bash /opt/akyldash/current/infra/deploy/prepare-production-config.sh`.
It creates `/etc/akyldash/production.env` from the tracked example and
generates `/etc/akyldash/review_secret`; both are root-owned mode `0600`.
It refuses to overwrite either file and does not start services or create
volumes. Review `DATA_ROOT` and place the approved normalized corpus there
before deployment.
3. After reviewing the root-owned checkout and audit output, run
`sudo bash /opt/akyldash/current/infra/deploy/install-helper.sh`. It installs
the backup reader, read-only verifier, `akyldash-compose config|status`, and
rollback helper with exact sudoers command rules. The Compose helper has no
start/stop/build operation and grants no direct Docker access. Actual
deployments remain owner-run through the documented Compose commands.
4. Confirm DNS points through Cloudflare to this origin. The owner reports UFW
already allows TCP `80` and `443`; read and document the full rules before
any firewall decision. TCP `1500` is allowed by owner report but has no
observed listener and no ISPmanager package/service was found; the owner
must identify its purpose. Do not change UFW as part of this procedure. The
Compose Caddy service obtains and renews HTTPS certificates automatically;
Cloudflare Full (strict) still needs end-to-end verification.
5. For a clean first deployment, skip backup only when Compose confirms there
are no containers and all persistent mounts are empty. If any data exists,
create and verify a backup before starting a new version. For a preloaded
@@ -49,14 +65,21 @@ proxy/firewall configuration, and a backup and restore have been tested.
sudo chmod 0600 /opt/akyldash/deployed-image.txt
```
Application deployment remains owner-run until registry permissions, a live
Gitea runner, and a controlled deploy procedure are tested. The helper only
supports a guarded application rollback.
Application deployment remains owner-run. The repository-level Actions runner
is installed and registered; the owner reports it Idle and the smoke workflow
passes. CI jobs have no rootless or system Docker socket and no production
secrets. The main CI workflow is being moved to `akyldash-ci`; Docker-dependent
image builds still need a compatible isolated builder design. CI has no image
publishing or production deployment step. The installed sudo helpers support
fixed verification, read-only Compose `config`/`status`, and guarded rollback.
They do not start or stop services.
## CI
`.gitea/workflows/ci.yaml` runs the Python unit suites and builds both
production images on pull requests and pushes to `main`. It does not publish an
image or deploy production. Gitea Actions is enabled at repository level, but a
successful workflow run has not yet confirmed that a compatible runner is
online.
image or deploy production. `.gitea/workflows/runner-smoke.yaml` exercises the
`akyldash-ci` runner on pull requests, pushes to `main`, or manual dispatch.
The current `main` workflow uses `ubuntu-latest`, while the registered runner
uses the project label `akyldash-ci`; the main CI job therefore has no matching
runner. The PR corrects the label.
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $EUID -ne 0 ]]; then
echo "Run this read-only audit as root." >&2
exit 1
fi
echo '== Host =='
hostname -f
grep -E '^(PRETTY_NAME|VERSION_ID)=' /etc/os-release
nproc
free -h
df -h /
echo '== Packages and services =='
dpkg-query -W docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
docker version --format 'Docker Engine {{.Server.Version}}'
docker compose version
containerd --version
runc --version
systemctl is-active docker
python3 -c 'import json; d=json.load(open("/etc/docker/daemon.json")); print("Docker logs:", d.get("log-driver"), d.get("log-opts"))'
echo '== Account and paths =='
id codex
for path in /opt/akyldash /opt/akyldash/current /etc/akyldash /etc/akyldash/production.env /etc/akyldash/review_secret /var/lib/akyldash/data /var/backups/akyldash /usr/local/sbin/akyldash-verify /usr/local/sbin/akyldash-rollback /usr/local/sbin/akyldash-compose /etc/sudoers.d/akyldash-codex; do
if [[ -e $path ]]; then
stat -c '%n owner=%U:%G mode=%a type=%F' "$path"
else
printf '%s absent\n' "$path"
fi
done
echo '== ISPmanager =='
dpkg-query -W -f='${binary:Package} ${Version}\n' 'ispmanager*' 'ispmgr*' 2>/dev/null || true
systemctl list-unit-files --type=service --no-legend | grep -iE 'ispmanager|ispmgr' || echo 'No ISPmanager service unit found.'
echo '== Docker state =='
docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
docker volume ls
echo '== Gitea Actions runner (read-only) =='
if id akyldash-runner >/dev/null 2>&1; then
id akyldash-runner
else
echo 'akyldash-runner user absent'
fi
if command -v act_runner >/dev/null 2>&1; then
act_runner --version
else
echo 'act_runner binary absent from PATH'
fi
for path in /etc/akyldash-runner/config.yaml /var/lib/akyldash-runner/.runner /var/lib/akyldash-runner/docker-store.img; do
if [[ -e $path ]]; then
stat -c '%n owner=%U:%G mode=%a type=%F' "$path"
else
printf '%s absent\n' "$path"
fi
done
systemctl status akyldash-act-runner.service --no-pager --full || true
systemctl status akyldash-runner-healthcheck.timer --no-pager --full || true
findmnt /var/lib/akyldash-runner/docker-data || true
echo '== Firewall and listeners (read-only) =='
ufw status verbose
ufw status numbered
ss -lntup
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
output=$(mktemp)
trap 'rm -f "$output"' EXIT
audit_script="$(dirname "$0")/audit-host.sh"
run_as_unprivileged="$(dirname "$0")/../test/run-as-unprivileged.sh"
if bash "$run_as_unprivileged" bash "$audit_script" >"$output" 2>&1; then
audit_status=0
else
audit_status=$?
fi
if ! grep -Fqx 'Run this read-only audit as root.' "$output"; then
echo "Host audit root guard did not reject unprivileged execution (audit exit code: $audit_status). Output:" >&2
cat "$output" >&2
exit 1
fi
echo 'PASS host audit root guard rejects unprivileged execution'
+3 -2
View File
@@ -129,13 +129,14 @@ for endpoint in $udp_listeners; do
failed=1
done
expected_sudoers=$'codex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-verify\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-rollback *'
expected_sudoers=$'codex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-verify\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-rollback *\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-compose config\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-compose status'
if [[ -x /usr/local/sbin/akyldash-verify && $(stat -c %U:%a /usr/local/sbin/akyldash-verify) == root:750 && \
-x /usr/local/sbin/akyldash-rollback && $(stat -c %U:%a /usr/local/sbin/akyldash-rollback) == root:750 && \
-x /usr/local/sbin/akyldash-compose && $(stat -c %U:%a /usr/local/sbin/akyldash-compose) == root:750 && \
-f /usr/local/lib/akyldash/archive.py && $(stat -c %U:%a /usr/local/lib/akyldash/archive.py) == root:644 && \
-f /etc/sudoers.d/akyldash-codex && $(stat -c %U:%a /etc/sudoers.d/akyldash-codex) == root:440 && \
$(cat /etc/sudoers.d/akyldash-codex) == "$expected_sudoers" ]]; then
echo 'PASS read-only verifier, rollback helper, and exact sudoers rules present'
echo 'PASS read-only verifier, Compose status/config helper, rollback helper, and exact sudoers rules present'
else
echo 'FAIL restricted helper or sudoers installation missing/different'
failed=1
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 1 || ( $1 != config && $1 != status ) ]]; then
echo 'Usage: akyldash-compose {config|status}' >&2
exit 2
fi
if [[ $EUID -ne 0 ]]; then
echo 'Run this helper through its fixed sudoers command.' >&2
exit 1
fi
checkout=/opt/akyldash/current
if [[ ! -d $checkout/.git || -L $checkout || $(stat -c %U "$checkout") != root ]]; then
echo 'Refusing Compose access: approved root-owned checkout is unavailable.' >&2
exit 1
fi
unsafe=$(find "$checkout" -xdev \( ! -user root -o -perm /022 \) -print -quit)
if [[ -n $unsafe ]]; then
echo 'Refusing Compose access: checkout contains a writable or non-root-owned path.' >&2
exit 1
fi
compose=(docker compose --env-file /etc/akyldash/production.env -f "$checkout/deploy/production/compose.yaml")
case $1 in
config) "${compose[@]}" config --quiet ;;
status) "${compose[@]}" ps ;;
esac
+6 -4
View File
@@ -10,7 +10,8 @@ checkout=/opt/akyldash/current
rollback_source=$checkout/infra/deploy/rollback.py
backup_source=$checkout/infra/backup/archive.py
verify_source=$checkout/infra/bootstrap/verify-helper.sh
if [[ ! -d $checkout/.git || ! -f $rollback_source || ! -f $backup_source || ! -f $verify_source ]]; then
compose_source=$checkout/infra/deploy/compose-helper.sh
if [[ ! -d $checkout/.git || ! -f $rollback_source || ! -f $backup_source || ! -f $verify_source || ! -f $compose_source ]]; then
echo "Install the approved repository checkout at $checkout first." >&2
exit 1
fi
@@ -43,7 +44,7 @@ if ! command -v visudo >/dev/null 2>&1; then
exit 1
fi
for path in /usr/local/sbin/akyldash-verify /usr/local/sbin/akyldash-rollback /usr/local/lib/akyldash/archive.py /etc/sudoers.d/akyldash-codex; do
for path in /usr/local/sbin/akyldash-verify /usr/local/sbin/akyldash-rollback /usr/local/sbin/akyldash-compose /usr/local/lib/akyldash/archive.py /etc/sudoers.d/akyldash-codex; do
if [[ -L $path ]]; then
echo "Refusing symlink at $path." >&2
exit 1
@@ -54,9 +55,10 @@ install -d -o root -g root -m 0755 /usr/local/lib/akyldash
install -o root -g root -m 0644 "$backup_source" /usr/local/lib/akyldash/archive.py
install -o root -g root -m 0750 "$verify_source" /usr/local/sbin/akyldash-verify
install -o root -g root -m 0750 "$rollback_source" /usr/local/sbin/akyldash-rollback
install -o root -g root -m 0750 "$compose_source" /usr/local/sbin/akyldash-compose
sudoers_file=/etc/sudoers.d/akyldash-codex
expected=$'codex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-verify\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-rollback *'
expected=$'codex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-verify\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-rollback *\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-compose config\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-compose status'
created=false
if [[ -e $sudoers_file ]]; then
if [[ $(stat -c %U:%a "$sudoers_file") != root:440 || $(cat "$sudoers_file") != "$expected" ]]; then
@@ -85,4 +87,4 @@ if ! visudo -c -f /etc/sudoers; then
echo "Sudoers validation failed; the newly added rule was removed." >&2
exit 1
fi
echo "Installed read-only verification and guarded rollback helpers; codex receives no general sudo or Docker access."
echo "Installed fixed read-only verification/Compose commands and guarded rollback; codex receives no general sudo or Docker access."
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $EUID -ne 0 ]]; then
echo 'Run this configuration step as root.' >&2
exit 1
fi
checkout=/opt/akyldash/current
example=$checkout/deploy/production/.env.example
config_dir=/etc/akyldash
env_file=$config_dir/production.env
secret_file=$config_dir/review_secret
if [[ ! -d $checkout/.git || -L $checkout || $(stat -c %U "$checkout") != root || ! -f $example ]]; then
echo 'Refusing configuration: approved root-owned checkout is unavailable.' >&2
exit 1
fi
unsafe=$(find "$checkout" -xdev \( ! -user root -o -perm /022 \) -print -quit)
if [[ -n $unsafe ]] || ! git -C "$checkout" diff --quiet HEAD -- deploy/production/.env.example; then
echo 'Refusing configuration: checkout is writable or .env.example differs from Git.' >&2
exit 1
fi
if [[ ! -d $config_dir || $(stat -c %U:%G:%a "$config_dir") != root:root:700 ]]; then
echo 'Expected /etc/akyldash to be root-owned mode 0700.' >&2
exit 1
fi
if [[ -e $env_file || -L $env_file || -e $secret_file || -L $secret_file ]]; then
echo 'Production env or review secret already exists; refusing to overwrite either file.' >&2
exit 1
fi
env_tmp=$(mktemp "$config_dir/.production.env.XXXXXX")
secret_tmp=$(mktemp "$config_dir/.review_secret.XXXXXX")
trap 'rm -f "$env_tmp" "$secret_tmp"' EXIT
install -o root -g root -m 0600 "$example" "$env_tmp"
openssl rand -hex 32 > "$secret_tmp"
chown root:root "$secret_tmp"
chmod 0600 "$secret_tmp"
mv -n "$env_tmp" "$env_file"
if [[ -e $env_tmp ]]; then
echo 'Production env already appeared; refusing to continue.' >&2
exit 1
fi
mv -n "$secret_tmp" "$secret_file"
if [[ -e $secret_tmp ]]; then
rm -f "$env_file"
echo 'Review secret already appeared; removed the new env file and stopped.' >&2
exit 1
fi
echo 'Created root-owned production.env and review_secret with mode 0600. No services or volumes were changed.'
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
helper=$(dirname "$0")/compose-helper.sh
for action in deploy up down docker; do
if bash "$helper" "$action" >/dev/null 2>&1; then
printf 'FAIL Compose helper accepted %s\n' "$action" >&2
exit 1
fi
done
echo 'PASS Compose helper rejects operations outside its read-only allowlist'
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
output=$(mktemp)
trap 'rm -f "$output"' EXIT
config_script="$(dirname "$0")/prepare-production-config.sh"
run_as_unprivileged="$(dirname "$0")/../test/run-as-unprivileged.sh"
if bash "$run_as_unprivileged" bash "$config_script" >"$output" 2>&1; then
config_status=0
else
config_status=$?
fi
if ! grep -Fqx 'Run this configuration step as root.' "$output"; then
echo "Production config root guard did not reject unprivileged execution (exit code: $config_status). Output:" >&2
cat "$output" >&2
exit 1
fi
echo 'PASS production config root guard rejects unprivileged execution'
+58 -9
View File
@@ -15,7 +15,7 @@ facts:
memory_gib: 7.7
swap_gib: 3.8
disk_gib: 99
disk_free_gib: 93
disk_free_gib: 92
network_interface: ens3
ipv4: 206.223.249.118/32
domain_resolution: akyldash.kg resolves to Cloudflare IPv4 and IPv6 edge addresses
@@ -26,12 +26,37 @@ facts:
- OpenSSH server
- systemd-resolved
- unattended-upgrades
absent:
- Docker Engine
- Docker Compose plugin
- Docker CE and CLI 29.9.0
- Docker Compose plugin 5.6.0
- containerd 2.4.1
- runc 1.5.2
- Git
- reverse proxy
access_audit_date: 2026-10-11
absent:
- ISPmanager package/service (unprivileged package and unit checks)
- root-owned application checkout
- restricted verifier and rollback helper
- non-loopback listeners on TCP 80, 443, 1500
access_audit_date: 2026-10-12
docker_service_active: true
docker_api_accessible_to_codex: false
docker_daemon_log_config:
driver: local
max_size: 10m
max_file: 3
bootstrap_paths:
/opt/akyldash: root:root 0755
/etc/akyldash: root:root 0700
/var/lib/akyldash/data: root:root 0750
/var/backups/akyldash: root:root 0700
unprivileged_nonloopback_tcp_listeners: [22]
owner_reported_ufw_allowed_tcp: [22, 80, 443, 1500]
port_1500_listener: false
rootless_docker_command_present: /usr/bin/dockerd-rootless.sh
runner_gitea_host_resolution: git.vakanaut.ru resolves to 195.209.48.28
runner_gitea_https_probe: /api/v1/version returned Gitea 1.25.5 (Actions protocol unverified)
cloudflare_edge_status:
http: 521
https: 521
target:
compose_file_in_repository: deploy/production/compose.yaml
compose_file_on_host: /opt/akyldash/current/deploy/production/compose.yaml
@@ -58,7 +83,7 @@ target:
persistent_data: named Compose volume opensearch-data
reverse_proxy:
target: Caddy in Compose; Caddyfile proxies akyldash.kg to backend:8080
status: repository configuration exists; not installed or running on VPS
status: no listener observed on 80/443; container state needs root Docker audit
external_ports_target: [22, 80, 443]
compose_networks:
proxy: caddy and backend
@@ -70,15 +95,36 @@ target:
restricted_helper:
path: /usr/local/sbin/akyldash-rollback
status: repository code and owner-run installer exist; not installed on VPS
compose_read_only_helper:
path: /usr/local/sbin/akyldash-compose
allowed_operations: [config, status]
status: repository code and owner-run installer exist; not installed on VPS
read_only_verifier:
path: /usr/local/sbin/akyldash-verify
status: repository code and owner-run installer exist; not installed on VPS
gitea_actions_runner:
repository: admin/akyldash
registration_scope: repository
implementation: official act_runner 0.2.13; pinned binary SHA-256 in infra/runner/install-runner.sh
label: akyldash-ci
capacity: 1
job_limits: {cpu: 2, memory_gib: 3, pids: 512}
account_slice_limits: {cpu: 2.5, memory_gib: 4, tasks: 2048}
docker_store_limit_gib: 15
docker_boundary: dedicated rootless daemon; no system Docker socket; job socket injection disabled; no production secret or sudo/docker group access observed
service_status: active; owner reports registered and Idle; owner reports smoke workflow passes on akyldash-ci
systemd_protect_home: read-only in the live unit as a temporary owner change; installer update is in PR
systemd_verification: verify passes; security exposure 7.4 medium; live runner process UID/GID 999:988, effective/permitted capabilities 0, NoNewPrivs 1, no supplementary groups
runner_log_observed: /var/log/akyldash-runner/act_runner.log; codex ACL read works; current file root:root 0644 is also other-readable; log contains task metadata but no job step output
runner_log_acl_iac: root-owned directory with codex search-only ACL; runner-owned private log with codex read-only ACL; systemd and logrotate reapply; not installed on VPS
ci_status: main workflow uses ubuntu-latest in main and has no matching runner; PR changes it to akyldash-ci
owner_action: review and merge the PR, then rerun the root installer to pin ProtectHome and runner log ACLs; inspect run 49 step logs because current non-owner API lacks access
checks:
- infra/bootstrap/verify.sh akyldash_vps
- docker compose -f deploy/production/compose.yaml ps
- curl -fsS https://akyldash.kg/review
- python3 infra/backup/archive.py verify /var/backups/akyldash/<archive>.tar.gz
backup_path: /var/backups/akyldash (target; archive script in infra/backup/archive.py is not installed or run)
backup_path: /var/backups/akyldash (directory exists; archive script in infra/backup/archive.py is not installed or run)
deployed_backend_image_record: /opt/akyldash/deployed-image.txt (required by drift verifier; not present before first deployment)
versions:
application:
@@ -87,4 +133,7 @@ versions:
telegram_bot: 0.2.2
infrastructure: unknown; no production install or release exists
caddy_image: 2.11.6-alpine pinned by manifest digest in Compose
docker_engine: not installed
docker_engine: 29.9.0 (daemon active; server API unverified as codex)
docker_compose: 5.6.0
containerd: 2.4.1
runc: 1.5.2
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -Eeuo pipefail
systemctl is-active --quiet akyldash-act-runner.service
runner_uid=$(id -u akyldash-runner)
runuser -u akyldash-runner -- env \
HOME=/var/lib/akyldash-runner/.config/act-runner \
XDG_CONFIG_HOME=/var/lib/akyldash-runner/.config \
XDG_DATA_HOME=/var/lib/akyldash-runner/.config/act-runner/.local/share \
DOCKER_HOST="unix:///run/user/$runner_uid/docker.sock" \
/usr/bin/docker info --format '{{.ServerVersion}}' >/dev/null
@@ -0,0 +1,7 @@
[Unit]
Description=Check AkylDash Gitea Actions runner health
OnFailure=akyldash-runner-restart.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/akyldash-runner-healthcheck
@@ -0,0 +1,10 @@
[Unit]
Description=Periodically check AkylDash Gitea Actions runner health
[Timer]
OnBootSec=2m
OnUnitActiveSec=1m
Unit=akyldash-runner-healthcheck.service
[Install]
WantedBy=timers.target
@@ -0,0 +1,6 @@
[Unit]
Description=Restart AkylDash Gitea Actions runner after a failed health check
[Service]
Type=oneshot
ExecStart=/bin/systemctl restart akyldash-act-runner.service
+15
View File
@@ -0,0 +1,15 @@
log:
level: info
runner:
file: /var/lib/akyldash-runner/.config/act-runner/.runner
capacity: 1
labels:
- "akyldash-ci:docker://docker.gitea.com/runner-images:ubuntu-24.04"
container:
privileged: false
options: --cpus=2 --memory=3g --pids-limit=512
valid_volumes: []
docker_host: "-"
force_pull: true
cache:
enabled: false
+22
View File
@@ -0,0 +1,22 @@
BEGIN { FS = ":" }
/^[[:space:]]*$/ || /^[[:space:]]*#/ { next }
NF != 3 || $2 !~ /^[0-9]+$/ || $3 !~ /^[0-9]+$/ || $3 < 1 { invalid = 1; next }
{
start[FILENAME, ++count[FILENAME]] = $2
end[FILENAME, count[FILENAME]] = $2 + $3 - 1
files[FILENAME] = 1
}
END {
if (invalid) exit 2
for (base = 100000; base + 65535 <= 4294901760; base += 65536) {
overlap = 0
for (file in files)
for (i = 1; i <= count[file]; i++)
if (start[file, i] <= base + 65535 && end[file, i] >= base) overlap = 1
if (!overlap) {
print base "-" base + 65535
exit
}
}
exit 1
}
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env bash
runner_die() { printf 'ERROR: %s\n' "$*" >&2; return 1; }
runner_ensure_account() {
local user=$1 home=$2 entry uid passwd_home shell groups uid_min
if ! entry=$(getent passwd "$user"); then
[[ ! -e $home && ! -L $home ]] || { runner_die "runner home already exists without its account: $home"; return 1; }
useradd --system --create-home --home-dir "$home" --shell /usr/sbin/nologin "$user" || return 1
return
fi
IFS=: read -r _ _ uid _ _ passwd_home shell <<<"$entry"
uid_min=$(awk '$1 == "UID_MIN" && $2 ~ /^[0-9]+$/ {print $2; exit}' /etc/login.defs)
[[ $uid =~ ^[0-9]+$ && $uid -gt 0 && $uid_min =~ ^[0-9]+$ && $uid -lt $uid_min && $passwd_home == "$home" && $shell == /usr/sbin/nologin ]] || { runner_die "existing $user account has an unexpected UID, home, or shell"; return 1; }
[[ $(id -gn "$user") == "$user" ]] || { runner_die "existing $user account has an unexpected primary group"; return 1; }
groups=$(id -nG "$user")
[[ $groups == "$user" ]] || { runner_die "existing $user account has unexpected supplementary groups: $groups"; return 1; }
[[ -d $home && ! -L $home ]] || { runner_die "existing $user home is missing or has unexpected type"; return 1; }
case $(stat -c %U "$home") in
"$user") ;;
root) [[ $(stat -c '%G:%a' "$home") == root:711 ]] || { runner_die "root-owned $user home must be mode 0711"; return 1; } ;;
*) runner_die "existing $user home has unexpected ownership"; return 1 ;;
esac
}
runner_lock_home() {
local home=$1 parent_mode
[[ -d $home && ! -L $home && $(stat -c %U /var/lib) == root ]] || { runner_die "runner home or its parent is unsafe: $home"; return 1; }
parent_mode=$(stat -c %a /var/lib)
(( (8#$parent_mode & 022) == 0 )) || { runner_die '/var/lib must not be group/world-writable'; return 1; }
chown root:root "$home" && chmod 0711 "$home" || return 1
[[ $(stat -c '%U:%G:%a' "$home") == root:root:711 ]] || { runner_die 'runner home could not be locked from runner writes'; return 1; }
}
runner_ensure_image() {
local image=$1 bytes=$2 parent_uid=$3 parent_mode=$4
python3 "$(dirname "${BASH_SOURCE[0]}")/secure-runner-image.py" "$image" "$bytes" "$parent_uid" "$parent_mode" || { runner_die "runner image validation or initialization failed: $image"; return 1; }
}
runner_install_file() {
local source=$1 destination=$2 owner=$3 group=$4 mode=${5#0}
if [[ -e $destination || -L $destination ]]; then
[[ -f $destination && ! -L $destination ]] && cmp -s "$source" "$destination" || { runner_die "existing runner file differs from reviewed configuration: $destination"; return 1; }
[[ $(stat -c '%U:%G:%a' "$destination") == "$owner:$group:$mode" ]] || { runner_die "existing runner file has unexpected ownership or permissions: $destination"; return 1; }
return
fi
install -o "$owner" -g "$group" -m "0$mode" "$source" "$destination"
}
runner_install_content() {
local destination=$1 owner=$2 group=$3 mode=$4 temporary
temporary=$(mktemp)
cat >"$temporary"
if ! runner_install_file "$temporary" "$destination" "$owner" "$group" "$mode"; then
rm -f "$temporary"
return 1
fi
rm -f "$temporary"
}
runner_install_content_allow_line_change() {
local destination=$1 owner=$2 group=$3 mode=$4 old_line=$5 new_line=$6
local temporary normalized expected_mode result=0
temporary=$(mktemp)
normalized=$(mktemp)
cat >"$temporary"
expected_mode=${mode#0}
if [[ -e $destination || -L $destination ]]; then
[[ -f $destination && ! -L $destination && $(stat -c '%U:%G:%a' "$destination") == "$owner:$group:$expected_mode" ]] || {
rm -f "$temporary" "$normalized"
runner_die "existing runner file has unexpected type, owner, or permissions: $destination"
return 1
}
if cmp -s "$temporary" "$destination"; then
rm -f "$temporary" "$normalized"
return
fi
awk -v old="$old_line" -v new="$new_line" '{ if ($0 == old) { $0 = new; count++ } print } END { if (count != 1) exit 1 }' "$destination" >"$normalized" || result=$?
if ((result != 0)) || ! cmp -s "$temporary" "$normalized"; then
rm -f "$temporary" "$normalized"
runner_die "existing runner file differs beyond the reviewed line change: $destination"
return 1
fi
install -o "$owner" -g "$group" -m "$mode" "$temporary" "$destination" || result=$?
else
install -o "$owner" -g "$group" -m "$mode" "$temporary" "$destination" || result=$?
fi
rm -f "$temporary" "$normalized"
((result == 0)) || return 1
[[ -f $destination && ! -L $destination && $(stat -c '%U:%G:%a' "$destination") == "$owner:$group:$expected_mode" ]] || { runner_die "runner file failed validation: $destination"; return 1; }
}
runner_ensure_private_directory() {
local directory=$1 owner=$2 group=$3 current= component index
local -a components
[[ $directory == /* ]] || { runner_die "runner directory path is not absolute: $directory"; return 1; }
IFS=/ read -r -a components <<<"${directory#/}"
for index in "${!components[@]}"; do
component=${components[index]}
[[ -n $component && $component != . && $component != .. ]] || { runner_die "runner directory path has an unsafe component: $directory"; return 1; }
current+="/$component"
[[ ! -L $current ]] || { runner_die "runner directory path contains a symbolic link: $current"; return 1; }
if [[ ! -e $current ]]; then
((index == ${#components[@]} - 1)) || { runner_die "runner directory parent is missing: $current"; return 1; }
break
fi
[[ -d $current ]] || { runner_die "runner directory path component is not a directory: $current"; return 1; }
if [[ $current == /var/lib/akyldash-runner ]]; then
[[ $(stat -c '%U:%G:%a' "$current") == root:root:711 ]] || { runner_die 'runner home must be root-owned mode 0711'; return 1; }
elif [[ $current == /var/lib/akyldash-runner/* ]]; then
[[ $(stat -c '%U:%G' "$current") == "$owner:$group" ]] || { runner_die "runner directory ancestor has unexpected ownership: $current"; return 1; }
fi
done
# These paths are runner-writable; make changes as that user so a path swap
# cannot turn a root operation into a write outside its home.
if [[ $directory == /var/lib/akyldash-runner/.config ]]; then
install -d -o "$owner" -g "$group" -m 0700 "$directory" || return 1
else
runuser -u "$owner" -- install -d -m 0700 "$directory" || return 1
fi
[[ -d $directory && ! -L $directory && $(stat -c '%U:%G:%a' "$directory") == "$owner:$group:700" ]] || { runner_die "runner directory failed validation: $directory"; return 1; }
}
runner_install_user_content() {
local destination=$1 owner=$2 group=$3 mode=${4#0} temporary
temporary=$(mktemp)
cat >"$temporary"
if [[ -e $destination || -L $destination ]]; then
[[ -f $destination && ! -L $destination ]] && cmp -s "$temporary" "$destination" || { rm -f "$temporary"; runner_die "existing runner file differs from reviewed configuration: $destination"; return 1; }
[[ $(stat -c '%U:%G:%a' "$destination") == "$owner:$group:$mode" ]] || { rm -f "$temporary"; runner_die "existing runner file has unexpected ownership or permissions: $destination"; return 1; }
rm -f "$temporary"
return
fi
chown "$owner:$group" "$temporary" && chmod "0$mode" "$temporary" || { rm -f "$temporary"; return 1; }
local result=0
runuser -u "$owner" -- install -m "0$mode" "$temporary" "$destination" || result=$?
rm -f "$temporary"
((result == 0)) || return 1
[[ -f $destination && ! -L $destination && $(stat -c '%U:%G:%a' "$destination") == "$owner:$group:$mode" ]] || { runner_die "runner file failed validation: $destination"; return 1; }
}
runner_validate_mount() {
local image=$1 store=$2 target filesystem source options backing mount_info
mount_info=$(findmnt --noheadings --output TARGET,FSTYPE,SOURCE,OPTIONS --mountpoint "$store") || { runner_die 'runner store is not mounted'; return 1; }
read -r target filesystem source options <<<"$mount_info" || { runner_die 'runner store mount information is empty'; return 1; }
[[ $target == "$store" && $filesystem == ext4 && $source == /dev/loop* ]] || { runner_die 'runner store is mounted from an unexpected target, filesystem, or device'; return 1; }
case ",$options," in *,nosuid,*nodev,*|*,nodev,*nosuid,*) ;; *) runner_die 'runner store mount is missing nosuid or nodev'; return 1 ;; esac
backing=$(losetup --noheadings --output BACK-FILE "$source") || { runner_die 'cannot identify the runner loop backing file'; return 1; }
[[ $(realpath -e "$backing") == "$(realpath -e "$image")" ]] || { runner_die 'runner store is backed by a different image'; return 1; }
}
runner_ensure_mount() {
local image=$1 store=$2 unit_name=$3 unit_file=$4 unit_tmp mounted=0
[[ -d $store && ! -L $store ]] || { runner_die "runner mount point is missing or is not a directory: $store"; return 1; }
if mountpoint -q "$store"; then
runner_validate_mount "$image" "$store" || return 1
mounted=1
fi
unit_tmp=$(mktemp)
if ! cat >"$unit_tmp" <<EOF
[Unit]
Description=Bounded storage for the AkylDash CI runner
Before=local-fs.target
[Mount]
What=$image
Where=$store
Type=ext4
Options=loop,nosuid,nodev
[Install]
WantedBy=local-fs.target
EOF
then
rm -f "$unit_tmp"
runner_die 'failed to prepare runner mount unit'
return 1
fi
if [[ -e $unit_file || -L $unit_file ]]; then
if [[ ! -f $unit_file || -L $unit_file ]] || ! cmp -s "$unit_tmp" "$unit_file"; then
rm -f "$unit_tmp"
runner_die "existing runner mount unit differs from the reviewed configuration: $unit_file"
return 1
fi
[[ $(stat -c '%u:%g:%a' "$unit_file") == "$(id -u):$(id -g):644" ]] || { rm -f "$unit_tmp"; runner_die 'existing runner mount unit has unexpected ownership or permissions'; return 1; }
else
install -m 0644 "$unit_tmp" "$unit_file" || { rm -f "$unit_tmp"; return 1; }
fi
rm -f "$unit_tmp"
systemctl daemon-reload || return 1
if ((mounted)); then
systemctl enable "$unit_name" || return 1
else
systemctl enable "$unit_name" || return 1
systemctl start "$unit_name" || return 1
runner_validate_mount "$image" "$store" || return 1
fi
}
+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env bash
set -Eeuo pipefail
readonly runner_user=akyldash-runner
readonly runner_home=/var/lib/akyldash-runner
readonly runner_runtime_home="$runner_home/.config/act-runner"
readonly runner_xdg_config_home="$runner_home/.config"
readonly runner_xdg_data_home="$runner_runtime_home/.local/share"
readonly runner_store="$runner_home/docker-data"
readonly runner_image="$runner_home/docker-store.img"
readonly runner_log_dir=/var/log/akyldash-runner
readonly runner_log="$runner_log_dir/act_runner.log"
readonly runner_mount_unit_name="$(systemd-escape --path --suffix=mount /var/lib/akyldash-runner/docker-data)"
readonly runner_mount_unit="/etc/systemd/system/$runner_mount_unit_name"
readonly runner_image_bytes=16106127360
readonly runner_version=0.2.13
readonly runner_sha256=3acac8b506ac8cadc88a55155b5d6378f0fab0b8f62d1e0c0450f4ccd69733e2
readonly runner_url="https://dl.gitea.com/gitea-runner/$runner_version/act_runner-$runner_version-linux-amd64"
readonly checkout=/opt/akyldash/current
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die 'run this script as root'
[[ -r /etc/os-release ]] || die 'cannot identify operating system'
. /etc/os-release
[[ ${ID:-} == ubuntu && ${VERSION_ID:-} == 24.04 ]] || die 'Ubuntu 24.04 is required'
[[ $(uname -m) == x86_64 ]] || die 'this pinned binary is for x86_64 only'
[[ $(stat -fc %T /sys/fs/cgroup) == cgroup2fs ]] || die 'rootless Docker requires cgroup v2'
[[ $(findmnt -n -o FSTYPE /) == ext4 ]] || die 'the bounded runner store currently requires ext4 on /'
[[ -d $checkout/.git && ! -L $checkout && $(stat -c %U "$checkout") == root ]] || die 'install the reviewed root-owned checkout at /opt/akyldash/current first'
for directory in /opt /opt/akyldash; do
[[ $(stat -c %U "$directory") == root ]] || die "$directory must be owned by root"
mode=$(stat -c %a "$directory")
(( (8#$mode & 022) == 0 )) || die "$directory must not be group/world-writable"
done
unsafe=$(find "$checkout" -xdev \( ! -user root -o -perm /022 \) -print -quit)
[[ -z $unsafe ]] || die 'the repository checkout contains files writable by non-root users'
git -C "$checkout" diff --quiet HEAD -- infra/runner || die 'runner files differ from the reviewed Git revision'
source "$checkout/infra/runner/install-runner-lib.sh"
if systemctl is-active --quiet akyldash-act-runner.service; then
die 'stop akyldash-act-runner.service after all jobs finish before rerunning this installer'
fi
[[ -r /etc/subuid && -r /etc/subgid ]] || die 'subordinate ID allocation files are unavailable'
if getent passwd "$runner_user" >/dev/null; then
runner_ensure_account "$runner_user" "$runner_home" || die 'runner account validation failed'
runner_lock_home "$runner_home" || die 'runner home protection failed'
else
[[ ! -e $runner_home && ! -L $runner_home ]] || die 'runner home exists without its account; inspect it before continuing'
fi
if [[ -e $runner_image || -L $runner_image ]]; then
runner_ensure_image "$runner_image" "$runner_image_bytes" 0 711 || die 'runner image validation failed'
else
[[ $(df -Pk / | awk 'NR==2 {print $4}') -ge 25000000 ]] || die 'need at least 25 GiB free before reserving 15 GiB for runner data'
fi
for file in /etc/subuid /etc/subgid; do
awk -F: '!/^[[:space:]]*#/ && !/^[[:space:]]*$/ && (NF != 3 || $2 !~ /^[0-9]+$/ || $3 !~ /^[0-9]+$/ || $3 < 1) { bad=1 } END { exit bad }' "$file" || die "$file contains an invalid subordinate ID entry"
done
subuid_pair=$(awk -F: -v user="$runner_user" '$1 == user { count++; pair=$2 ":" $3 } END { if (count > 1) exit 2; if (count == 1) print pair }' /etc/subuid) || die 'runner has multiple subuid allocations; inspect them before continuing'
subgid_pair=$(awk -F: -v user="$runner_user" '$1 == user { count++; pair=$2 ":" $3 } END { if (count > 1) exit 2; if (count == 1) print pair }' /etc/subgid) || die 'runner has multiple subgid allocations; inspect them before continuing'
for pair in "$subuid_pair" "$subgid_pair"; do
[[ -z $pair || $pair =~ ^[0-9]+:65536$ ]] || die 'existing runner subordinate ID allocation is not a single 65536-ID range'
done
if [[ -n $subuid_pair && -n $subgid_pair && $subuid_pair != "$subgid_pair" ]]; then
die 'runner subuid and subgid allocations differ; inspect them before continuing'
fi
existing_pair=${subuid_pair:-$subgid_pair}
if [[ -n $existing_pair ]]; then
subid_start=${existing_pair%%:*}
[[ $subid_start =~ ^[1-9][0-9]*$ && $subid_start -ge 100000 && $subid_start -le 4294901760 ]] || die 'existing runner subordinate ID range is outside the supported range'
subid_end=$((subid_start + 65535))
subid_range="$subid_start-$subid_end"
else
subid_range=$(awk -f "$(dirname "$0")/find-free-subid-range.awk" /etc/subuid /etc/subgid) || die 'could not find a free 65536-ID range shared by /etc/subuid and /etc/subgid'
subid_start=${subid_range%-*}
subid_end=${subid_range#*-}
fi
for file in /etc/subuid /etc/subgid; do
awk -F: -v user="$runner_user" -v start="$subid_start" -v end="$subid_end" '$1 != user && $2 <= end && $2 + $3 - 1 >= start { conflict=1 } END { exit conflict }' "$file" || die "runner subordinate ID range conflicts with another entry in $file"
done
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y uidmap dbus-user-session curl logrotate acl docker-ce-rootless-extras
runner_ensure_account "$runner_user" "$runner_home" || die 'runner account creation failed'
runner_lock_home "$runner_home" || die 'runner home protection failed'
subid_args=()
[[ -n $subuid_pair ]] || subid_args+=(--add-subuids "$subid_range")
[[ -n $subgid_pair ]] || subid_args+=(--add-subgids "$subid_range")
if ((${#subid_args[@]})); then
usermod "${subid_args[@]}" "$runner_user"
fi
runner_uid=$(id -u "$runner_user")
runner_ensure_private_directory "$runner_home/.config" "$runner_user" "$runner_user" || die 'runner config directory failed validation'
runner_ensure_private_directory "$runner_home/.config/docker" "$runner_user" "$runner_user" || die 'runner Docker config directory failed validation'
runner_ensure_private_directory "$runner_home/.config/systemd" "$runner_user" "$runner_user" || die 'runner systemd config directory failed validation'
runner_ensure_private_directory "$runner_home/.config/systemd/user" "$runner_user" "$runner_user" || die 'runner user systemd directory failed validation'
runner_ensure_private_directory "$runner_home/.config/systemd/user/docker.service.d" "$runner_user" "$runner_user" || die 'runner Docker override directory failed validation'
runner_ensure_private_directory "$runner_runtime_home" "$runner_user" "$runner_user" || die 'runner runtime home failed directory validation'
runner_ensure_private_directory "$runner_runtime_home/.local" "$runner_user" "$runner_user" || die 'runner XDG data parent failed directory validation'
runner_ensure_private_directory "$runner_xdg_data_home" "$runner_user" "$runner_user" || die 'runner XDG data directory failed directory validation'
if [[ -e $runner_home/.runner || -L $runner_home/.runner ]]; then
[[ -f $runner_home/.runner && ! -L $runner_home/.runner ]] || die 'legacy runner registration state is not a regular file'
if [[ ! -e $runner_runtime_home/.runner && ! -L $runner_runtime_home/.runner ]]; then
runner_install_user_content "$runner_runtime_home/.runner" "$runner_user" "$runner_user" 0600 <"$runner_home/.runner" || die 'legacy runner registration state could not be preserved'
fi
fi
if [[ ! -e $runner_store && ! -L $runner_store ]]; then
install -d -o root -g root -m 0755 "$runner_store"
fi
[[ -d $runner_store && ! -L $runner_store ]] || die 'runner mount path is not a directory'
install -d -o root -g "$runner_user" -m 0750 /etc/akyldash-runner "$runner_log_dir"
[[ -d $runner_log_dir && ! -L $runner_log_dir ]] || die 'runner log directory must be a real directory'
[[ ! -L $runner_log ]] || die 'runner log path must not be a symbolic link'
if [[ -e $runner_log ]]; then
[[ -f $runner_log ]] || die 'runner log path must be a regular file'
else
install -o "$runner_user" -g "$runner_user" -m 0600 /dev/null "$runner_log"
fi
chown "$runner_user:$runner_user" "$runner_log"
chmod 0600 "$runner_log"
setfacl -b "$runner_log_dir"
setfacl -k "$runner_log_dir"
setfacl -b "$runner_log"
setfacl -m u:codex:--x "$runner_log_dir"
setfacl -m u:codex:r--,g::---,m::r-- "$runner_log"
getfacl -cp "$runner_log_dir" | grep -Fqx 'user:codex:--x' || die 'runner log directory ACL is not restrictive'
getfacl -cp "$runner_log" | grep -Fqx 'user:codex:r--' || die 'runner log read ACL is missing'
getfacl -cp "$runner_log" | grep -Fqx 'group::---' || die 'runner log is readable by its group'
getfacl -cp "$runner_log" | grep -Fqx 'other::---' || die 'runner log is readable by other users'
runner_ensure_image "$runner_image" "$runner_image_bytes" 0 711 || die 'runner image initialization failed'
runner_ensure_mount "$runner_image" "$runner_store" "$runner_mount_unit_name" "$runner_mount_unit" || die 'runner mount activation failed'
chown "$runner_user:$runner_user" "$runner_store"
chmod 0700 "$runner_store"
runner_install_file "$(dirname "$0")/act-runner-healthcheck.sh" /usr/local/sbin/akyldash-runner-healthcheck root root 0755 || die 'healthcheck command differs from reviewed configuration'
runner_install_file "$(dirname "$0")/config.yaml" /etc/akyldash-runner/config.yaml root "$runner_user" 0640 || die 'runner config differs from reviewed configuration'
if [[ -e /usr/local/bin/act_runner || -L /usr/local/bin/act_runner ]]; then
[[ -f /usr/local/bin/act_runner && ! -L /usr/local/bin/act_runner ]] || die 'existing act_runner path is not a regular file'
printf '%s %s\n' "$runner_sha256" /usr/local/bin/act_runner | sha256sum --check --status || die 'existing act_runner binary does not match the pinned release'
else
tmp_binary=$(mktemp)
trap 'rm -f "$tmp_binary"' EXIT
curl --fail --location --silent --show-error "$runner_url" -o "$tmp_binary"
printf '%s %s\n' "$runner_sha256" "$tmp_binary" | sha256sum --check --status || die 'official act_runner checksum mismatch'
install -o root -g root -m 0755 "$tmp_binary" /usr/local/bin/act_runner
rm -f "$tmp_binary"
trap - EXIT
fi
runner_install_user_content "$runner_home/.config/docker/daemon.json" "$runner_user" "$runner_user" 0600 <<EOF
{
"data-root": "$runner_store",
"log-driver": "local",
"log-opts": {"max-size": "10m", "max-file": "2"}
}
EOF
runner_install_user_content "$runner_home/.config/systemd/user/docker.service.d/limits.conf" "$runner_user" "$runner_user" 0644 <<'EOF'
[Service]
Delegate=yes
CPUQuota=200%
MemoryMax=4G
TasksMax=1024
Restart=always
RestartSec=5
EOF
runner_install_user_content "$runner_home/.config/systemd/user/docker.service.d/environment.conf" "$runner_user" "$runner_user" 0644 <<EOF
[Service]
Environment=HOME=$runner_runtime_home
Environment=XDG_CONFIG_HOME=$runner_xdg_config_home
Environment=XDG_DATA_HOME=$runner_xdg_data_home
EOF
runner_install_content_allow_line_change /etc/systemd/system/akyldash-act-runner.service root root 0644 'ProtectHome=yes' 'ProtectHome=read-only' <<EOF
[Unit]
Description=AkylDash repository Gitea Actions runner
After=network-online.target local-fs.target
Wants=network-online.target
RequiresMountsFor=$runner_store
[Service]
Type=simple
Slice=user-$runner_uid.slice
User=$runner_user
Group=$runner_user
Environment=HOME=$runner_runtime_home
Environment=XDG_CONFIG_HOME=$runner_xdg_config_home
Environment=XDG_DATA_HOME=$runner_xdg_data_home
WorkingDirectory=$runner_runtime_home
Environment=XDG_RUNTIME_DIR=/run/user/$runner_uid
Environment=DOCKER_HOST=unix:///run/user/$runner_uid/docker.sock
ExecStartPre=/bin/sh -c 'for i in \$(seq 1 60); do /usr/bin/docker info >/dev/null 2>&1 && exit 0; sleep 2; done; exit 1'
ExecStart=/usr/local/bin/act_runner --config /etc/akyldash-runner/config.yaml daemon
Restart=always
RestartSec=10
CPUQuota=50%
MemoryMax=768M
TasksMax=256
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=read-only
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
RestrictSUIDSGID=yes
ReadWritePaths=$runner_runtime_home $runner_xdg_config_home /var/log/akyldash-runner /run/user/$runner_uid
StandardOutput=append:/var/log/akyldash-runner/act_runner.log
StandardError=append:/var/log/akyldash-runner/act_runner.log
UMask=0077
ExecStartPost=/usr/bin/setfacl -m u:codex:r--,g::---,m::r-- /var/log/akyldash-runner/act_runner.log
[Install]
WantedBy=multi-user.target
EOF
install -d -o root -g root -m 0755 "/etc/systemd/system/user-$runner_uid.slice.d"
runner_install_content "/etc/systemd/system/user-$runner_uid.slice.d/limits.conf" root root 0644 <<EOF
[Slice]
CPUQuota=250%
MemoryMax=4G
TasksMax=2048
EOF
runner_install_content /etc/logrotate.d/akyldash-runner root root 0644 <<'EOF'
/var/log/akyldash-runner/act_runner.log {
daily
rotate 7
size 10M
compress
missingok
notifempty
copytruncate
postrotate
/usr/bin/setfacl -m u:codex:r--,g::---,m::r-- /var/log/akyldash-runner/act_runner.log
endscript
}
EOF
runner_install_file "$(dirname "$0")/akyldash-runner-healthcheck.service" /etc/systemd/system/akyldash-runner-healthcheck.service root root 0644
runner_install_file "$(dirname "$0")/akyldash-runner-healthcheck.timer" /etc/systemd/system/akyldash-runner-healthcheck.timer root root 0644
runner_install_file "$(dirname "$0")/akyldash-runner-restart.service" /etc/systemd/system/akyldash-runner-restart.service root root 0644
loginctl enable-linger "$runner_user"
systemctl daemon-reload
systemctl start "user@$runner_uid.service"
rootless_docker_unit="$runner_xdg_config_home/systemd/user/docker.service"
rootless_env=(HOME="$runner_runtime_home" XDG_CONFIG_HOME="$runner_xdg_config_home" XDG_DATA_HOME="$runner_xdg_data_home" XDG_RUNTIME_DIR="/run/user/$runner_uid" DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$runner_uid/bus")
runuser -u "$runner_user" -- env "${rootless_env[@]}" sh -c 'test -w "$HOME" && test -w "$XDG_CONFIG_HOME" && test -w "$XDG_DATA_HOME"' || die 'rootless Docker HOME and XDG directories must be writable by the runner'
if [[ -e $rootless_docker_unit || -L $rootless_docker_unit ]]; then
[[ -f $rootless_docker_unit && ! -L $rootless_docker_unit && $(stat -c %U "$rootless_docker_unit") == "$runner_user" ]] || die 'existing rootless Docker unit has an unexpected type or owner'
grep -Fq 'dockerd-rootless.sh' "$rootless_docker_unit" || die 'existing rootless Docker unit differs from the expected service'
else
runuser -u "$runner_user" -- env "${rootless_env[@]}" dockerd-rootless-setuptool.sh install
fi
runuser -u "$runner_user" -- env "${rootless_env[@]}" systemctl --user daemon-reload
runuser -u "$runner_user" -- env "${rootless_env[@]}" systemctl --user enable docker.service
if runuser -u "$runner_user" -- env "${rootless_env[@]}" systemctl --user is-active --quiet docker.service; then
runuser -u "$runner_user" -- env "${rootless_env[@]}" systemctl --user restart docker.service
else
runuser -u "$runner_user" -- env "${rootless_env[@]}" systemctl --user start docker.service
fi
docker_pid=$(runuser -u "$runner_user" -- env "${rootless_env[@]}" systemctl --user show docker.service --property=MainPID --value)
[[ $docker_pid =~ ^[1-9][0-9]*$ && -r /proc/$docker_pid/environ ]] || die 'rootless Docker process environment is unavailable'
docker_environment=$(tr '\0' '\n' <"/proc/$docker_pid/environ") || die 'could not read rootless Docker process environment'
for expected in "HOME=$runner_runtime_home" "XDG_CONFIG_HOME=$runner_xdg_config_home" "XDG_DATA_HOME=$runner_xdg_data_home"; do
grep -Fqx -- "$expected" <<<"$docker_environment" || die "running rootless Docker process is missing $expected"
done
printf '\nRunner runtime installed. Register it interactively, then enable its services as described in docs/operations/CI_RUNNER.md.\n'
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Create or validate the runner image without following replaceable paths."""
import os
import stat
import subprocess
import sys
def open_directory(path: str) -> int:
current = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
try:
for component in path.strip("/").split("/"):
if not component:
continue
next_fd = os.open(
component,
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
dir_fd=current,
)
os.close(current)
current = next_fd
return current
except BaseException:
os.close(current)
raise
def filesystem_type(fd: int) -> str:
result = subprocess.run(
["blkid", "-p", "-s", "TYPE", "-o", "value", f"/proc/self/fd/{fd}"],
check=False,
capture_output=True,
text=True,
pass_fds=(fd,),
)
return result.stdout.strip() if result.returncode == 0 else ""
def main() -> int:
image, bytes_text, parent_uid_text, parent_mode_text = sys.argv[1:]
image = os.path.abspath(image)
parent_path, name = os.path.split(image)
if not name or name in {".", ".."}:
raise ValueError("invalid image filename")
parent_fd = open_directory(parent_path)
image_fd = -1
try:
parent_stat = os.fstat(parent_fd)
if parent_stat.st_uid != int(parent_uid_text) or stat.S_IMODE(parent_stat.st_mode) != int(parent_mode_text, 8):
raise RuntimeError("image parent has unexpected owner or permissions")
created = False
try:
image_fd = os.open(
name,
os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC,
dir_fd=parent_fd,
)
except FileNotFoundError:
image_fd = os.open(
name,
os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC,
0o600,
dir_fd=parent_fd,
)
created = True
image_stat = os.fstat(image_fd)
if not stat.S_ISREG(image_stat.st_mode) or image_stat.st_uid != os.geteuid() or image_stat.st_nlink != 1:
raise RuntimeError("image must be a singly-linked regular file owned by the installer")
if not created and image_stat.st_mode & 0o022:
raise RuntimeError("existing image is writable by group or other users")
if created:
os.posix_fallocate(image_fd, 0, int(bytes_text))
subprocess.run(
["mkfs.ext4", "-F", "-q", f"/proc/self/fd/{image_fd}"],
check=True,
pass_fds=(image_fd,),
)
image_stat = os.fstat(image_fd)
if image_stat.st_size != int(bytes_text):
raise RuntimeError(f"image size is {image_stat.st_size} bytes, expected {bytes_text}; refusing to resize or format")
if filesystem_type(image_fd) != "ext4":
raise RuntimeError("image does not contain ext4; refusing to format")
path_stat = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
if not stat.S_ISREG(path_stat.st_mode) or (path_stat.st_dev, path_stat.st_ino) != (image_stat.st_dev, image_stat.st_ino):
raise RuntimeError("image path changed during validation")
return 0
finally:
if image_fd >= 0:
os.close(image_fd)
os.close(parent_fd)
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, RuntimeError, ValueError, subprocess.CalledProcessError) as error:
print(f"ERROR: {error}", file=sys.stderr)
raise SystemExit(1)
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
workflow=.gitea/workflows/ci.yaml
grep -Fq 'docker compose --env-file deploy/production/.env.example -f deploy/production/compose.yaml config --quiet' "$workflow"
grep -Fq 'caddy_2.11.6_linux_amd64.tar.gz' "$workflow"
grep -Fq 'sha512sum --check' "$workflow"
grep -Fq 'caddy" validate --config deploy/production/Caddyfile --adapter caddyfile' "$workflow"
if grep -Eq '(^|[[:space:]])docker run([[:space:]]|$)' "$workflow"; then
echo 'CI must validate Caddyfile directly in the job container, without docker run' >&2
exit 1
fi
test "$(grep -Ec 'docker build -f deploy/production/Dockerfile\.(backend|opensearch)' "$workflow")" -eq 2
echo 'CI container operation checks passed'
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -Eeuo pipefail
output=$(mktemp)
trap 'rm -f "$output"' EXIT
installer="$(dirname "$0")/install-runner.sh"
run_as_unprivileged="$(dirname "$0")/../test/run-as-unprivileged.sh"
if bash "$run_as_unprivileged" bash "$installer" >"$output" 2>&1; then
installer_status=0
else
installer_status=$?
fi
if ! grep -Fqx 'ERROR: run this script as root' "$output"; then
echo "Runner installer root guard did not reject unprivileged execution (exit code: $installer_status). Output:" >&2
cat "$output" >&2
exit 1
fi
echo 'PASS runner installer root guard rejects unprivileged execution'
@@ -0,0 +1,276 @@
#!/usr/bin/env bash
set -Eeuo pipefail
runner_dir=$(cd "$(dirname "$0")" && pwd)
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/bin" "$tmp/store" "$tmp/partial-store"
log=$tmp/commands.log
export RUNNER_TEST_LOG=$log
cat >"$tmp/bin/mkfs.ext4" <<'EOF'
#!/usr/bin/env bash
printf 'mkfs\n' >>"$RUNNER_TEST_LOG"
if [[ -n ${RUNNER_TEST_REPLACE_IMAGE:-} ]]; then
rm -f "$RUNNER_TEST_IMAGE"
ln -s "$RUNNER_TEST_REPLACE_IMAGE" "$RUNNER_TEST_IMAGE"
fi
EOF
cat >"$tmp/bin/blkid" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "${RUNNER_TEST_FS:-ext4}"
EOF
cat >"$tmp/bin/systemctl" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$*" >>"$RUNNER_TEST_LOG"
if [[ $1 == start ]]; then
[[ ${RUNNER_TEST_FAIL_START:-0} == 0 ]] || exit 1
: >"$RUNNER_TEST_MOUNTED"
fi
EOF
cat >"$tmp/bin/mountpoint" <<'EOF'
#!/usr/bin/env bash
[[ -e $RUNNER_TEST_MOUNTED ]]
EOF
cat >"$tmp/bin/findmnt" <<'EOF'
#!/usr/bin/env bash
printf '%s ext4 /dev/loop0 %s\n' "$RUNNER_TEST_STORE" "${RUNNER_TEST_OPTIONS:-rw,nosuid,nodev,relatime}"
EOF
cat >"$tmp/bin/losetup" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$RUNNER_TEST_BACKING"
EOF
chmod +x "$tmp/bin/"*
PATH="$tmp/bin:$PATH"
export PATH
source "$runner_dir/install-runner-lib.sh"
runuser() {
shift 2
[[ $1 == -- ]] || return 2
shift
"$@"
}
getent() {
[[ $1 == passwd ]] || return 2
if [[ -n ${RUNNER_TEST_PASSWD:-} ]]; then
printf '%s\n' "$RUNNER_TEST_PASSWD"
elif [[ -r ${RUNNER_TEST_ACCOUNT_STATE:-} ]]; then
cat "$RUNNER_TEST_ACCOUNT_STATE"
else
return 2
fi
}
id() {
case $1 in
-gn) printf '%s\n' "${RUNNER_TEST_PRIMARY_GROUP:-akyldash-runner}" ;;
-nG) [[ ${TEST_EXTRA_GROUP:-0} == 1 ]] && printf 'akyldash-runner docker\n' || printf 'akyldash-runner\n' ;;
*) command id "$@" ;;
esac
}
stat() {
if [[ $1 == -c && $2 == %U && $3 == ${RUNNER_TEST_HOME:-} ]]; then
printf '%s\n' "${RUNNER_TEST_HOME_OWNER:-akyldash-runner}"
elif [[ $1 == -c && $2 == %G:%a && $3 == ${RUNNER_TEST_HOME:-} ]]; then
printf '%s:%s\n' "${RUNNER_TEST_HOME_GROUP:-root}" "${RUNNER_TEST_HOME_MODE:-711}"
else
command stat "$@"
fi
}
useradd() {
printf 'useradd\n' >>"$RUNNER_TEST_LOG"
local user=${@: -1} home=
while (($#)); do
if [[ $1 == --home-dir ]]; then home=$2; shift 2; else shift; fi
done
mkdir -p "$home"
printf '%s:x:990:990::%s:/usr/sbin/nologin\n' "$user" "$home" >"$RUNNER_TEST_ACCOUNT_STATE"
}
export RUNNER_TEST_HOME="$tmp/account-home"
export RUNNER_TEST_ACCOUNT_STATE="$tmp/account.passwd"
mkdir -p "$RUNNER_TEST_HOME"
export RUNNER_TEST_PASSWD="akyldash-runner:x:990:990::${RUNNER_TEST_HOME}:/usr/sbin/nologin"
runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME"
RUNNER_TEST_HOME_OWNER=root runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME"
if RUNNER_TEST_HOME_OWNER=root RUNNER_TEST_HOME_MODE=755 runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME" 2>/dev/null; then
echo 'Writable root-owned runner home was accepted' >&2
exit 1
fi
TEST_EXTRA_GROUP=1
if runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME" 2>/dev/null; then
echo 'Runner account with extra group membership was accepted' >&2
exit 1
fi
unset TEST_EXTRA_GROUP
if RUNNER_TEST_PASSWD="akyldash-runner:x:990:990::${tmp}/wrong-home:/usr/sbin/nologin" runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME" 2>/dev/null; then
echo 'Runner account with a different home was accepted' >&2
exit 1
fi
if RUNNER_TEST_PASSWD="akyldash-runner:x:0:990::${RUNNER_TEST_HOME}:/usr/sbin/nologin" runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME" 2>/dev/null; then
echo 'Runner account with UID 0 was accepted' >&2
exit 1
fi
if RUNNER_TEST_PASSWD="akyldash-runner:x:1000:990::${RUNNER_TEST_HOME}:/usr/sbin/nologin" runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME" 2>/dev/null; then
echo 'Runner account with a regular-user UID was accepted' >&2
exit 1
fi
RUNNER_TEST_PRIMARY_GROUP=unexpected
if runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME" 2>/dev/null; then
echo 'Runner account with an unexpected primary group was accepted' >&2
exit 1
fi
unset RUNNER_TEST_PRIMARY_GROUP
unset RUNNER_TEST_PASSWD
export RUNNER_TEST_HOME="$tmp/new-account-home"
runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME"
runner_ensure_account akyldash-runner "$RUNNER_TEST_HOME"
[[ $(grep -c '^useradd$' "$log") == 1 ]]
private_root=$tmp/private
mkdir -m 0700 "$private_root"
runner_owner=$(command id -un)
runner_group=$(command id -gn)
runner_ensure_private_directory "$private_root/config" "$runner_owner" "$runner_group"
runner_ensure_private_directory "$private_root/config" "$runner_owner" "$runner_group"
mkdir -m 0700 "$tmp/outside"
ln -s "$tmp/outside" "$private_root/linked"
if runner_ensure_private_directory "$private_root/linked/docker" "$runner_owner" "$runner_group" 2>/dev/null; then
echo 'Runner config symlink was accepted' >&2
exit 1
fi
[[ ! -e $tmp/outside/docker ]]
legacy_root=$tmp/legacy
mkdir -p "$legacy_root/.config/systemd/user/docker.service.d"
chmod 0755 "$legacy_root" "$legacy_root/.config" "$legacy_root/.config/systemd" "$legacy_root/.config/systemd/user" "$legacy_root/.config/systemd/user/docker.service.d"
for legacy_dir in "$legacy_root" "$legacy_root/.config" "$legacy_root/.config/systemd" "$legacy_root/.config/systemd/user" "$legacy_root/.config/systemd/user/docker.service.d"; do
runner_ensure_private_directory "$legacy_dir" "$runner_owner" "$runner_group"
[[ $(stat -c %a "$legacy_dir") == 700 ]]
done
user_config=$private_root/daemon.json
runner_install_user_content "$user_config" "$runner_owner" "$runner_group" 0600 <<'EOF'
{"data-root":"/private/runner"}
EOF
runner_install_user_content "$user_config" "$runner_owner" "$runner_group" 0600 <<'EOF'
{"data-root":"/private/runner"}
EOF
if runner_install_user_content "$user_config" "$runner_owner" "$runner_group" 0600 <<'EOF' 2>/dev/null
{"data-root":"/unexpected"}
EOF
then
echo 'Conflicting runner user config was accepted' >&2
exit 1
fi
migrated_unit=$tmp/akyldash-act-runner.service
printf '[Service]\nProtectHome=yes\nProtectSystem=strict\n' >"$migrated_unit"
chmod 0644 "$migrated_unit"
runner_install_content_allow_line_change "$migrated_unit" "$runner_owner" "$runner_group" 0644 'ProtectHome=yes' 'ProtectHome=read-only' <<'EOF'
[Service]
ProtectHome=read-only
ProtectSystem=strict
EOF
grep -Fqx 'ProtectHome=read-only' "$migrated_unit"
runner_install_content_allow_line_change "$migrated_unit" "$runner_owner" "$runner_group" 0644 'ProtectHome=yes' 'ProtectHome=read-only' <<'EOF'
[Service]
ProtectHome=read-only
ProtectSystem=strict
EOF
printf '[Service]\nProtectHome=read-only\nProtectSystem=no\n' >"$migrated_unit"
if runner_install_content_allow_line_change "$migrated_unit" "$runner_owner" "$runner_group" 0644 'ProtectHome=yes' 'ProtectHome=read-only' <<'EOF' 2>/dev/null
[Service]
ProtectHome=read-only
ProtectSystem=strict
EOF
then
echo 'Systemd unit with unrelated drift was accepted' >&2
exit 1
fi
image=$tmp/docker-store.img
runner_ensure_image "$image" 1048576 "$(command id -u)" 700
runner_ensure_image "$image" 1048576 "$(command id -u)" 700
[[ $(grep -c '^mkfs$' "$log") == 1 ]]
truncate -s 1048575 "$image"
if runner_ensure_image "$image" 1048576 "$(command id -u)" 700 2>/dev/null; then
echo 'Mismatched image size was accepted' >&2
exit 1
fi
[[ $(grep -c '^mkfs$' "$log") == 1 ]]
truncate -s 1048576 "$image"
if RUNNER_TEST_FS=ext3 runner_ensure_image "$image" 1048576 "$(command id -u)" 700 2>/dev/null; then
echo 'Existing non-ext4 image was accepted' >&2
exit 1
fi
[[ $(grep -c '^mkfs$' "$log") == 1 ]]
external=$tmp/external-file
printf 'preserve this file\n' >"$external"
race_image=$tmp/race.img
ln -s "$external" "$race_image"
if runner_ensure_image "$race_image" 1048576 "$(command id -u)" 700 2>/dev/null; then
echo 'Symlink runner image was accepted' >&2
exit 1
fi
[[ $(cat "$external") == 'preserve this file' ]]
rm -f "$race_image"
race_image=$tmp/race-during-format.img
export RUNNER_TEST_IMAGE="$race_image" RUNNER_TEST_REPLACE_IMAGE="$external"
if runner_ensure_image "$race_image" 1048576 "$(command id -u)" 700 2>/dev/null; then
echo 'Image path replacement during formatting was accepted' >&2
exit 1
fi
[[ $(cat "$external") == 'preserve this file' ]]
rm -f "$race_image"
unset RUNNER_TEST_IMAGE RUNNER_TEST_REPLACE_IMAGE
[[ $(grep -c '^mkfs$' "$log") == 2 ]]
unit_name='var-lib-akyldash\x2drunner-docker\x2ddata.mount'
unit_file=$tmp/systemd/$unit_name
mkdir -p "$(dirname "$unit_file")"
export RUNNER_TEST_STORE="$tmp/store" RUNNER_TEST_BACKING="$image"
export RUNNER_TEST_MOUNTED="$tmp/mounted"
runner_ensure_mount "$image" "$RUNNER_TEST_STORE" "$unit_name" "$unit_file"
[[ $(grep -c '^start ' "$log") == 1 ]]
grep -Fq "enable $unit_name" "$log"
grep -Fq "start $unit_name" "$log"
# A second run with the image mounted must reuse it and avoid another start.
runner_ensure_image "$image" 1048576 "$(command id -u)" 700
runner_ensure_mount "$image" "$RUNNER_TEST_STORE" "$unit_name" "$unit_file"
[[ $(grep -c '^mkfs$' "$log") == 2 ]]
[[ $(grep -c '^start ' "$log") == 1 ]]
chmod 0664 "$unit_file"
if runner_ensure_mount "$image" "$RUNNER_TEST_STORE" "$unit_name" "$unit_file" 2>/dev/null; then
echo 'Writable systemd mount unit was accepted' >&2
exit 1
fi
chmod 0644 "$unit_file"
export RUNNER_TEST_BACKING="$tmp/unrelated.img"
touch "$RUNNER_TEST_BACKING"
if runner_ensure_mount "$image" "$RUNNER_TEST_STORE" "$unit_name" "$unit_file" 2>/dev/null; then
echo 'Active mount backed by a different image was accepted' >&2
exit 1
fi
[[ $(grep -c '^start ' "$log") == 1 ]]
export RUNNER_TEST_BACKING="$image"
# Simulate interruption after unit installation/enable, before mount activation.
export RUNNER_TEST_STORE="$tmp/partial-store" RUNNER_TEST_MOUNTED="$tmp/partial-mounted"
export RUNNER_TEST_FAIL_START=1
if runner_ensure_mount "$image" "$RUNNER_TEST_STORE" "$unit_name" "$tmp/systemd/partial.mount" 2>/dev/null; then
echo 'Injected mount interruption was not observed' >&2
exit 1
fi
export RUNNER_TEST_FAIL_START=0
runner_ensure_image "$image" 1048576 "$(command id -u)" 700
runner_ensure_mount "$image" "$RUNNER_TEST_STORE" "$unit_name" "$tmp/systemd/partial.mount"
[[ $(grep -c '^mkfs$' "$log") == 2 ]]
[[ $(grep -c '^start ' "$log") == 3 ]]
export RUNNER_TEST_STORE="$tmp/store" RUNNER_TEST_MOUNTED="$tmp/mounted" RUNNER_TEST_OPTIONS=rw,relatime
if runner_validate_mount "$image" "$RUNNER_TEST_STORE" 2>/dev/null; then
echo 'Runner mount missing nosuid/nodev was accepted' >&2
exit 1
fi
unset RUNNER_TEST_OPTIONS
echo 'runner installer idempotency checks passed'
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env bash
set -Eeuo pipefail
config=infra/runner/config.yaml
installer=infra/runner/install-runner.sh
assert_absent() {
local pattern=$1 file=$2
if grep -Eq "$pattern" "$file"; then
echo "Forbidden content matched in $file" >&2
return 1
fi
}
grep -Eq '^ capacity: 1$' "$config"
grep -Fq 'akyldash-ci:docker://docker.gitea.com/runner-images:ubuntu-24.04' "$config"
grep -Fq 'docker_host: "-"' "$config"
grep -Eq '^ privileged: false$' "$config"
grep -Eq '^ valid_volumes: \[\]$' "$config"
grep -Fq -- '--cpus=2 --memory=3g --pids-limit=512' "$config"
assert_absent 'var/run/docker.sock|metrics:|health_check:|production.env|review_secret' "$config"
grep -Fq 'docker-ce-rootless-extras' "$installer"
grep -Fq 'runner_ensure_image "$runner_image" "$runner_image_bytes" 0 711' "$installer"
grep -Fq 'runner_lock_home "$runner_home"' "$installer"
grep -Fq 'test -w "$HOME" && test -w "$XDG_CONFIG_HOME" && test -w "$XDG_DATA_HOME"' "$installer"
grep -Fq 'rootless_env=(HOME="$runner_runtime_home" XDG_CONFIG_HOME="$runner_xdg_config_home" XDG_DATA_HOME="$runner_xdg_data_home"' "$installer"
grep -Fq 'Environment=XDG_CONFIG_HOME=$runner_xdg_config_home' "$installer"
grep -Fq 'Environment=XDG_DATA_HOME=$runner_xdg_data_home' "$installer"
grep -Fq 'runner_home/.config/systemd/user/docker.service.d/environment.conf' "$installer"
grep -Fq 'Environment=HOME=$runner_runtime_home' "$installer"
grep -Fq 'systemctl --user restart docker.service' "$installer"
grep -Fq 'systemctl --user show docker.service --property=MainPID --value' "$installer"
grep -Fq 'tr '\''\0'\'' '\''\n'\'' <"/proc/$docker_pid/environ"' "$installer"
grep -Fq 'grep -Fqx -- "$expected"' "$installer"
if grep -Fq 'systemctl --user set-environment' "$installer"; then
echo 'Rootless Docker environment must persist in its user unit drop-in' >&2
exit 1
fi
grep -Fq 'HOME=/var/lib/akyldash-runner/.config/act-runner' infra/runner/act-runner-healthcheck.sh
grep -Fq 'XDG_CONFIG_HOME=/var/lib/akyldash-runner/.config' infra/runner/act-runner-healthcheck.sh
grep -Fq 'XDG_DATA_HOME=/var/lib/akyldash-runner/.config/act-runner/.local/share' infra/runner/act-runner-healthcheck.sh
if grep -Fq 'env HOME="$runner_home"' "$installer"; then
echo 'Protected runner home must not be passed as rootless Docker HOME' >&2
exit 1
fi
grep -Fq 'die '\''stop akyldash-act-runner.service after all jobs finish before rerunning this installer' "$installer"
grep -Fq 'ReadWritePaths=$runner_runtime_home $runner_xdg_config_home /var/log/akyldash-runner /run/user/$runner_uid' "$installer"
grep -Fq 'ProtectHome=read-only' "$installer"
grep -Fq "runner_install_content_allow_line_change /etc/systemd/system/akyldash-act-runner.service root root 0644 'ProtectHome=yes' 'ProtectHome=read-only'" "$installer"
grep -Fq 'ProtectSystem=strict' "$installer"
grep -Fq 'NoNewPrivileges=yes' "$installer"
grep -Fq 'PrivateTmp=yes' "$installer"
grep -Fq 'ProtectKernelTunables=yes' "$installer"
grep -Fq 'ProtectKernelModules=yes' "$installer"
grep -Fq 'ProtectKernelLogs=yes' "$installer"
grep -Fq 'RestrictSUIDSGID=yes' "$installer"
if grep -Fxq 'ProtectHome=yes' "$installer"; then
echo 'Runner service must keep /run/user reachable with read-only home protection' >&2
exit 1
fi
grep -Fq 'os.O_NOFOLLOW | os.O_CLOEXEC' infra/runner/secure-runner-image.py
grep -Fq 'os.posix_fallocate(image_fd, 0, int(bytes_text))' infra/runner/secure-runner-image.py
grep -Fq 'pass_fds=(image_fd,)' infra/runner/secure-runner-image.py
grep -Fq 'systemctl enable "$unit_name"' infra/runner/install-runner-lib.sh
grep -Fq 'systemctl start "$unit_name"' infra/runner/install-runner-lib.sh
grep -Fq 'runuser -u "$owner" -- install -d -m 0700 "$directory"' infra/runner/install-runner-lib.sh
grep -Fq 'runner_install_user_content "$runner_home/.config/docker/daemon.json"' "$installer"
assert_absent 'basename.*runner_mount_unit|enable --now.*runner_mount_unit' "$installer"
grep -Fq 'groups=$(id -nG "$user")' infra/runner/install-runner-lib.sh
grep -Fq 'id -gn "$user"' infra/runner/install-runner-lib.sh
assert_absent 'dockerd-rootless-setuptool.sh install --force' "$installer"
grep -Fq 'runner_sha256=3acac8b506ac8cadc88a55155b5d6378f0fab0b8f62d1e0c0450f4ccd69733e2' "$installer"
grep -Fq 'find-free-subid-range.awk' "$installer"
grep -Fq 'usermod "${subid_args[@]}" "$runner_user"' "$installer"
grep -Fq 'subid_args+=(--add-subuids "$subid_range")' "$installer"
assert_absent 'usermod.*(sudo|docker)|/var/run/docker.sock|/etc/sudoers' "$installer"
for workflow in .gitea/workflows/*.yaml; do
grep -Fq 'runs-on: akyldash-ci' "$workflow"
if grep -Fq 'runs-on: ubuntu-latest' "$workflow"; then
echo "Workflow still targets the unavailable ubuntu-latest label: $workflow" >&2
exit 1
fi
done
grep -Fq 'test ! -S /var/run/docker.sock' .gitea/workflows/runner-smoke.yaml
grep -Fq 'for socket in /run/user/*/docker.sock' .gitea/workflows/runner-smoke.yaml
grep -Fq 'test ! -e /etc/akyldash/production.env' .gitea/workflows/runner-smoke.yaml
grep -Fq 'test ! -e /etc/akyldash/review_secret' .gitea/workflows/runner-smoke.yaml
assert_absent '(^|[[:space:]])(docker|docker-compose|deploy)([[:space:]]|$)|production.env=|review_secret=' .gitea/workflows/runner-smoke.yaml
fixture=$(mktemp)
fixture_g=$(mktemp)
trap 'rm -f "$fixture" "$fixture_g"' EXIT
printf 'production.env\n' >"$fixture"
if assert_absent 'deploy|production.env|review_secret|docker.sock' "$fixture" 2>/dev/null; then
echo 'Negative guard regression: prohibited fixture was accepted' >&2
exit 1
fi
printf 'codex:100000:65536\n' >"$fixture"
printf 'codex:165000:1000\n' >"$fixture_g"
range=$(awk -f infra/runner/find-free-subid-range.awk "$fixture" "$fixture_g")
[[ $range == 231072-296607 ]]
: >"$fixture_g"
range=$(awk -f infra/runner/find-free-subid-range.awk "$fixture" "$fixture_g")
[[ $range == 165536-231071 ]]
: >"$fixture"
range=$(awk -f infra/runner/find-free-subid-range.awk "$fixture" "$fixture_g")
[[ $range == 100000-165535 ]]
printf 'broken\n' >"$fixture_g"
if awk -f infra/runner/find-free-subid-range.awk "$fixture" "$fixture_g" >/dev/null 2>&1; then
echo 'Malformed subordinate ID allocation was accepted' >&2
exit 1
fi
echo 'runner configuration guards passed'
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
set -euo pipefail
installer=infra/runner/install-runner.sh
grep -Fq 'logrotate acl docker-ce-rootless-extras' "$installer"
grep -Fq 'readonly runner_log_dir=/var/log/akyldash-runner' "$installer"
grep -Fq 'readonly runner_log="$runner_log_dir/act_runner.log"' "$installer"
grep -Fq 'install -d -o root -g "$runner_user" -m 0750 /etc/akyldash-runner "$runner_log_dir"' "$installer"
grep -Fq 'install -o "$runner_user" -g "$runner_user" -m 0600 /dev/null "$runner_log"' "$installer"
grep -Fq 'chown "$runner_user:$runner_user" "$runner_log"' "$installer"
grep -Fq 'chmod 0600 "$runner_log"' "$installer"
grep -Fq 'setfacl -b "$runner_log_dir"' "$installer"
grep -Fq 'setfacl -k "$runner_log_dir"' "$installer"
grep -Fq 'setfacl -b "$runner_log"' "$installer"
grep -Fq 'setfacl -m u:codex:--x "$runner_log_dir"' "$installer"
grep -Fq 'setfacl -m u:codex:r--,g::---,m::r-- "$runner_log"' "$installer"
grep -Fq "grep -Fqx 'group::---'" "$installer"
grep -Fq "grep -Fqx 'other::---'" "$installer"
grep -Fq 'UMask=0077' "$installer"
grep -Fq 'ExecStartPost=/usr/bin/setfacl -m u:codex:r--,g::---,m::r-- /var/log/akyldash-runner/act_runner.log' "$installer"
grep -Fq ' copytruncate' "$installer"
grep -Fq ' postrotate' "$installer"
grep -Fq ' /usr/bin/setfacl -m u:codex:r--,g::---,m::r-- /var/log/akyldash-runner/act_runner.log' "$installer"
grep -Fq ' endscript' "$installer"
if grep -Eq 'setfacl .*(-R|default:)|chmod 0644.*act_runner.log|other::r--' "$installer"; then
echo 'Runner log ACL must stay limited to codex reading the single log file' >&2
exit 1
fi
echo 'runner log ACL checks passed'
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
if (($# == 0)); then
echo 'Usage: run-as-unprivileged.sh command [args...]' >&2
exit 2
fi
if [[ $EUID -eq 0 ]]; then
if ! command -v setpriv >/dev/null 2>&1; then
echo 'Cannot run the guard test as non-root: setpriv is required.' >&2
exit 1
fi
exec setpriv --reuid=65534 --regid=65534 --clear-groups -- "$@"
fi
exec "$@"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
helper="$(dirname "$0")/run-as-unprivileged.sh"
expected_uid=$EUID
if [[ $EUID -eq 0 ]]; then
expected_uid=65534
fi
if ! actual_uid=$(bash "$helper" id -u); then
echo 'Failed to run the test command as an unprivileged user.' >&2
exit 1
fi
if [[ $actual_uid != "$expected_uid" ]]; then
echo "Expected test command UID $expected_uid, got $actual_uid." >&2
exit 1
fi
echo "PASS test command runs as UID $actual_uid"