diff --git a/.claude/agents/security-reviewer.md b/.claude/agents/security-reviewer.md new file mode 100644 index 0000000..ed8c494 --- /dev/null +++ b/.claude/agents/security-reviewer.md @@ -0,0 +1,98 @@ +--- +name: security-reviewer +description: Security review of a pullgate change before it is committed or merged. Use for every pull request and every uncommitted change that touches Go code, units, example configs, CI, release, or the design and threat model. +tools: Read, Grep, Glob, Bash +model: opus +--- + +You review changes to pullgate, a tool that lets a Linux host pull a git repo +and apply one exact commit as root, only after its owner taps Apply on +Telegram. A mistake here gives root on the host to whoever can push to the +repo, or applies a commit nobody approved. Review like an attacker who can +push any commit to the repo, who may control the listener user, and who may +have the bot token. + +## Before you start + +1. Read `THREAT-MODEL.md` and `DESIGN.md`. They define what must hold. +2. Find the change: the diff you were given, or `git diff main...HEAD` + plus `git diff` and `git status` for uncommitted work. +3. Read the changed files in full, not only the diff lines. Follow calls + into code that did not change when it matters. + +## What to check + +**The gate (rules 1, 2, 5)** +- No setting is read from the repo or the tree. Only `/etc/pullgate/*.toml`. +- Root applies only a SHA from its own state, found by the code of an + approval, with a constant-time compare, inside `asked <= now < expires`. + A code works once: the question is removed from the state (synced) before + the apply starts. +- Forward only: the SHA must descend from the applied SHA, checked again at + apply time, unless `allow_older` is set. +- At most one open question. A newer tip never changes what an approval + applies. +- The state moves forward only after `apply` and `health` succeed. + `in_progress` is synced before `apply` runs; found at start, it pauses. +- `on_failure`: `rollback` runs the old apply and health, and a failed + rollback writes the pause file; `pause` holds the SHA and does not write + the pause file. The code default is `pause`. + +**No code before the tap (rule 3)** +- Before Apply, nothing from the commit runs. git only reads objects. +- `check` and `summary` never run as root: a uid 0 `check_user` is refused, + the credential is set, extra groups are dropped. +- The tree is read-only, written by pullgate from blobs: no checkout, no + `git archive`, no filters, no submodules, no LFS. Path parts `..`, `.git`, + empty, NUL are refused. Files are opened with `O_NOFOLLOW|O_EXCL` in + directories made in this export. Caps on files and bytes hold. + +**git as root (rule 6)** +- Every git call goes through the safe runner: the directory checks first, + an empty environment, no system or global config, hooks off, fsmonitor + off, only the ssh and file protocols, a timeout, an output cap. +- The URL and branch cannot become options (`-`). + +**The listener (rule 4)** +- Only the listener holds the token. The token never reaches a log, an + error (Go's `*url.Error` holds the URL, and the URL holds the token), or a + file other than its own. +- A tap counts only from `owner_id`, in `chat_id`, on the message ID of an + open, unexpired question whose code it holds, once. +- It writes only approvals with a code and an action. It opens no port. + +**Messages** +- Text from the commit (subjects, file names, summary and check output) is + cleaned of control and invisible characters, capped per line, + HTML-escaped, and shown after the head lines. The message fits 4096 + characters and is cut on whole lines. + +**Files and processes** +- Root reads inbox files with `O_NOFOLLOW`, a size cap, an owner check, and + strict JSON. Writes are atomic (temp, sync, rename). +- Config, key and known hosts files are checked for owner and mode. +- Commands are absolute argv lists, no shell, with an empty environment plus + the documented `PULLGATE_*` variables, a timeout that kills the process + group, and an output cap. +- Fail closed: every error, timeout or unclear state means no apply. + +**Repo hygiene** +- No real host names, domain names, IP addresses, VPN or tailnet names, + tokens, keys, user IDs, private names of people, or links to private + repositories. Test data is invented. +- New dependencies are justified. GitHub Actions are pinned to a full commit + SHA. Workflows have the smallest `permissions`. +- If the change alters what a message shows, what root or the listener + checks, or where a file goes, `THREAT-MODEL.md` and `DESIGN.md` change in + the same pull request. +- Tests cover the deny paths, not only the happy path. Run + `go test -race ./...` and `go vet ./...` if Go is available. + +## Output + +List findings, most severe first. For each: severity (critical, high, +medium, low), `file:line`, what is wrong, a concrete way it fails (inputs or +steps → wrong result), and the fix. Mark a finding "unsure" if you could not +confirm it. If you find nothing, say so and list what you checked. + +Do not edit files, do not commit, and do not start other agents. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..92a9599 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,26 @@ +version: 2 +updates: + # Pull request titles look like "chore(deps): bump ...". The chore type + # makes no release. + - package-ecosystem: gomod + directory: / + schedule: + interval: weekly + # Wait 7 days after a new version comes out, so that a bad release can + # be found and pulled first. Security updates do not wait. + cooldown: + default-days: 7 + commit-message: + prefix: chore + include: scope + + # Pull request titles look like "ci(deps): bump actions/checkout ...". + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + cooldown: + default-days: 7 + commit-message: + prefix: ci + include: scope diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6ed1cc9 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,86 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + schedule: + # Every Monday: find vulnerabilities that became known since the last push. + - cron: "17 5 * * 1" + +permissions: + contents: read + +concurrency: + # A new push to a pull request cancels the older run for it. + # Each push to main gets its own group, so those runs are never cancelled. + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: true + +jobs: + test: + name: test (${{ matrix.go }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # go.mod: the oldest Go we support (the go line in go.mod). + # stable: the newest Go release. + go: [go.mod, stable] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ matrix.go == 'go.mod' && 'go.mod' || '' }} + go-version: ${{ matrix.go == 'stable' && 'stable' || '' }} + - name: Check formatting + run: | + unformatted="$(gofmt -l .)" + if [ -n "$unformatted" ]; then + echo "These files are not formatted with gofmt:" + echo "$unformatted" + exit 1 + fi + - run: go vet ./... + # The tests need git. GitHub sets CI=true, and then a test fails + # instead of skips when git is missing. + - run: git --version + - run: go test -race ./... + - name: Build static binaries + run: | + for arch in amd64 arm64; do + CGO_ENABLED=0 GOOS=linux GOARCH="$arch" go build -trimpath -o "/tmp/pullgate-$arch" ./cmd/pullgate + done + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0 + with: + # Dependabot does not update this version. Update it by hand. + version: v2.14.0 + # With the tag e2e, the files of the end-to-end test are checked too. + args: --build-tags e2e + + vuln: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + # Release binaries are built with the newest Go, so check the + # standard library of that version. + go-version: stable + - name: govulncheck + # Dependabot does not update this version. Update it by hand. + run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml new file mode 100644 index 0000000..b085a4d --- /dev/null +++ b/.github/workflows/pr-title.yml @@ -0,0 +1,43 @@ +name: PR title + +# The squash merge uses the pull request title as the commit message, and +# release-please reads those messages. So the title must follow +# Conventional Commits. See docs/releasing.md. + +on: + # pull_request_target also runs for pull requests from forks. It runs with + # this repository's token, so this workflow must never check out or run + # code from the pull request. It only reads the title. + pull_request_target: + types: [opened, edited, synchronize, reopened] + +permissions: + pull-requests: read # read the pull request + +concurrency: + # Check only the newest title of a pull request. + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + title: + name: Conventional Commits title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + types: | + security + feat + fix + perf + revert + docs + chore + ci + test + refactor + build + style diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7af3079 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# Release build output +/dist/ + +# Binary from "go build ./cmd/pullgate" +/pullgate + +# Test coverage output +*.out +*.coverprofile +coverage.html + +# Editor and OS files +.idea/ +.vscode/ +*.swp +*~ +.DS_Store diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..9022e76 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,61 @@ +# golangci-lint configuration, v2 format. +# Reference: https://golangci-lint.run/docs/configuration/file/ +version: "2" + +linters: + # standard: errcheck, govet, ineffassign, staticcheck, unused. + default: standard + enable: + - bodyclose # HTTP response bodies are closed + - errorlint # errors are checked with errors.Is/As and wrapped with %w + - forbidigo # library code does not print (see settings) + - gosec # security problems + - misspell # spelling mistakes in comments and strings + - noctx # network calls take a context.Context + - nolintlint # //nolint comments name the linter and give a reason + - unconvert # type conversions that do nothing + + settings: + forbidigo: + # Library code must never print or log on its own: a secret could end + # up in a terminal or a log. Library code gets an io.Writer or a + # *slog.Logger from its caller, and returns values and errors. + # Code in cmd/ talks to the user, so it may print (see exclusions below). + forbid: + - pattern: ^fmt\.Print.*$ + msg: library code must not print; return the value or an error + - pattern: ^print(ln)?$ + msg: library code must not print; return the value or an error + - pattern: ^os\.(Stdout|Stderr)$ + msg: library code must not use stdout or stderr; take an io.Writer + - pattern: ^log\.(Logger\.)?(Print|Fatal|Panic).*$ + msg: library code must not log; return an error or take a *slog.Logger + - pattern: ^log\.(Logger\.)?(Output|SetOutput)$ + msg: library code must not log; return an error or take a *slog.Logger + - pattern: ^slog\.(Debug|Info|Warn|Error|Log)(Context|Attrs)?$ + msg: library code must not use the default logger; take a *slog.Logger + - pattern: ^slog\.(Default|SetDefault)$ + msg: library code must not use the default logger; take a *slog.Logger + # Match on types, so an import alias or a *log.Logger cannot hide a call. + analyze-types: true + nolintlint: + require-explanation: true + require-specific: true + + exclusions: + rules: + # Code in cmd/ may print. Only the rules about printing and logging + # (their messages start with "library code must not") are off there. + - path: ^cmd/ + linters: + - forbidigo + text: library code must not + +formatters: + enable: + - gofmt + - goimports + settings: + goimports: + local-prefixes: + - github.com/code6x/pullgate diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..456f327 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,76 @@ +# Working on pullgate + +pullgate lets a Linux host pull a git repo by itself and apply one exact +commit only after its owner taps Apply on Telegram. Read +[DESIGN.md](DESIGN.md) and [THREAT-MODEL.md](THREAT-MODEL.md) before you +change code. They are the rules the code must follow. + +## Layout + +- `cmd/pullgate/` - the one binary. Subcommands: `run`, `listen`, `apply`, + `status`, `version`. +- `internal/` - one package per part. Packages do not import `cmd/`. + - `internal/config/` - the instance and listener configs, and the checks + of the files they name (DESIGN.md sections 4 and 5). + - `internal/safedir/` - the check that no other user can write a + directory (rule 6, DESIGN.md section 6). + - `internal/gitx/` - git, run safely: fetch, ancestry, log, diff, and the + export of a tree without filters (DESIGN.md section 6). + - `internal/state/` - the state file, the lock and the pause file. + - `internal/spool/` - the outbox and inbox files between root and the + listener (DESIGN.md section 8). + - `internal/telegram/` - a small Bot API client. The token never shows in + an error. + - `internal/listener/` - `pullgate listen` (DESIGN.md section 9). + - `internal/message/` - the text of the messages: cleaning, the watch + list, the cut to one message (DESIGN.md section 12). + - `internal/gate/` - `run`, `apply` and `status` (DESIGN.md sections 7, + 9, 10, 13). +- `contrib/` - example systemd units and example configs. +- `test/e2e/` - the end-to-end test. Build tag `e2e`. +- `.claude/agents/security-reviewer.md` - the security review every change + gets. + +## Commands + +```sh +go test -race ./... +go vet ./... +golangci-lint run --build-tags e2e +go test -race -tags e2e ./test/e2e/... # needs git +``` + +## Rules + +- **This repository is public.** Never add a real host name, domain name, + IP address, VPN or tailnet name, token, key, user ID, private name of a + person, household or company, or a link to a private repository. Use + example names: `example-host`, `config-repo`, `git.example.com`, and IP + addresses from `192.0.2.0/24`. Test keys and tokens are made by the test. +- **Never log, print or return a secret value** (the bot token, the deploy + key, a one-time code), not even in an error or a test failure. +- **Fail closed.** Every error, timeout, cancel or unclear case means: do + not apply, do not approve. +- **Root trusts nothing from the listener, the repo, or the commit** except + a code that matches its own state. It takes the SHA from its own state. +- **Every change has tests**, and they test the deny paths, not only the + happy path. +- **Every change gets a security review** by the agent in + `.claude/agents/security-reviewer.md` before it is committed. Fix what it + finds. If you do not fix a finding, say why in the pull request. +- **If a change alters** what a message shows, what root or the listener + checks, what runs as which user, or where a file goes, update DESIGN.md + and THREAT-MODEL.md in the same pull request. If it changes the config, a + unit or a command, update the README and `contrib/` too. +- **Dependencies:** the standard library and `github.com/BurntSushi/toml`. + Anything else needs a reason in the pull request. +- **Git:** one feature branch and one pull request per change. Pull request + titles follow [Conventional Commits](https://www.conventionalcommits.org/) + (`feat:`, `fix:`, `docs:`, `test:`, `ci:`, `chore:`). Pull requests are + squash merged. Never push to `main` directly. +- **Open work is a GitHub issue** with a "Done when" checklist, never a TODO + file. +- **Every error says how to fix it**: what is wrong, where (the file and key, + or the step), and how to fix it. +- **Docs** use plain English and short sentences. Many readers are not + native speakers. Dates are absolute (`2026-11-11`). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..29a585c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,4 @@ +@AGENTS.md + +Before you commit, run the `security-reviewer` agent from +`.claude/agents/security-reviewer.md` on the change. diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..9dca30f --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,570 @@ +# pullgate design + +Status: accepted for version 0.1 on 2026-11-11. + +pullgate lets a Linux host change only through its own updates. The host +pulls a git repo by itself. It applies a new commit only after its owner +taps **Apply** on a Telegram question that names that exact commit. + +Read [THREAT-MODEL.md](THREAT-MODEL.md) next. It says what this design +protects, and where it stops. + +## 1. Words + +- **instance**: one repo that one host follows, with one config file + `/etc/pullgate/NAME.toml`, one state directory and one lock. A host can + have several instances. `NAME` matches `[a-z0-9][a-z0-9-]{0,31}`. +- **tip**: the commit that the configured branch points to after a fetch. +- **applied SHA**: the last commit that root applied with success. It is + empty before the first apply. +- **held SHA**: the last SHA whose apply failed, while no newer apply has + worked (section 10). +- **question**: one Telegram message that names one full SHA and has two + buttons, Apply and Skip. +- **code**: a random one-time code of 128 bits (22 characters, base64url). + The buttons carry it instead of the SHA. +- **approval**: a small file that the listener writes when the owner taps a + button. It holds the code and the button (apply or skip). Nothing else. +- **tree**: a clean, read-only copy of the files of one commit, written by + pullgate itself from git objects. +- **pause file**: `/var/lib/pullgate/NAME/paused`. While it exists, the + instance does nothing: no run, no apply. + +## 2. The rules + +These rules come from issue #1. Each one has tests (section 14). + +1. **The gate lives on the host, never in the repo.** What runs, who may + approve and which paths get a warning come only from the host config: + `/etc/pullgate/NAME.toml` and `/etc/pullgate/listener.toml`. pullgate + never reads any setting from the repo. A commit cannot change the gate. +2. **One exact commit.** The question shows the full SHA. Apply applies only + that SHA, even when a newer commit arrives in between. +3. **No code from the new commit runs before Apply.** Before the tap, + pullgate only fetches the commit and reads it with git. The optional + `check` and `summary` commands may read the tree as data. They run as an + unprivileged user (`check_user`), never as root, on a read-only tree. +4. **Only one process holds the bot token**: the listener. It runs as its own + unprivileged user. It only connects out (`getUpdates` long-poll), it opens + no port. It accepts a tap only from the configured owner user ID, in the + configured chat, on an open question. All it can do is write an approval + for that open question. The approval carries only the code. Root looks + up the SHA in its own state. +5. **Root does the apply.** It acts only on an approval whose code matches a + question that root recorded itself, and only within the time limit of that + question. By default it moves forward only: the new SHA must descend from + the applied SHA. Going to an older or unrelated commit needs the explicit + setting `allow_older = true`. Before the first apply there is no applied + SHA, so any tip may be asked. +6. **Root never runs git in a directory another user can write.** Before + every git command, root checks the git directory and every directory above + it (section 6). git runs with hooks off and without system or global + config. pullgate writes the tree itself from git objects: no filters, no + submodules, no LFS. + +## 3. Processes and users + +| process | user | started by | holds | +|---|---|---|---| +| `pullgate run NAME` | root | a timer (`pullgate-run@NAME.timer`) | the clone, the state, the deploy key | +| `pullgate apply NAME` | root | a path unit (`pullgate-apply@NAME.path`) when the inbox is not empty, or the auto approval exists | the state | +| `pullgate listen` | `pullgate` (own user) | a service (`pullgate-listen.service`) | the bot token, its list of open questions | +| `check`, `summary` | `check_user` (default `pullgate-check`) | `pullgate run` | nothing | +| `apply`, `health` | root | `pullgate apply` | what the owner's command needs | +| `pullgate status NAME` | root | the owner | nothing | + +Root and the listener never talk directly. They use a spool directory +(section 8). + +The run unit is sandboxed (read-only system, private `/tmp`, no new +privileges). The apply unit runs the owner's `apply` command as root, so it +can be less strict; each example sets what its `apply` needs. + +## 4. Files + +| path | owner, mode | what | +|---|---|---| +| `/etc/pullgate/NAME.toml` | root, 0600 or 0644 | the instance config | +| `/etc/pullgate/listener.toml` | root, 0640 group listener, or 0644 | the listener config | +| the deploy key | root, 0600 | read-only SSH deploy key | +| the known hosts file | root, 0644 | the pinned SSH host key of the git server | +| the bot token file | the listener user, 0600 (or a systemd credential) | the bot token | +| `/var/lib/pullgate/NAME/` | root, 0711 | the state directory | +| `/var/lib/pullgate/NAME/repo.git` | root, 0700 | the bare clone | +| `/var/lib/pullgate/NAME/state.json` | root, 0600 | the state (section 9) | +| `/var/lib/pullgate/NAME/lock` | root, 0600 | the lock (`flock`) | +| `/var/lib/pullgate/NAME/paused` | root | the pause file | +| `/var/lib/pullgate/NAME/auto-approval` | root, 0600 | the approval that `auto` mode writes (section 13) | +| `/var/lib/pullgate/NAME/trees/` | root, 0711 | the trees of one process (section 6) | +| `/var/spool/pullgate/` and `/var/spool/pullgate/NAME/` | root, 0755 | the spool | +| `/var/spool/pullgate/NAME/outbox` | root, group listener, 0770 | messages from root to the listener | +| `/var/spool/pullgate/NAME/inbox` | listener, 0700 | approvals from the listener to root | +| `/var/lib/pullgate-listener/state.json` | listener, 0600 | the listener's open questions | + +The paths can be changed with `--config-dir`, `--state-dir` and +`--spool-dir`, for tests. + +**Checks of the gate files.** pullgate refuses to start when the instance +config, the deploy key, the known hosts file, or the program (the first +word) of a command is a symlink, is not owned by root, or can be written by +group or others; or when a directory above one of them fails the check of +section 6. The deploy key must also not be readable by group or others. The +listener checks `listener.toml` and its token file the same way (the token +file must be owned by the listener user). In tests, "root" means the user +that runs the test. + +**Files in directories that the listener can write.** Root never follows a +path that the listener can change. It opens the spool directories with +`os.OpenRoot` (no symlinks out of the directory), fixes their owner and mode +through the open directory, creates files in them with +`O_CREAT|O_EXCL|O_NOFOLLOW` under a random temporary name and renames them +in the same directory. `/var/spool/pullgate` and `NAME/` are owned by root +and pass the check of section 6, so the listener cannot swap `outbox` or +`inbox` for a symlink. + +## 5. The instance config + +```toml +mode = "ask" # "ask" (default), "auto" or "off" +on_failure = "rollback" # "rollback" or "pause"; the code default is "pause" +host = "example-host" # shown in each message; default: the host name + +[repo] +url = "ssh://git@git.example.com/owner/config-repo.git" +branch = "main" +deploy_key = "/etc/pullgate/NAME.key" +known_hosts = "/etc/pullgate/NAME.known_hosts" + +[commands] +# argv lists, no shell. The first word is an absolute path. +check = ["/usr/local/bin/check-config", "--strict"] # optional +summary = ["/usr/local/bin/config-diff"] # optional +apply = ["/usr/local/sbin/install-config"] # required +health = ["/usr/local/sbin/health-check"] # optional +check_user = "pullgate-check" +check_timeout = "5m" +apply_timeout = "30m" + +[watch] +# A warning in the question for each changed path that matches. +# "*" matches inside one path part, "**" matches any number of parts. +paths = ["policy/**", "*.toml"] + +[limits] +questions_per_day = 10 # default 10 +approval_ttl = "12h" # default 12h, at most 7 days +max_failed_tries = 1 # default 1; counts only with on_failure = "rollback" +max_files = 100000 # default 100000 files in one tree +max_tree_bytes = 1073741824 # default 1 GiB in one tree +allow_older = false # default false (rule 5) +refuse_symlinks = false # default false; true refuses a commit with a symlink that points out of the tree + +[listener] +user = "pullgate" # the user of the listener; owns the inbox +``` + +Unknown keys are an error. An unknown mode or `on_failure` is an error. A +missing `apply` is an error. Every error names the file, the key and the fix. + +There is no default for `on_failure` in the example configs: each example +sets it. The code default is `pause`, because it is the safe choice. + +**The repo URL.** `ssh://…` and `user@host:path` use SSH (section 6). A path +that starts with `/`, or a `file://` URL, is a local repo. root runs git in +it too (`git-upload-pack`), so a local repo must pass the same check as the +clone (section 6): owned by root, nobody else can write it. Other URLs +(`https://`, `git://`, relative paths) are refused. The key and known hosts +paths may hold only `A-Za-z0-9._/-`, because git gives `GIT_SSH_COMMAND` to +a shell. + +## 6. Git, safely (rule 6) + +Before each git command, root checks the **git directory**: + +- The git directory and each directory above it up to `/` must be owned by + root (the running user) and not writable by group or others. +- One exception for a directory above: it may be writable by others when it + is owned by root and has the sticky bit (like `/tmp`). Then no other user + can rename or remove our directory in it. +- Every file and directory inside the git directory must be owned by root, + must not be writable by group or others, and must be a regular file or a + directory (no symlink, no special file). + +If a check fails, pullgate stops with an error that names the path, and runs +no git. + +Each git command runs: + +- with an empty environment, plus `PATH`, `HOME` set to the state + directory, `GIT_CONFIG_NOSYSTEM=1`, `GIT_CONFIG_GLOBAL=/dev/null`, + `GIT_TERMINAL_PROMPT=0`, `GIT_ASKPASS=`, `LC_ALL=C` and + `GIT_SSH_COMMAND` (below); +- with these settings before the subcommand: `core.hooksPath=/dev/null`, + `core.fsmonitor=false`, `protocol.allow=never`, `protocol.ssh.allow=always`, + `protocol.file.allow=always` (for local repos, see section 5), + `submodule.recurse=false`, `fetch.recurseSubmodules=false`, + `core.attributesFile=/dev/null`, `transfer.fsckObjects=true`, + `gc.auto=0` and `maintenance.auto=false`; +- with `--git-dir` set, never in a work tree; +- in its own process group, with a timeout that kills the group, and a cap + on its output. + +The fetch is: + +``` +git fetch --no-tags --no-recurse-submodules --no-write-fetch-head \ + --no-auto-gc -- URL +refs/heads/BRANCH:refs/pullgate/tip +``` + +`GIT_SSH_COMMAND` is `ssh -F /dev/null -i KEY -o IdentitiesOnly=yes +-o IdentityAgent=none -o UserKnownHostsFile=KNOWN_HOSTS +-o GlobalKnownHostsFile=/dev/null -o StrictHostKeyChecking=yes +-o BatchMode=yes`. The URL comes from the host config. It must not start +with `-`, so git cannot read it as an option. The branch must be a plain +name (`[A-Za-z0-9][A-Za-z0-9._/-]*`, no `..`). + +Then `git rev-parse --verify refs/pullgate/tip^{commit}` gives the tip. +pullgate keeps `refs/pullgate/applied` on the applied SHA, so git never +loses it after a force push. No gc runs. + +The other reads are `git merge-base --is-ancestor`, `git rev-list --count`, +`git log -z --no-mailmap --format=%s`, `git diff-tree -r -z --no-renames +--name-only` and `git ls-tree -r -z`. + +**The tree.** pullgate never uses `git checkout` or `git archive`, because +both apply `.gitattributes` (filters, `export-subst`, `export-ignore`). It +reads `git ls-tree -r -l -z --full-tree SHA` and then each blob with +`git cat-file --batch`. It writes the files itself: + +- Each path part must not be empty, `.`, `..` or `.git` (in any case), and + must not hold a NUL. A bad path stops the export. +- Regular files are written 0444 (0555 when the git mode is 100755), with + `O_CREAT|O_EXCL|O_NOFOLLOW`, inside directories that pullgate made in this + export. A repeated name, or a path below a file or a symlink of the tree, + stops the export. +- Symlinks (mode 120000) are written as symlinks. pullgate never follows a + symlink of a tree. A symlink whose target is absolute or holds `..` gets a + warning in the question; with `refuse_symlinks = true` it stops the + export. A command that reads the tree must not follow symlinks blindly. +- Submodules (mode 160000) are skipped and listed in the question as a + warning. +- The export stops when the tree has more than `max_files` entries or more + than `max_tree_bytes` bytes. +- The export goes to `trees/.tmp-RANDOM`. Only when it is complete does it + get its final name. Then each directory gets mode 0555, and the top + directory gets 0750 with group `check_user`. + +**Fresh trees.** A tree belongs to one process. `pullgate run` exports the +trees for `check` and `summary`; `pullgate apply` exports fresh trees for +`apply`, `health` and a rollback. Each process removes its trees when it +ends, and removes trees that an earlier process left (after a crash) when it +starts. So a tree that a command changed, or a half-written tree, is never +used again. + +## 7. One run (`pullgate run NAME`) + +1. Read the config. Take the lock (`flock`, no wait). If another run or + apply holds it, log "busy" and exit 0. If the pause file exists, log + "paused" and exit 0. If `mode = "off"`, log "off" and exit 0. +2. If the state shows an apply in progress (section 10), write the pause + file, report, and exit. +3. Make sure the clone and the spool directories exist with the right owners + and modes (section 4). Fetch (section 6). +4. Expire: each question in the state whose time is up is removed. If it was + open, root asks the listener to edit it ("expired") and marks its SHA + expired. +5. Decide: + - tip = applied SHA: nothing to do. If a question is open, close it + ("the branch is back to the applied commit"). + - tip = the SHA of the open question: nothing to do. + - tip is the held SHA, or was asked before and the question expired or + was skipped, or its check failed, or it was refused, or it failed + `max_failed_tries` times: nothing to do. `pullgate status NAME + --ask-again` clears this mark. + - tip is not a descendant of the applied SHA (an older commit, a force + push, a rewritten branch) and `allow_older` is false: refuse. Send one + notice for this SHA and mark it refused. When `allow_older` is true, + ask, with a warning line at the top: "This commit is not a descendant + of the applied commit." With no applied SHA, every tip is allowed. + - the questions in the last 24 hours reached `questions_per_day`: log it, + send one notice per day, and do not ask. +6. Export the tree of the tip, and the tree of the applied SHA + (`PULLGATE_OLD_TREE`). +7. Run `check` as `check_user` (section 11). If it fails, mark the SHA + "check failed", send a notice with the last lines of its output, and do + not ask. The same SHA is not checked again. +8. Run `summary` as `check_user`, and build the message (section 12). +9. If a question is open, close it: root marks it superseded in its state, + and asks the listener to edit it ("a newer commit replaced this + question"). A tap that the listener took before the edit still counts + for the old SHA (rule 2); section 9 says how. +10. `ask`: make a new code, record the question in the state (synced to + disk) and write the question to the outbox. `auto`: record the question + in the state the same way, but instead of a message, write the code to + the auto approval file (section 13). + +## 8. The spool + +Each instance has `/var/spool/pullgate/NAME/outbox` and `.../inbox`. + +**Outbox** (root writes, the listener reads and removes). One JSON file per +message, named `SEQ.json` with a 20-digit sequence number (nanoseconds), +written to a random `.tmp-*` name and renamed. The listener handles them in +name order and skips names that start with `.`. Kinds: + +- `ask`: `question` (an id, unique per instance), `code`, `expires` + (time), `text` (HTML, ready to send); +- `edit`: `question`, `text`: replace the text of that question and remove + its buttons. The listener forgets the code of the question; +- `notice`: `text`: a new message; +- `reply`: `question`, `text`: a reply to that question, or a new message + when the listener does not know the question. + +A file the listener cannot parse is removed and logged. If Telegram refuses +a message, the listener tries again on the next round, and drops it after +one day with a log line. + +**Inbox** (the listener writes, root reads and removes). One file per tap, +`SEQ.json`, written to a `.tmp-*` name and renamed, at most 1 KiB, with +`{"code": "...", "action": "apply" | "skip"}`. Unknown fields are an error. +Root opens each file through `os.OpenRoot` with `O_NOFOLLOW`, needs a +regular file owned by the listener user, reads at most 1 KiB, and removes the +file before it acts. A bad file is logged and removed. Root removes `.tmp-*` +files older than one minute. + +`pullgate-apply@NAME.path` watches the inbox (`DirectoryNotEmpty=`) and the +auto approval (`PathExists=`), and starts `pullgate apply NAME`. The apply +service has a start limit, so a stuck file cannot start it in a loop. + +## 9. Questions and approvals + +Root keeps its questions in `state.json`: + +``` +{ "id": 7, "code": "…", "sha": "…", "base": "…", "asked": time, + "expires": time, "open": true } +``` + +`base` is the applied SHA when the question was asked. At most one +question is open. A superseded question stays in the list (`"open": false`) +until it expires, so that a tap that the listener took before the close +still counts (rule 2). The listener forgets a code when it handles the +`edit` that closes the question, so it cannot take a tap for it after that. +Every list entry is removed when it is answered or expires. + +**The listener** calls `deleteWebhook` at start and then `getUpdates` with +`allowed_updates = ["callback_query"]`. It accepts a tap only when all of +these hold, else it answers "This question is closed." and writes nothing: + +- `from.id` is `owner_id`, and `message.chat.id` is `chat_id`; +- the data is `a:CODE` or `s:CODE`, and CODE is a code that it holds; +- the message ID is the message ID of that question; +- the message was not edited (no `edit_date`), and its text is the text + that Telegram gave back when the listener sent it (a SHA-256 of it is + kept). So a token thief who edits the text above real buttons gets no + tap counted (THREAT-MODEL.md T1); +- the question has not expired by the listener's clock; +- the question has no tap yet. After the first tap the listener forgets the + code, so a second tap does nothing. + +Then it writes the approval, edits the question ("Apply tapped. Waiting for +the host." or "Skipped."), and answers the tap. + +**Root** (`pullgate apply NAME`) takes the lock (with a wait). If the pause +file exists or `mode = "off"`, it removes the approvals, replies "ignored: +the instance is paused" (or off) to each question it knows, and exits. +Else it reads the approvals in name order. For each one: + +1. find the question with that code in its own state, with a constant-time + compare. No match: log and ignore. +2. check `asked <= now < expires` by its own clock. Else: drop the question, + reply "expired", ignore. +3. remove the question from its state (synced), so the code works once. +4. `skip`: mark the SHA skipped, reply "skipped", next approval. +5. `apply`: take the SHA **from its own state**, never from the approval. + Check again that the SHA descends from the applied SHA (unless + `allow_older`, or there is no applied SHA). Else reply "refused" and + ignore. Then apply it (section 10). + +`pullgate apply` does at most one apply. Approvals after it stay in the +inbox for the next start. After an apply, every open question whose `base` +is no longer the applied SHA is closed ("the applied commit changed"), and +its SHA mark is cleared, so the next run asks again with a correct summary. + +## 10. The apply + +The steps, with the state synced to disk at each arrow: + +1. Write `in_progress = {phase: "apply", sha, old_sha}` → +2. Export fresh trees (section 6). Run `apply` as root in the tree of the + SHA (environment in section 11). Then `health`, if it is set. +3. Both succeed: the applied SHA becomes this SHA, `refs/pullgate/applied` + moves, `in_progress` and the held SHA are cleared, all marks of older + SHAs are dropped → report "applied". +4. One fails: count a failed try for this SHA →. Then by `on_failure`: + - `rollback`, with an applied SHA: write `in_progress = {phase: + "rollback", sha, old_sha}` →. Run `apply` with the last good SHA, then + `health`. If that works, clear `in_progress` → and report "failed, + rolled back to OLD". If it fails too, write the pause file, clear + `in_progress` → and report "failed, the rollback failed too, the + instance is paused". With no applied SHA there is nothing to roll back + to: hold the SHA, as with `pause`. + - `pause`: do not roll back and do not write the pause file. The SHA + becomes the held SHA. Clear `in_progress` →. It is not tried again, + every report and `pullgate status` say that the last apply failed, and + a **newer** commit is still asked, with the line "The last apply (SHA) + failed." at the top. So the owner can fix it forward with a new commit. + The applied SHA does not change after a failure. State moves forward + only after success. + +**Tries.** Every try needs a new question and a new tap (in `auto` mode, a +new run). With `rollback`, a SHA with fewer than `max_failed_tries` failed +tries is asked again on the next run; with `max_failed_tries` failed tries +it is not asked again until a new commit (or `--ask-again`). With `pause`, +a failed SHA is held at once and the count does not matter. + +**A crash** leaves `in_progress` in the state. The next run or apply cannot +know what happened on the host. It writes the pause file, marks the SHA +failed and reports "the apply (or rollback) of SHA was cut off; check the +host, then run `pullgate status NAME --resume`". + +**Changes to the gate.** An approved commit may change the gate itself: the +host config, the units, or the pullgate binary, when the `apply` command +installs them. pullgate reads its config once when a process starts, so a +rollback uses the commands of the process that did the apply. Put the gate +files of the repo in the `watch` list, so the question warns about them. + +## 11. Commands and their environment + +Commands are argv lists. The first word must be an absolute path. No shell. +They run with an empty environment plus: + +- `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin` +- `PULLGATE_INSTANCE`: the instance name +- `PULLGATE_SHA`: the full SHA of the commit +- `PULLGATE_OLD_SHA`: the applied SHA, empty on the first apply +- `PULLGATE_TREE`: the tree of `PULLGATE_SHA`, read-only +- `PULLGATE_OLD_TREE`: the tree of `PULLGATE_OLD_SHA`, read-only, empty on + the first apply +- `PULLGATE_CHANGED_FILES`: the path of a read-only file with the paths + that differ between the two SHAs, each one ended by a NUL byte (all paths + on the first apply). Read it with `xargs -0`. A file, because a list of + paths can be too long for the environment and a path can hold a newline. +- `PULLGATE_FAILED_SHA`: the held SHA, if there is one. The host may be + part way to it, not at `PULLGATE_OLD_SHA`. +- `PULLGATE_ROLLBACK`: `1` during a rollback, else empty. + +**In a rollback**, `PULLGATE_SHA` and `PULLGATE_TREE` are the last good SHA +and its tree; `PULLGATE_OLD_SHA` and `PULLGATE_OLD_TREE` are the SHA that +just failed and its tree; `PULLGATE_CHANGED_FILES` lists the paths that +differ between them. So `apply` must be safe to run again on an older tree. + +Their working directory is `PULLGATE_TREE`. Each has a timeout +(`check_timeout`, `apply_timeout`); on timeout the whole process group is +killed and the command counts as failed. pullgate keeps at most 64 KiB of +their output. The output of `apply` and `health` goes to the journal; the +report shows only the exit status. The output of `check` (its last lines) +and of `summary` goes into Telegram messages, after the cleaning of +section 12. + +**check and summary (rule 3)** run as `check_user`, with its own group and +no other groups. When pullgate runs as root, `check_user` must not be root +(uid 0): pullgate refuses such a config. When pullgate does not run as root +(tests, a trial), it cannot change user, so `check_user` must be the user +that runs it. A process of `check_user` could leave its process group and +live on. So after each `check` and `summary`, root runs `kill -KILL -1` as +`check_user`, which stops every process of that user; and when the run unit +ends, systemd stops everything left in its cgroup. Use one `check_user` per +instance. The run unit's sandbox (read-only system, private `/tmp`, no new +privileges) also applies to them. + +## 12. The message + +The question is HTML (`parse_mode = HTML`), with link previews off: + +``` +pullgate on HOST, instance NAME +⚠ The last apply (SHA) failed. (only when a SHA is held) +⚠ This commit is not a descendant of … (only with allow_older) +Apply this commit? +FULL SHA +First apply: there is no applied commit yet. All N files are listed. +or: Since APPLIED SHA: +⚠ Watched path changed: path +⚠ Symlink out of the tree: path → target +⚠ Submodule skipped: path + +Commits (N): +• subject +Changed files (N): +• path +Summary: +
output of the summary command
+``` + +Text from the commit (subjects, paths, symlink targets, summary output) is +cleaned before it is shown: control and invisible characters become `?` +(newlines stay only in the summary output), each line is cut to 200 +characters, and then it is HTML-escaped. At most 50 commit subjects are +read. + +The message must fit one Telegram message (4096 characters). pullgate cuts +it to 3800 characters, counted on the escaped text in UTF-16 units: the head +(host, instance, SHA, the warnings) always stays, and when lines are left +out the last line says how many ("… 120 more lines left out"). The cut is on +whole lines, so it never splits an HTML tag or entity. The `
` block is
+closed after a cut.
+
+## 13. Modes, limits, status
+
+- `ask` (the default): as above.
+- `auto`: no question. `pullgate run` records the question in its state and
+  writes its code to `/var/lib/pullgate/NAME/auto-approval` (root-owned,
+  0600). The path unit starts `pullgate apply`, which handles it like an
+  approval from the inbox, then removes it, and reports. The apply needs
+  the same checks (code, time, forward only). For development hosts.
+- `off`: `pullgate run` and `pullgate apply` do nothing.
+
+`pullgate status NAME` prints the mode, the applied SHA, the open question,
+the held SHA, the pause file and an apply in progress. Flags:
+
+- `--ask-again`: clear the marks of the last fetched tip (expired, skipped,
+  check failed, refused, failed, held), so the next run asks again;
+- `--pause`: write the pause file;
+- `--resume`: remove the pause file and clear an apply in progress.
+
+The listener (`pullgate listen --config /etc/pullgate/listener.toml`):
+
+```toml
+token_file = "/etc/pullgate/bot-token"   # or $CREDENTIALS_DIRECTORY/bot-token
+owner_id = 123456789                     # the Telegram user ID of the owner
+chat_id = 123456789                      # the chat (the private chat with the owner)
+instances = ["config-repo", "playbooks"]
+spool_dir = "/var/spool/pullgate"        # default
+state_file = "/var/lib/pullgate-listener/state.json"
+api_url = "https://api.telegram.org"     # only tests change it
+```
+
+Several instances share one listener when they share one bot: two
+`getUpdates` loops on one token conflict.
+
+All processes log with `log/slog` to stderr; the units set
+`SyslogIdentifier=pullgate`, so each step is in the journal. The bot token,
+the deploy key and the code never appear in a log line or an error.
+
+## 14. Tests
+
+Each rule and each limit has a test. The tests use a fake Telegram server
+(`net/http/httptest`) and a local bare git repo as the remote. They need
+`git`. On CI, a missing `git` is a failure, not a skip.
+
+The end-to-end test (`test/e2e`, build tag `e2e`) builds the binary, makes a
+bare repo with two commits, runs `pullgate run`, the listener against the
+fake Telegram server, a tap, `pullgate apply`, and checks that the second
+commit was applied.
+
+## 15. Not in version 0.1
+
+- Self-update of pullgate.
+- Signed commits (`git verify-commit`).
+- A web UI.
diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md
new file mode 100644
index 0000000..21a6f84
--- /dev/null
+++ b/THREAT-MODEL.md
@@ -0,0 +1,298 @@
+# pullgate threat model
+
+Status: accepted for version 0.1 on 2026-11-11.
+
+This file says what pullgate protects, from whom, and where it stops. Read
+[DESIGN.md](DESIGN.md) first for the words and the flows.
+
+## 1. The problem in one paragraph
+
+A host that pulls its own config from a git repo changes whenever someone
+pushes to that repo. Whoever can push (a person, a CI job, a stolen key)
+can change the host, often as root. pullgate puts a person between the push
+and the change: the host applies one exact commit only after its owner taps
+Apply on a question that names that commit, and the rules of that gate live
+on the host, out of reach of the repo.
+
+## 2. What we protect
+
+| asset | where it lives |
+|---|---|
+| the host itself (root) | the host |
+| the gate: the instance config, the listener config, the units, the binary | `/etc/pullgate`, `/etc/systemd/system`, the binary path |
+| the state: applied SHA, open questions, failed marks | `/var/lib/pullgate/NAME/state.json` |
+| the deploy key (read-only) | `/etc/pullgate` |
+| the bot token | the listener's token file or systemd credential |
+| the approval decision | Telegram, the listener, the state |
+
+## 3. Who we trust, and how much
+
+| actor | trust |
+|---|---|
+| the owner (the person who taps) | Trusted. Their judgment is the check. |
+| the owner's Telegram account and phone | Trusted. Anyone who can use this account can approve. |
+| Telegram's servers | Trusted to deliver messages and to say truthfully who tapped. They see the question text: SHAs, commit subjects, file names and the summary output. |
+| root on the host | Fully trusted. |
+| the listener process and its user | Trusted only to pass on the owner's taps. If it is taken over, it can approve an open question without the owner (T2). It can never choose the SHA. |
+| `check_user` and the `check`/`summary` commands | Not trusted with root. They read hostile data (T3). |
+| the git server and everyone who can push | **Not trusted.** A commit may be hostile. |
+| the network | Not trusted. SSH with a pinned host key protects the fetch. |
+| other local users | Not trusted. |
+| the `apply` and `health` commands | Trusted: the owner wrote them. They run as root on the approved tree. |
+
+## 4. What pullgate promises
+
+1. **No change without a tap.** In `ask` mode, root runs `apply` only for a
+   SHA whose question the owner approved (or that a taken-over listener
+   approved, T2).
+2. **The SHA is root's own.** The applied SHA is the one root put in the
+   question. Nothing outside root's state can choose it.
+3. **No code from a new commit runs before the tap, and never as root.**
+4. **Forward only**, unless the host config says otherwise.
+5. **The gate is not in the repo.** No commit can change who approves, what
+   runs, or what is watched, except by an approved apply that installs it
+   (T5).
+
+## 5. Threats
+
+Each threat says what an attacker can try, what stops it, and what is left.
+
+### T1. A stolen bot token
+
+*Attack.* Someone gets the bot token. They can call the Bot API as the bot:
+read updates, send messages, edit them.
+
+*Defense.* A token cannot make a tap from the owner's user ID; Telegram signs
+nothing, but it reports the real sender of a `callback_query`, and the
+listener checks `from.id` and `chat.id`. A thief who runs their own
+`getUpdates` steals the updates from the listener (two pollers conflict),
+so taps can get lost: lost taps deny, they do not approve. The thief can
+send a fake question to the owner, with buttons whose codes the listener
+does not hold; a tap on it does nothing, because the listener holds the
+only list of codes, and root checks the code against its own state. The
+thief can also read new taps of the owner (the code of an open question)
+but a code alone is useless without write access to the inbox.
+The thief can also edit the text of a real question, so that harmless text
+sits above real buttons for a hostile SHA. The listener counts a tap only on
+a message that was never edited, whose text is the text Telegram gave back
+when the listener sent it (DESIGN.md section 9).
+
+*Left.* The thief can show the owner false text (a fake "applied"
+message), can hide questions, and can see the question text. Keep the
+token in a file only the listener user can read, or a systemd credential.
+Change it with BotFather when in doubt.
+
+### T2. A compromised listener
+
+*Attack.* An attacker runs code as the listener user.
+
+*Defense.* The listener user can write only to the inboxes and the outboxes.
+An approval holds a code; root looks the code up in its own state, so the
+listener cannot name a SHA, cannot approve a commit that root did not ask
+about, cannot pass the time limit, and cannot replay a used code. Root reads
+inbox files with `O_NOFOLLOW`, caps their size, needs the listener as owner,
+and rejects unknown fields. The forward-only rule still holds. The listener
+user can write in the outbox and the inbox. Root never follows a path there:
+the spool directories above them are root-owned, root opens them with
+`os.OpenRoot`, and creates files with `O_CREAT|O_EXCL|O_NOFOLLOW` under a
+random name. So a symlink that the listener plants cannot make root write
+or change a file elsewhere.
+
+*Left.* It can approve any open question (or a superseded one that has not
+expired) without the owner, and it can hide or fake messages. So the
+attacker still needs a hostile commit in the repo **and** the listener.
+Run the listener as its own user, with the hardened unit.
+
+### T3. A hostile commit
+
+*Attack.* Someone who can push writes a commit made to hurt the host before
+or during the review.
+
+- **Its content.** Before the tap, no file of the commit runs. git only
+  reads objects. `check` and `summary` read files as data, as `check_user`
+  (not root), in a read-only tree, inside the run unit's sandbox. A parser
+  bug in them hits only `check_user`. They have a timeout and an output cap.
+  A process of `check_user` that leaves its process group to fake a later
+  check or summary is stopped with `kill -KILL -1` as `check_user` after
+  each command, and by systemd when the run unit ends. Use one `check_user`
+  per instance.
+- **A tree that changed.** Trees are written to a temporary name and renamed
+  only when complete. Each process exports its own fresh trees and removes
+  them at the end; `apply` never runs on a tree that a check, an earlier
+  apply, or a crash left behind.
+- **File names.** Each path part is checked: no `..`, no `.git`, no empty
+  part, no NUL. Names with control or invisible characters, or with HTML,
+  are cleaned and escaped before they are shown, so a name cannot fake a
+  line of the question.
+- **Commit subjects and summary output.** The same cleaning; HTML-escaped,
+  each line capped. The head of the question (host, instance, SHA, the
+  warnings) always comes first, before any text from the commit.
+- **Symlinks.** They are written as symlinks and never followed by
+  pullgate. The tree is written with `O_NOFOLLOW|O_EXCL` into directories
+  that pullgate made itself, so a symlink cannot make pullgate write
+  outside the tree. A repeated name, or a path below a file or symlink,
+  stops the export; git checks the objects on fetch (`transfer.fsckObjects`).
+  A symlink whose target is absolute or holds `..` gets a warning in the
+  head of the question, so the owner sees it before root's `apply` may
+  follow it; `refuse_symlinks = true` refuses such a commit. A command that
+  reads the tree must not follow symlinks blindly (the docs say so).
+- **Large trees.** `max_files` and `max_tree_bytes` stop the export. The
+  question has a fixed size. git output is capped.
+- **`.gitattributes` filters.** pullgate never checks out and never runs
+  `git archive`; it writes blobs itself, so no `filter`, `textconv`,
+  `export-subst` or `export-ignore` runs. git runs without system and
+  global config, so no filter is defined anyway.
+- **Submodules.** Not fetched, not written (`--no-recurse-submodules`, mode
+  160000 is skipped), listed as a warning.
+- **LFS.** Not used. An LFS pointer file is written as the small text file
+  it is.
+- **A hostile commit that the owner approves.** The apply then runs as root
+  on purpose. pullgate cannot stop a bad change that the owner approves; it
+  makes sure the owner sees the full SHA, the subjects, the changed files,
+  and a warning for each watched path.
+
+### T4. Root runs git where another user can write
+
+*Attack.* If another user can write the git directory, they can set
+`core.fsmonitor`, hooks, or `core.sshCommand` in `config`, and git runs
+it as root.
+
+*Defense.* Rule 6: root owns the clone in a root-only directory, checks the
+git directory, all its contents and all parents before every git command,
+and refuses on any problem. git runs with `core.hooksPath=/dev/null`,
+`core.fsmonitor=false`, no system or global config, and an empty
+environment.
+
+### T5. An approved apply that changes the gate itself
+
+*Attack.* The repo holds the instance config, a unit, or the binary, and
+`apply` installs them. A commit that weakens the gate (`mode = "auto"`, a
+new owner ID, no watch list) is approved by mistake.
+
+*Defense.* pullgate cannot know what `apply` installs. It reads its config
+once per process, so the running apply and its rollback use the gate of
+the process that started them. The owner should keep the gate files out of
+the repo, or list them in `watch`, so the question shows "⚠ Watched path
+changed" for them. The listener's owner ID and chat ID are in a separate
+file that `apply` should not touch.
+
+*A rollback after such an apply.* If the new gate fails `health`, the
+rollback runs the **old** apply on the old tree, with the commands of the
+current process (the old gate). So a rollback puts the old gate files back
+when `apply` installs them. If the new gate did break pullgate itself (for
+example a bad binary), the next run fails to start and the owner sees the
+failed unit; pullgate does not try to repair itself (self-update is not in
+0.1).
+
+*Left.* An approved commit can change everything. This is the price of
+having the host manage itself.
+
+### T6. A rollback that fails
+
+*Attack or accident.* `apply` fails, and running it again on the old tree
+fails too. The host may be half changed.
+
+*Defense.* With `on_failure = "rollback"`, a failed rollback writes the pause
+file and reports it. Nothing more runs until the owner looks and runs
+`pullgate status NAME --resume`. With `on_failure = "pause"` there is no
+rollback: the failed SHA is held, and the owner can fix it forward. The
+applied SHA does not change after a failure.
+
+### T7. A force push or a rewritten branch
+
+*Attack.* The branch is moved to a commit that does not descend from the
+applied SHA, maybe to undo a fix or to hide history.
+
+*Defense.* Forward only: the run refuses the tip, sends one notice, and marks
+the SHA refused. Root checks it again at apply time. Only
+`allow_older = true` in the host config allows it, and then the question
+has a warning line.
+
+### T8. An old commit offered again
+
+*Attack.* The branch is set back to an older commit that was skipped,
+failed, or was applied earlier (a downgrade).
+
+*Defense.* An ancestor of the applied SHA is refused (T7). A SHA that was
+skipped, failed its check, failed its apply, or whose question expired, is
+not asked again unless `--ask-again` is used. The state keeps these marks.
+
+### T9. A lost or stale approval
+
+*Attack or accident.* A tap is lost; or a tap arrives late; or a tap is
+replayed; or an old message is tapped.
+
+*Defense.* A lost tap means no apply (fail closed); the question expires and
+the SHA waits for a new commit or `--ask-again`. The listener forgets a code
+after the first tap and after the question is closed, so a second tap, or a
+tap on a closed or expired question, writes nothing. Root removes a question
+from its state before it acts, so a replayed approval finds no question.
+Root checks the time limit itself. A tap on a superseded question that the
+listener took before it handled the close still applies the old SHA
+(rule 2); the forward-only check still holds then.
+
+### T10. A crash between apply and the state write
+
+*Accident.* Power is lost while `apply` runs, or just after it, before the
+state is written.
+
+*Defense.* Root syncs `in_progress` to disk before it starts `apply`. On the
+next start, `in_progress` means "unknown result": pullgate writes the pause
+file, marks the SHA failed, and reports. It does not guess. The state is
+written to a temporary file, synced, and renamed, so it is never half
+written.
+
+### T11. A wrong clock
+
+*Accident or attack.* The host clock jumps forward or back.
+
+*Defense.* Time limits are checked by root with its own clock against times
+it recorded itself: an approval counts only when `asked <= now < expires`.
+A clock that goes back before `asked` denies. A clock that jumps forward
+expires questions early: this denies too. The listener checks expiry with its
+own clock as well. Timeouts of commands use the monotonic clock.
+
+*Left.* A clock that is set far back while a question is open can keep that
+question valid longer than `approval_ttl`. The code still works only once.
+
+### T12. A replayed or forged inbox file
+
+*Attack.* A local user, or the listener, puts files in the inbox.
+
+*Defense.* Only the listener user can write the inbox. Root needs the
+listener as the file owner, a regular file, at most 1 KiB, valid JSON
+without unknown fields, and a code that matches its state. A bad file is
+removed and logged. The path unit then has nothing left and stops.
+
+### T13. A hostile git server or network
+
+*Attack.* A fake server, or a server that sends huge or broken data.
+
+*Defense.* SSH with `StrictHostKeyChecking=yes` and a pinned known hosts file
+from the host config; a read-only deploy key; no other protocols. git has
+a timeout and an output cap. The tree export has caps.
+
+### T14. Weak gate files
+
+*Attack.* A local user can write the config, the deploy key, the known
+hosts file, the program of a command, or a directory above one of them.
+
+*Defense.* pullgate refuses to start then (DESIGN.md section 4). A local
+repo URL must pass the same check as the clone, because root runs
+`git-upload-pack` in it. The listener checks its own config and token file.
+
+### T15. Too many questions
+
+*Attack.* Someone pushes many commits to tire the owner into tapping Apply.
+
+*Defense.* At most one open question per instance; a newer tip replaces it.
+`questions_per_day` caps the questions. A SHA is asked once.
+
+## 6. Out of scope
+
+- An attacker who is root on the host.
+- A program that a command runs and that pullgate did not check (for
+  example a tool that `apply` calls by name). The owner writes `apply`.
+- An attacker who controls the owner's Telegram account.
+- A bad change that the owner approves on purpose.
+- Signed commits (planned later).
diff --git a/cmd/pullgate/main.go b/cmd/pullgate/main.go
new file mode 100644
index 0000000..03ddd87
--- /dev/null
+++ b/cmd/pullgate/main.go
@@ -0,0 +1,20 @@
+// Command pullgate pulls a git repo, asks the owner on Telegram to apply one
+// exact commit, and applies it as root. See DESIGN.md.
+package main
+
+import (
+	"fmt"
+	"os"
+)
+
+// version is set at build time with -ldflags "-X main.version=...".
+var version = "dev"
+
+func main() {
+	if len(os.Args) == 2 && os.Args[1] == "version" {
+		fmt.Println("pullgate", version)
+		return
+	}
+	fmt.Fprintln(os.Stderr, `pullgate: give a command: version; see DESIGN.md (exit 64)`)
+	os.Exit(64)
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..183dec8
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module github.com/code6x/pullgate
+
+go 1.26.10