diff --git a/.gitignore b/.gitignore index 01eea44..619dff1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ ssh_host_ed25519_key # local config; copy config/forge.example.toml /config/forge.toml +.~lock.*# diff --git a/README.md b/README.md index e9de531..aeaa2d7 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,26 @@ # forge -forge is a self-hosted git forge written in Rust. It is a working name, and the project is not yet released. +forge is a self-hosted git forge. You run it on your own server, so your code stays on machines you control and no third-party service sits in the middle. It ships as one binary, `forge`, which serves the web UI, git over HTTPS, and git over SSH. Repositories are plain bare git repositories on disk, and account data lives in one SQLite database. -It runs as a single process (`forge`) that serves the web UI, git over HTTPS (smart HTTP), and git over SSH. Repositories are plain bare git repositories on disk. Account and repo metadata live in a SQLite/Turso database. +Try the live instance at https://git.tahinli.com. -## Status +forge is a working name, and it is not released yet. -forge is at **Milestone 2** ("repo browsing and raw files"). It currently provides: +## Features -- local accounts (argon2id passwords), with the first user created as admin -- sessions, CSRF protection on every POST, and a `__Host-` session cookie -- SSH public keys and personal access tokens (`forge_...`) -- creating repos, with public or private visibility, collaborators, and an archive flag -- clone and push over HTTPS and SSH -- basic branch protection: the default branch cannot be deleted or force-pushed, and archived repos reject pushes -- repo browsing: the repo home page with the rendered README, directory listings with the last commit per entry, file views with syntax highlighting and `#L12` line anchors, Markdown rendering with a source toggle, commit history (paginated), commit views with diffs, branch and tag lists, and `.tar.gz` / `.zip` archives -- raw files served from a separate user-content origin (see [Raw user content](#raw-user-content)) - -Not yet: issues, pull requests, webhooks, mirrors, CI. See [Roadmap](#roadmap). - -## Requirements - -- Rust stable, edition 2024 -- git 2.38 or newer (boot refuses to start with an older git) +- **Accounts:** local accounts with argon2id passwords, two-factor login (TOTP) with recovery codes, SSH keys, and personal access tokens. +- **Repositories:** public or private repos, collaborators, archiving, and a trash for deleted repos. +- **Git:** clone and push over HTTPS and SSH. The default branch cannot be deleted or force-pushed, and archived repos reject pushes. +- **Browsing:** rendered READMEs, syntax-highlighted files with line links, Markdown source view, commit history and diffs, branches and tags, and `.tar.gz` or `.zip` downloads. +- **Collaboration:** issues, pull requests with reviews, notifications, and releases. +- **Automation:** webhooks, push mirrors, replication to a standby, and CI runners. +- **Large files:** Git LFS. +- **Backups:** scheduled backup sets with verification and restore. ## Quick start +You need Rust (stable, edition 2024) and git 2.38 or newer. forge refuses to start with an older git. + 1. Copy the example config. forge reads `config/forge.toml` by default. ```sh @@ -38,13 +33,13 @@ Not yet: issues, pull requests, webhooks, mirrors, CI. See [Roadmap](#roadmap). cargo run -p forge-web ``` -3. Create the admin account. Either open http://127.0.0.1:7660/setup (it works only while there are zero users), or use the CLI: +3. Open http://127.0.0.1:7660/setup and create the admin account (its password must be at least 12 characters). This page works only while there are no users. You can also create the account from the shell: ```sh - cargo run -p forge-web -- admin create-user --admin + cargo run -p forge-web -- admin create-user tahinli --admin ``` - The CLI reads the password from `FORGE_PASSWORD` if set, or prompts for it twice. Passwords must be at least 12 characters. The first user is always an admin, even without `--admin`. + The command reads the password from `FORGE_PASSWORD` if it is set, or asks for it twice. Passwords must be at least 12 characters. 4. Add an SSH key at `/settings/keys`. Use an ed25519 key: @@ -52,114 +47,31 @@ Not yet: issues, pull requests, webhooks, mirrors, CI. See [Roadmap](#roadmap). ssh-keygen -t ed25519 ``` - Paste the contents of the `.pub` file. RSA keys are rejected with a message asking for ed25519. The reason is that `ssh-rsa` keys sign with SHA-1, and forge disables SHA-1 signatures. ECDSA and security-key (`sk-`) variants are also accepted by the form. - -5. To change only the capitalization of your username (for example `tahinli` to `Tahinli`), open `/settings/profile`. Any other change is refused. The instance operator can do the same from a shell with `cargo run -p forge-web -- admin set-username `. + RSA keys are rejected, because forge turns off SHA-1 signatures. -6. Create an access token at `/settings/tokens`. The token starts with `forge_` and is shown once. Store it somewhere safe. +5. Create a token at `/settings/tokens` for HTTPS pushes. It starts with `forge_` and is shown only once. -7. Account security lives at `/settings/security`: - - **Password:** change it with the current password. The new one needs 10 to 1024 characters. Your other sessions are signed out; the one you are using stays signed in. Wrong current passwords count toward the same per-user login limit as failed logins. - - **Email:** change it with the current password. The address must contain one `@`, have no spaces, and be at most 254 characters. - - **Two-factor authentication (TOTP):** click "Enable 2FA", add the secret or `otpauth://` link to an authenticator app, and confirm with a 6-digit code. Ten single-use recovery codes are then shown once, so save them. Turning 2FA off needs the password and a code. Regenerating recovery codes needs a code. Codes are TOTP (RFC 6238, SHA-1, 6 digits, 30-second steps), and a code from one step either side of the current time is accepted. Each code works only once. With 2FA on, a correct password leads to `/login/2fa`, which asks for a code or a recovery code. The pending login lasts 5 minutes. Each user gets 10 second-factor attempts per 15 minutes. - - **Git over HTTPS is unaffected by 2FA.** It authenticates with access tokens (step 6), not with passwords or TOTP codes. Revoke a token at `/settings/tokens` if it leaks. - -7. Create a repo at `/new`, then push over either transport: +6. Create a repo at `/new`, then push to it: ```sh # SSH - git remote add origin ssh://git@127.0.0.1:2222//.git + git remote add origin ssh://git@127.0.0.1:2222/tahinli/my-repo.git git push -u origin main - # HTTPS: username and token as the password - git remote add origin http://127.0.0.1:7660//.git + # HTTPS: use your username, and the token as the password + git remote add origin http://127.0.0.1:7660/tahinli/my-repo.git git push -u origin main ``` -## Configuration - -The file is TOML. Every key in `config/forge.example.toml` is listed below. Paths are relative to the working directory unless absolute. - -| Key | Example value | Meaning | -|---|---|---| -| `database` | `"./data/forge.db"` | SQLite/Turso database file. `admin create-user` creates its parent directory. | -| `data_dir` | `"./data"` | Root for repos, instance key, gitconfig, hooks, and sockets. Created with mode 0700. | -| `listen` | `"127.0.0.1:7660"` | HTTP listen address for the web UI and smart HTTP. | -| `base_url` | `"http://127.0.0.1:7660"` | Public base URL used in links and clone URLs. Set this to your public `https://` URL in production. | -| `user_content_base_url` | `"http://127.0.0.1:7661"` | Separate origin for raw user content. Set it to a different registrable domain in production (see [Raw user content](#raw-user-content)). | -| `user_content_listen` | `"127.0.0.1:7661"` | Address of the listener that serves raw user content. Your reverse proxy forwards the user-content hostname to it. | -| `ssh_listen` | `"0.0.0.0:2222"` | SSH listen address for git over SSH. | -| `ssh_public_host` | `"127.0.0.1"` | Host shown in SSH clone URLs. | -| `ssh_public_port` | `2222` | Port shown in SSH clone URLs. | -| `registration` | `"closed"` | Self-registration policy: `closed`, `invite`, or `open`. Default is `closed`. M1 has no sign-up page, so accounts come from `/setup`, the CLI, or `/admin/users`. | -| `trusted_proxies` | `[]` | Addresses or CIDR networks (for example `["127.0.0.1"]`) whose `X-Forwarded-For` header is trusted. Set it to the address your reverse proxy connects from. Empty means the TCP peer is the client, so a spoofed header cannot change the client IP. Used for login and git throttling. | - -Production config normally lives at `/etc/forge/forge.toml` (see the systemd unit below). - -### Command line and environment - -```text -forge [--config ] [serve | hook | runner ... | admin create-user [--admin] | admin set-username | admin reset-password | admin trash-list | admin trash-purge --older-than-days | admin audit-purge --older-than-days | admin delete-user [--yes] | admin backup --out [--include-key] [--repos-only | --db-only] | admin backup-verify | admin fsck [--full] | admin lfs-gc | admin restore --from --data-dir ] -``` - -- `--config ` sets the config file. Precedence: `--config`, then `FORGE_CONFIG`, then `config/forge.toml`. -- `serve` (the default when no subcommand is given) starts the server. -- `hook ` is called by git hook shims. You do not run it by hand. -- `admin create-user [--admin]` creates a user from the CLI. -- `admin set-username ` changes only the capitalization of a user's username (`current` matches any case). Example: `forge admin set-username tahinli Tahinli`. -- `admin reset-password ` sets a random 20-character temporary password, prints it once, and signs the user out of every session. Give the password to the user, who should change it at `/settings/security`. Nothing else changes. Use it when a user is locked out of their account. Two-factor settings are not changed, so the user still needs a code. -- `admin trash-list` lists deleted repos in `data_dir/trash`, oldest first, as `\t\t`. -- `admin trash-purge --older-than-days N` permanently removes trash entries deleted at least N days ago. Nothing else is removed, and this cannot be undone. -- `FORGE_PASSWORD` supplies the password for `admin create-user` without a prompt. -- `RUST_LOG` sets the log filter (default `info`). Logs go to stderr. -- `GET /healthz` returns `ok `. +Account settings live at `/settings/security`. There you can change your password or email, or turn on two-factor login (save the ten recovery codes it shows). Git over HTTPS uses access tokens, not your password or 2FA codes, so revoke a token at `/settings/tokens` if it leaks. You can change only the capitalization of your username, at `/settings/profile`. -## Data layout +## Deploy on a server -Everything under `data_dir`: +Run forge behind a TLS reverse proxy for any use beyond localhost. The session cookie is marked `Secure`, so logging in over plain HTTP will not work outside localhost. -| Path | Purpose | -|---|---| -| `forge.db`, `forge.db-wal`, `forge.db-shm` | Metadata database (users, sessions, keys, tokens, repos). Sits next to `database` in the example config. | -| `forge.key` | Instance key. Encrypts sealed values. Created on first boot. | -| `ssh_host_ed25519_key` | SSH host key. Created on first boot. | -| `gitconfig` | Managed gitconfig written at boot. Do not edit by hand, it is rewritten at boot. | -| `hooks/` | `pre-receive` and `post-receive` shims that run `forge hook `. Rewritten at boot. | -| `repos/ab/cd/.git` | Bare repositories. `` is the lowercased ULID; the path does not depend on the repo name. | -| `internal.sock` | Unix socket used by git hooks to reach the server. Mode 0600. Removed on shutdown. | -| `trash/-.git` | Repos deleted from the settings page (`/{owner}/{repo}/settings`). Each is a plain bare repository, moved here by a rename. The database rows are gone, so the repo no longer appears in forge. | +The easiest way is a system service, using the unit in `deploy/forge.service`. You can also run forge as a dedicated user with a systemd user service. Then enable linger (`sudo loginctl enable-linger forge`) so it keeps running after logout. -### Recovering a deleted repo - -A deleted repo is not erased at once. Its bare directory is moved to `data_dir/trash/`, and only `admin trash-purge` removes it. To recover it, list the trash with `forge admin trash-list` and clone from the directory, which works without the server: - -```sh -git clone --mirror /var/lib/forge/trash/-.git recovered.git -``` - -The clone restores all branches and tags. The owner, visibility, description and collaborators are not restored, so re-create the repo under the same name and push the mirror to it with `git push --mirror`. - -### Backups - -See [`docs/backup.md`](docs/backup.md) for what a backup set contains, how to ship it off-site, how to restore, and the quarterly restore drill. - -- **`forge.key` must be backed up separately and stored safely, offline.** Without it, sealed values cannot be decrypted, and they are lost. Keep it out of the same backup set as the database if you can. -- **Never copy a live `forge.db`** (or its `-wal`/`-shm` files) with `cp` or `rsync`. Take a consistent snapshot with `VACUUM INTO`, for example from the `sqlite3` shell while forge is running: - - ```sql - VACUUM INTO '/var/backups/forge/forge-2026-10-15.db'; - ``` - -- **Repositories**: do not copy bare repos while pushes are in progress. Use `git bundle create --all` or `git push --mirror` to a copy. -- **Unix socket path length**: `data_dir/internal.sock` must be shorter than 108 bytes, the unix socket path limit. Boot fails with an error otherwise. Choose a short `data_dir` (for example `/var/lib/forge`). - -## Deployment - -### systemd - -`deploy/forge.service` runs `/usr/local/bin/forge serve` as a dedicated `forge` user, with `FORGE_CONFIG=/etc/forge/forge.toml`, working directory `/var/lib/forge`, and a hardened sandbox (`ProtectSystem=strict`, `/var/lib/forge` and, if present, `/var/backups/forge` writable, no capabilities, `UMask=0077`). - -Typical setup: +System service setup: ```sh sudo useradd --system --home /var/lib/forge --shell /usr/sbin/nologin forge @@ -170,66 +82,30 @@ sudo install -m 0644 deploy/forge.service /etc/systemd/system/forge.service sudo systemctl daemon-reload && sudo systemctl enable forge ``` -Edit `/etc/forge/forge.toml` before starting: +Before you start it, edit `/etc/forge/forge.toml`: -- `base_url`: public `https://` URL. -- `user_content_base_url`: a separate registrable domain, not a subdomain of `base_url`. -- `ssh_public_host` and `ssh_public_port`: public hostname and port. +- `base_url`: your public `https://` URL. +- `user_content_base_url`: a separate domain, not a subdomain of `base_url` (see below). +- `ssh_public_host` and `ssh_public_port`: your public host name and port. - `database` and `data_dir`: absolute paths under `/var/lib/forge`. -- `trusted_proxies = ["127.0.0.1"]` when the reverse proxy runs on this host. Otherwise every client shares the proxy's IP for login and git throttling. -- `[backup] dir`: under `/var/lib/forge` or `/var/backups/forge`. The unit makes only those writable. Create the latter with `sudo install -d -o forge -g forge -m 0700 /var/backups/forge`. +- `trusted_proxies = ["127.0.0.1"]` if the reverse proxy runs on the same host. Without this, every client shares the proxy's IP for login throttling. +- `[backup] dir`: under `/var/lib/forge` or `/var/backups/forge`. -Create the admin before starting. `/setup` lets the first visitor claim the admin account while there are no users, so create the admin before the reverse proxy exposes the site. +Create the admin account (password at least 12 characters) before the reverse proxy makes the site public. `/setup` lets the first visitor claim the admin account while there are no users. ```sh -sudo -u forge FORGE_CONFIG=/etc/forge/forge.toml /usr/local/bin/forge admin create-user --admin +sudo -u forge FORGE_CONFIG=/etc/forge/forge.toml /usr/local/bin/forge admin create-user tahinli --admin sudo systemctl start forge ``` -Open the SSH port (2222 by default) in the firewall. - -### Reverse proxy and TLS - -Run forge behind a TLS reverse proxy for any non-localhost use. The session cookie is named `__Host-forge_session` and is marked `Secure`, so browsers send it only over HTTPS. Logging in over plain HTTP outside localhost will not work. Set `base_url` to the public HTTPS URL. - -Git routes need a proxy that does not buffer or time out early. The example below targets [Ferron](https://ferron.sh) 3.0.0-rc.7, the newest release found (a pre-release; the latest stable, 2.8.1, was not checked against this config). Ferron uses its own `ferron.conf` format, not KDL. - -- Buffering: `buffer_request` and `buffer_response` are off by default. The example sets both to `0` so they stay off, because git smart HTTP streams packs in both directions. -- Timeouts: `connection_timeout` (default 2s) and `idle_timeout` (default 60s) are per upstream. The example raises `idle_timeout` to `3600s`, because `git upload-pack` can stay silent while it builds a pack. Ferron's proxy docs list no total-request timeout, so there is no separate read/send timeout to raise. -- Body size: Ferron's docs describe no request body size limit, so there is nothing to disable. Do not add one on git paths (`///git-receive-pack`, `git-upload-pack`). -- Forwarded headers: Ferron sets `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Real-IP` and `Forwarded` itself and keeps the incoming `Host`, so the example adds no header lines. -- SSH: port 2222 is not proxied. Ferron handles HTTP(S) only, so forge serves SSH directly on `ssh_listen`. Open that port on the host. - -### Brute-force throttling - -Login and git HTTP authentication are throttled in memory, per process, over a 15 minute sliding window: - -- Login: 10 failed attempts per username, and 30 per client IP. A throttled attempt gets HTTP 429 with the message "Too many attempts. Try again later.", and the password is not checked. A successful login clears that username's counter. -- Git HTTP (Basic auth with a token): 30 failed attempts per client IP. The next request gets HTTP 429 with `Retry-After`. Anonymous requests and successful logins are not counted. -- The client IP is the TCP peer, unless the peer is in `trusted_proxies`. Then it is the right-most `X-Forwarded-For` address that is not a trusted proxy. IPv6 addresses are counted per /64. -- Throttling events are logged at `warn` with the IP and the folded username. Counters are lost on restart and are not shared between instances. +Open the SSH port (2222 by default) in your firewall. The reverse proxy does not forward SSH, so forge serves it directly. -### Raw user content +### Reverse proxy -forge runs a third listener, `user_content_listen` (default `127.0.0.1:7661`). It serves only the raw files of repos, on the origin `user_content_base_url`. It has its own explicit routes and does not share the app's router. - -Put it on its own registrable domain in production, for example `usercontent.example.net` next to `forge.example.com`. Browsers treat that as a separate site, so a file a user uploads cannot run script against the app origin. The raw origin is also built to be inert: - -- No cookies are read or set on it, so app sessions never reach it. -- Every response has `Content-Security-Policy: default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox`, `X-Content-Type-Options: nosniff`, and `Referrer-Policy: no-referrer`. -- SVG, HTML, XML and other non-image binaries are sent with `Content-Disposition: attachment`. - -Private repos need a signed link. The app puts a `?token=` on raw links for private repos, and that token is valid for 10 minutes. Public repos need no token. A missing, hidden, or bad token gets 404. - -Example Ferron 3.0.0-rc.7 config (`ferron.conf`) with two hostnames. A bare host block already gets automatic ACME TLS; the `tls` block only sets the account contact: +Git needs a proxy that does not buffer and allows long silent periods, because `git upload-pack` can pause while it builds a pack. This example uses [Ferron](https://ferron.sh) 3.0.0-rc.7, a pre-release. Ferron uses its own `ferron.conf` format. A bare host block gets automatic TLS. ``` forge.example.com { - tls { - provider acme - challenge http-01 - contact admin@example.com - } buffer_request 0 buffer_response 0 proxy { @@ -240,11 +116,6 @@ forge.example.com { } usercontent.example.net { - tls { - provider acme - challenge http-01 - contact admin@example.com - } buffer_request 0 buffer_response 0 proxy { @@ -253,47 +124,121 @@ usercontent.example.net { } ``` -The two hostnames are different registrable domains, so the raw origin is a separate site with no app cookies. +Set `base_url = "https://forge.example.com"` and `user_content_base_url = "https://usercontent.example.net"` to match. Turn off compression on git paths too. forge does not compress responses yet. -With that setup, set `base_url = "https://forge.example.com"` and `user_content_base_url = "https://usercontent.example.net"`. +#### User content domain -### Limits +Raw repo files are served from `user_content_base_url`, which must be a different domain from `base_url` (for example `usercontent.example.net` next to `forge.example.com`). Browsers then treat it as a separate site, so a file a user uploads cannot run script against your app. The raw origin reads no cookies and sends risky file types as downloads. Links to private repo files carry a `?token=` that expires after 10 minutes. -- Blob view: the first 1 MiB of a file is shown. Larger files are truncated, with a link to the raw file. -- Syntax highlighting: skipped for files over 512 KiB or 20,000 lines. Those are shown without highlighting. -- Raw files: up to 8 MiB are read into memory and sent. Larger files are streamed. -- Commit diffs: at most 300 files, 2,000 lines per file, and 20,000 lines in total. Anything past that is cut off with a notice. +### Automatic updates -Compression is currently **off for every route**. Git smart-HTTP responses must not be compressed, and the server cannot yet switch compression off per route, so it is disabled globally (`TODO(M1)` in `boot.rs`). Let the proxy do no compression on git paths either. +forge can update itself. When CI passes on a push to the forge repo, the server swaps in the new binary and restarts. Runners do the same when they are idle. This needs the user units in `deploy/user/`, because the binary lives in `~/bin`. Use `forge` for the server and `ci` for a runner, each a dedicated user with linger enabled. The system unit `deploy/forge.service` is for a root-managed install with the binary in `/usr/local/bin`, which the `forge` user cannot write, so it does not self-update. Use it or the user units, not both. -## Security notes +As the `forge` user, install the server units (the runner host does the same as `ci`, with `forge-runner.service` and `forge-runner-rollback.service`): -From `docs/architecture.md`. These are the properties forge is designed for. Not all are fully implemented in M1. +```sh +install -d ~/bin ~/.config/systemd/user +install -m 0755 target/release/forge ~/bin/forge +install -m 0755 deploy/user/forge-rollback ~/bin/forge-rollback +install -m 0644 deploy/user/forge.service deploy/user/forge-rollback.service ~/.config/systemd/user/ +systemctl --user daemon-reload && systemctl --user enable --now forge.service +``` -- Authorization goes through a single function, `authorize()`. A private repo that the actor cannot see returns 404, so its existence is not revealed. -- Passwords use argon2id. Tokens and session tokens are stored as SHA-256 hashes and compared in constant time. Tokens are shown once and kept out of URLs and logs. -- SSH keys must match exactly. `ssh-rsa` with SHA-1 is disabled, and the SSH server accepts only `GIT_PROTOCOL` from env requests. Handshake and inactivity timeouts apply. -- No shell is used. SSH exec commands are parsed against an allow-list, and git is started with explicit arguments. -- Git runs with `receive.fsckObjects=true`, and hooks are fail-closed: if the internal socket is unreachable, the push is rejected. -- Users cannot write hooks or repo-local config. Submodules are not recursed. -- Run as a dedicated service user, and keep the git binary patched. -- Keep `forge.key` and `data_dir` private. Back up `forge.key` separately. +Turn on updates in `forge.toml`: -## Roadmap +```toml +[self_update] +enabled = true +repo = "Tahinli/forge" +branch = "main" +job = "build" +artifact = "dist_forge" +``` -From `docs/architecture.md` (section 10). +Runners update by default (`auto_update = true` in `runner.toml`). Set it to `false` to pin a runner's binary by hand. -- **M1: clone and push work.** Accounts, SSH keys, tokens, repo create, smart HTTP and SSH, pre-receive policy, minimal UI. -- **M2 (current): repo browsing and raw domain.** Tree, blob, commit and diff views; README rendering; syntax highlighting; raw files on `user_content_base_url`. -- **M3: issues.** Issues, comments, labels, milestones, with permissions through `authorize()`. -- **M4: pull requests.** PR refs, mergeability via `merge-tree`, reviews, merge strategies. -- **M5: webhooks, push mirrors, replication, backups, export.** Including `VACUUM INTO` snapshots, integrity checks, and restore drills. -- **M6: custom CI runner and commit-status API.** Required checks enforced on push as well as PR merge. +If a new binary crashes on start three times within a minute, systemd gives up and runs `forge-rollback`. That script keeps the old binary as `~/bin/forge.prev`, so it puts it back, records the bad build's sha256 in `~/bin/forge.bad`, and starts the unit again. A forge or runner skips any hash listed there, so it will not install the same build again. Check the journal (`journalctl --user -u forge -e`) to see what happened. -## License +Rollback does not undo database migrations. If the new version migrated the database, the old binary runs against the new schema. Take a backup before you rely on updates (see [Data and backups](#data-and-backups)). + +## Configuration + +Settings live in TOML. `config/forge.example.toml` lists every key with comments. Relative paths are relative to the working directory. The keys you are most likely to change: + +| Key | Example | Meaning | +|---|---|---| +| `listen` | `"127.0.0.1:7660"` | Address for the web UI and git over HTTPS. | +| `base_url` | `"https://forge.example.com"` | Public URL used in links and clone addresses. | +| `user_content_base_url` | `"https://usercontent.example.net"` | Public URL of the raw file origin. | +| `user_content_listen` | `"127.0.0.1:7661"` | Address of the raw file listener. | +| `ssh_listen` | `"0.0.0.0:2222"` | Address for git over SSH. | +| `ssh_public_host` / `ssh_public_port` | `"forge.example.com"` / `2222` | Host and port shown in SSH clone addresses. | +| `registration` | `"closed"` | `closed`, `invite`, or `open`. Accounts come from `/setup`, the CLI, or `/admin/users`. | +| `trusted_proxies` | `["127.0.0.1"]` | Proxy addresses whose `X-Forwarded-For` header is trusted. Leave empty if there is no proxy. | + +The config file is `config/forge.toml` by default. Pick another path with `--config` or the `FORGE_CONFIG` variable. + +## Admin commands -forge is licensed under the GNU Affero General Public License, version 3 or later (AGPL-3.0-or-later). +Run `forge admin `, or `cargo run -p forge-web -- admin ` from a checkout. + +| Command | What it does | +|---|---| +| `admin create-user [--admin]` | Create a user. The first user is always an admin. | +| `admin set-username ` | Change only the capitalization of a username. | +| `admin reset-password ` | Set a random temporary password and sign the user out everywhere. | +| `admin delete-user [--yes]` | Delete a user. | +| `admin trash-list` | List deleted repos, oldest first. | +| `admin trash-purge --older-than-days ` | Permanently remove trashed repos older than N days. | +| `admin audit-purge --older-than-days ` | Delete audit log entries older than N days. | +| `admin backup --out [--include-key] [--repos-only \| --db-only]` | Write a backup set. | +| `admin backup-verify ` | Check a backup set. | +| `admin restore --from --data-dir ` | Restore a backup set into a new data directory. | +| `admin fsck [--full]` | Run `git fsck` on every repo and check the database. | +| `admin lfs-gc` | Delete unused LFS objects that are at least a day old. | + +`serve` is the default command. `hook` and `runner` are for git hooks and CI runners. Set `RUST_LOG` to change the log level. `GET /healthz` returns `ok` and the build commit. + +## Data and backups + +Everything lives under `data_dir`: + +| Path | What it is | +|---|---| +| `forge.db` | Metadata: users, sessions, keys, tokens, repos. | +| `forge.key` | Instance key. It encrypts stored secrets. Created on first boot. | +| `ssh_host_ed25519_key` | SSH host key. Created on first boot. | +| `repos/` | Bare repositories. | +| `trash/` | Repos deleted from their settings page, until you purge them. | + +Back up `forge.key` separately, and keep it offline. Without it, encrypted values such as mirror credentials cannot be read again. + +Never copy a live database file with `cp` or `rsync`. Take a consistent copy with `VACUUM INTO`, which is safe while forge runs: + +```sql +VACUUM INTO '/var/backups/forge/forge-2026-10-15.db'; +``` + +For a full backup, use `forge admin backup --out `. See [`docs/backup.md`](docs/backup.md) for what a backup set contains, how to ship it off-site, how to restore, and the quarterly restore drill. + +#### Recovering a deleted repo + +Deleted repos stay in the trash until `admin trash-purge` runs. Find one with `forge admin trash-list`, then clone it with `git clone --mirror recovered.git`. This restores all branches and tags, but not the owner, visibility, description, or collaborators. + +## CI runners + +CI workflows are TOML files in `.forge/ci.toml` in your repo. Jobs run on runners, which are `forge runner` processes on machines you control. The forge never connects to a runner; runners pull jobs over HTTPS. Each job runs in its own rootless sandbox, with its own workspace and a read-only token, and no container tool is needed. See [`docs/ci.md`](docs/ci.md) for the workflow format, the security model, and runner setup. + +## Security + +- Passwords use argon2id. Tokens are stored as SHA-256 hashes. +- Private repos you cannot see return 404, so their existence is not revealed. +- No shell runs for git, and pushes are checked for object integrity. Users cannot add hooks or repo-level git config. +- Login is throttled: 10 failed attempts per username and 30 per IP, over 15 minutes. +- Run forge as a dedicated user, keep the git binary patched, and keep `forge.key` and `data_dir` private. + +## License -### Fonts +forge is free software, licensed under the GNU Affero General Public License, version 3 or later (AGPL-3.0-or-later). -The web UI bundles two fonts, served from the forge origin under `/assets/fonts/`: Figtree (UI) and IBM Plex Mono (code). Both are licensed under the SIL Open Font License 1.1. The license texts are in `style/fonts/` and are also served at `/assets/fonts/Figtree-OFL.txt` and `/assets/fonts/IBMPlexMono-OFL.txt`. Sources, pinned versions and checksums are listed in `style/fonts/README.md`. +The web UI bundles the Figtree and IBM Plex Mono fonts, both under the SIL Open Font License 1.1. Licenses and checksums are in `style/fonts/`. diff --git a/docs/architecture.md b/docs/architecture.md index 6a61e3e..aa1594e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,9 +1,8 @@ # Forge Architecture -Status: milestones 1 and 2 are implemented. Later milestones are outlined here and not built yet. +Status: repo hosting and browsing are implemented. Later features are outlined here and not built yet. "Forge" is a placeholder name. Renaming is a find-and-replace. -Sources: the M1 plan (`~/.claude/plans/purring-prancing-wirth.md`), the interface contract (`docs/m1-interfaces.md`), and the research notes (`docs/research.md`, sections 1-16). Items marked *(unverified)* in the research are not confirmed. --- @@ -27,11 +26,11 @@ Sources: the M1 plan (`~/.claude/plans/purring-prancing-wirth.md`), the interfac | Git smart-HTTP | Routes in Topcoat, backed by the `git` binary | No axum. The git child process streams request and response bodies directly. | | Metadata DB | Turso | Embedded SQLite-compatible store. Holds all metadata. WAL with `synchronous=FULL` (section 8.3). | | Git serving | `git` binary (`upload-pack`, `receive-pack`, merges, blame, verify, maintenance) | Git's own implementation is the only trustworthy server side. | -| Git reads | `gix` in-process | Object, tree, and blob reads, rev-walk, diffs, rename detection, archives (research §7). | +| Git reads | `gix` in-process | Object, tree, and blob reads, rev-walk, diffs, rename detection, archives. | | SSH | russh 0.64.x | Built-in SSH server for git over SSH. No OpenSSH dependency. | | Hooks | `forge hook` subcommand over a unix socket | Hook policy lives in the app, not in files users can edit. | -Not used: `git2` (adds a C dependency, research §7). Dumb HTTP (disabled, research §1). +Not used: `git2` (adds a C dependency). Dumb HTTP (disabled). --- @@ -42,7 +41,7 @@ Cargo workspace at the repo root. Edition 2024, resolver 3. ``` project_git/ Cargo.toml .gitignore config/forge.toml deploy/forge.service style/main.scss - docs/{research.md, architecture.md, m1-interfaces.md} + docs/architecture.md crates/ forge-core/ domain types, store, migrations, config, secret key, authz, names, passwords, tokens, sessions forge-git/ safe git command builder, process spawn and streaming, pkt-line, repo init, managed gitconfig, version check @@ -80,7 +79,7 @@ Store API (`Store`: async, `Clone`, wraps the Turso connection). `open()` sets W ## 4. Data model -### 4.1 Milestone 1 tables (`0001_init.sql`) +### 4.1 Core tables (`0001_init.sql`) Conventions: ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional digits and a `Z` suffix. Booleans are integers 0/1. Foreign keys are enforced. @@ -120,7 +119,7 @@ Conventions: ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional di - `name` TEXT NOT NULL - `token_hash` TEXT NOT NULL UNIQUE (hex sha256; the token is shown once) - `scopes` TEXT NOT NULL (serialized list) -- `expires_at` TEXT NULL (default expiry is 30 days, research §10) +- `expires_at` TEXT NULL (default expiry is 30 days) - `created_at` TEXT NOT NULL, `last_used_at` TEXT NULL **`repos`** @@ -150,24 +149,24 @@ Conventions: ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional di - `protocol` TEXT NOT NULL CHECK (`http` or `ssh`) - `created_at` TEXT NOT NULL -Secrets (`forge.key` is not in the DB). Values sealed with XChaCha20-Poly1305 are stored as `v1:` plus base64(nonce || ciphertext). M1 has no sealed column yet. Mirror credentials and TOTP secrets are the first candidates (M5 and later). +Secrets (`forge.key` is not in the DB). Values sealed with XChaCha20-Poly1305 are stored as `v1:` plus base64(nonce || ciphertext). No column is sealed yet. Mirror credentials and TOTP secrets are the first candidates. ### 4.2 Later tables (outline) -| Table | Milestone | Purpose | -|---|---|---| -| `issues` | M3 | Number per repo, title, body, state, author, timestamps | -| `comments` | M3 | Issue and PR comments, polymorphic by parent, edit history | -| `labels` | M3 | Per-repo labels, plus an `issue_labels` join | -| `milestones` | M3 | Per-repo milestones, due date, state | -| `pulls` | M4 | PR number, base and head refs, head oid, merge state, outdated flag | -| `reviews` | M4 | Reviewer, state (approve, request changes, comment), commit oid | -| `review_comments` | M4 | Commit oid, path, line, side, diff hunk, outdated flag (kept, never deleted) | -| `webhooks` | M5 | Target URL, events, encrypted secret (sealed) | -| `deliveries` | M5 | Delivery id, attempt, status, request and response, retry state | -| `mirrors` | M5 | Pull and push mirrors, interval, backoff, sealed credentials | -| `commit_statuses` | M6 | Commit oid, context, state, target URL, creator | -| `replication_state` | M5 | Per-repo, per-replica last ref checksum, last success and failure | +| Table | Purpose | +|---|---| +| `issues` | Number per repo, title, body, state, author, timestamps | +| `comments` | Issue and PR comments, polymorphic by parent, edit history | +| `labels` | Per-repo labels, plus an `issue_labels` join | +| `milestones` | Per-repo milestones, due date, state | +| `pulls` | PR number, base and head refs, head oid, merge state, outdated flag | +| `reviews` | Reviewer, state (approve, request changes, comment), commit oid | +| `review_comments` | Commit oid, path, line, side, diff hunk, outdated flag (kept, never deleted) | +| `webhooks` | Target URL, events, encrypted secret (sealed) | +| `deliveries` | Delivery id, attempt, status, request and response, retry state | +| `mirrors` | Pull and push mirrors, interval, backoff, sealed credentials | +| `commit_statuses` | Commit oid, context, state, target URL, creator | +| `replication_state` | Per-repo, per-replica last ref checksum, last success and failure | --- @@ -220,16 +219,16 @@ Push: - reject ref names with a leading `-` or containing `..` 5. The response is `{allow, message}`. The hook prints `message` to stderr and exits 0 if allowed, 1 if not. A non-zero exit rejects the whole push. 6. On accept, git moves the objects out of quarantine and updates refs. Git updates refs in one transaction. -7. Post-receive: `hook post-receive` POSTs the same updates to `/hook/post-receive`. The handler calls `record_push_event` for each ref. Replication (M5), webhooks (M5), PR ref updates (M4), and cache invalidation (M2) attach here. Post-receive cannot reject. +7. Post-receive: `hook post-receive` POSTs the same updates to `/hook/post-receive`. The handler calls `record_push_event` for each ref. Replication, webhooks, PR ref updates, and cache invalidation attach here. Post-receive cannot reject. 8. Hook failures are fail-closed for pre-receive. If the socket is unreachable, the push is rejected. -### 5.5 User-content domain for raw files (M2) +### 5.5 User-content domain for raw files Raw and user-uploaded files are served from `user_content_base_url` (for example `raw.`), a separate origin from the app. 1. Request arrives on the user-content host. The path is parsed as owner, repo, ref, and file path. 2. Repo lookup, then `authorize(actor, repo, role, Action::Read)`. Anonymous is allowed for public repos. A private repo the caller cannot see gives 404. -3. Every path component is checked for symlinks before reading, not only the last one (research §4). +3. Every path component is checked for symlinks before reading, not only the last one. 4. The blob is read through `gix` and streamed. HTML and SVG are served with `Content-Disposition: attachment`. 5. Every response carries `X-Content-Type-Options: nosniff` and a strict CSP. 6. Cookies from the app origin are never sent to this origin. Session auth is not accepted on this host. @@ -268,7 +267,7 @@ Rules (in order): Status mapping: `NotFound` becomes 404 everywhere, including git and SSH. `Forbidden` becomes 403 on web and after authentication. For git over HTTP, an unauthenticated request that needs auth gets 401 with the Basic challenge. A private repo is never revealed by a 403. Any future go-get-style endpoints follow the same rule. -Roles: `Read`, `Triage`, `Write`, `Maintain`, `Admin` (per repo, from `collaborators`), plus instance admin. Org teams come later (research §10). +Roles: `Read`, `Triage`, `Write`, `Maintain`, `Admin` (per repo, from `collaborators`), plus instance admin. Org teams come later. --- @@ -286,7 +285,7 @@ Rules: - `paths()` appends `--` then the paths. - `env()` takes only `&'static str` keys. - User input reaches git only through `GitCommand`. -- Repo-local config is not trusted (research §4). Submodules are never recursed. +- Repo-local config is not trusted. Submodules are never recursed. ### 7.2 Managed gitconfig (`/gitconfig`) @@ -294,32 +293,32 @@ Written at boot by `write_managed_gitconfig()`. Keys: - `core.hooksPath=/hooks` - `receive.fsckObjects=true`, `transfer.fsckObjects=true` -- `core.fsync` and `core.fsyncMethod` set explicitly. The default `committed,-loose-object` risks losing recent work (research §16). +- `core.fsync` and `core.fsyncMethod` set explicitly. The default `committed,-loose-object` risks losing recent work. - `uploadpack.allowFilter=true`, `uploadpack.allowRefInWant=true` - `receive.advertisePushOptions=true` -- `protocol.file.allow=user` (research §4) -- Later: `uploadpack.hideRefs` and `transfer.hideRefs` for internal refs (M4 `refs/pull/*` as needed) +- `protocol.file.allow=user` +- Later: `uploadpack.hideRefs` and `transfer.hideRefs` for internal refs (`refs/pull/*` as needed) ### 7.3 Repo path layout `/repos///.git`, where `` is the lowercased ULID. Created with `git init --bare` through the builder. Renames are DB-only, because the path depends on the id, not the name. -### 7.4 Maintenance and caches (M2 and later) +### 7.4 Maintenance and caches - `git maintenance` with incremental repack and loose-objects, or `git repack --geometric=2 --write-midx`. - Commit-graph with changed-path Bloom filters (makes `git log -- path` fast). - Bitmaps for clone speed. -- A pool of long-running `git cat-file --batch-command` processes, one per repo, for hot reads (research §7). -- "Last commit per file" cache keyed by `(commit, path)` for tree views (research §5). +- A pool of long-running `git cat-file --batch-command` processes, one per repo, for hot reads. +- "Last commit per file" cache keyed by `(commit, path)` for tree views. - Archive cache, with no promise of stable checksums across git versions. -- Forks: full copies first. Alternates or object pools are deferred, and pools must never be pruned (research §5). +- Forks: full copies first. Alternates or object pools are deferred, and pools must never be pruned. - Ref updates use `git update-ref --stdin` for atomicity. ### 7.5 Minimum git version - Boot calls `require_min_version(env, (2,38,0))`. Boot fails if git is older. -- 2.38 is required for `merge-tree --write-tree` (M4). -- In practice, track the latest git release for security fixes. Keep it patched (CVE-2024-32002 and CVE-2025-48384 are submodule hook-execution bugs, research §4). +- 2.38 is required for `merge-tree --write-tree`. +- In practice, track the latest git release for security fixes. Keep it patched (CVE-2024-32002 and CVE-2025-48384 are submodule hook-execution bugs). --- @@ -330,11 +329,11 @@ Written at boot by `write_managed_gitconfig()`. Keys: - **Primary** (writes, serves users). - **Standby** at a different provider. It receives git mirrors, DB snapshots, and bundles. - **Immutable backups** at a third location and provider. -- Provider diversity covers provider, payment method, contact email, and jurisdiction. Research §11 notes that account termination can happen without warning. Lesson from SourceHut (2024): the standby was under 30s behind, but backups were up to 12h old with no off-site copy. Lesson from OVH Strasbourg (2021): backups at the same site burned with the primary. +- Provider diversity covers provider, payment method, contact email, and jurisdiction. Account termination can happen without warning. Lesson from SourceHut (2024): the standby was under 30s behind, but backups were up to 12h old with no off-site copy. Lesson from OVH Strasbourg (2021): backups at the same site burned with the primary. ### 8.2 Git replication (single writer) -1. After post-receive, a replication job takes a per-repo lock and runs `git push --mirror` to each replica over SSH. Failures are recorded and retried with backoff. Push mirrors run after each push (M5). +1. After post-receive, a replication job takes a per-repo lock and runs `git push --mirror` to each replica over SSH. Failures are recorded and retried with backoff. Push mirrors run after each push. 2. Hourly reconcile: compare a ref checksum (sha256 of sorted `git for-each-ref --format='%(objectname) %(refname)'`) between primary and replica. On mismatch, re-mirror and run `git fsck`. 3. Daily `git bundle create --all` per repo to off-provider storage, then `git bundle verify`. 4. Weekly `git fsck --full` on replicas from cron. `git maintenance` has no fsck task. @@ -345,7 +344,7 @@ Written at boot by `write_managed_gitconfig()`. Keys: - Turso supports only `synchronous` OFF or FULL. Use WAL with FULL. - Litestream is not verified on Turso files, and Turso says mixed SQLite and Turso access across processes is unsupported. Spike before relying on it (open question 2). - Turso Sync and CDC are documented only for Turso Cloud. Do not depend on them for self-hosting. -- Verified path: `VACUUM INTO` snapshots every 5-15 minutes. Ship each snapshot to the standby and to backups. Keep a JSON or F3 export as a second format (F3: friendly forge format, JSON plus attachments, research §9). +- Verified path: `VACUUM INTO` snapshots every 5-15 minutes. Ship each snapshot to the standby and to backups. Keep a JSON or F3 export as a second format (F3: friendly forge format, JSON plus attachments). - Integrity: `PRAGMA quick_check` daily. `integrity_check` plus `foreign_key_check` weekly. Alert on any result other than `ok`. ### 8.4 Integrity, backups, and drills @@ -360,7 +359,7 @@ Written at boot by `write_managed_gitconfig()`. Keys: - Dead-man switch: healthchecks.io pings with `/start` and `/fail` for each backup and integrity job. A missed ping alerts. - Filesystem: btrfs (or ZFS with at least 4 GB RAM) for checksums, scrub, and snapshots. ext4 or XFS with tested backups is acceptable on small VPSes. - App files: write temp file, fsync it, rename it, fsync the directory. -- After any unclean shutdown, run `git fsck` (GitLab runbook, research §11). +- After any unclean shutdown, run `git fsck` (GitLab runbook). ### 8.5 Manual failover with fencing @@ -380,9 +379,9 @@ Do: - Put `--end-of-options` before user revisions and `--` before paths. Reject names and refs that start with `-`. - Route all git calls through `GitCommand`. - Check every path component for symlinks when rendering, archiving, or writing. -- Use exact, case-sensitive key lookup (Gitea auth bypass, research §2). -- Disable `ssh-rsa` with SHA-1. Set handshake and auth timeouts (Gogs DoS, research §2). -- Accept only `GIT_PROTOCOL` from SSH env requests (Gogs CVE-2024-39930, research §2). +- Use exact, case-sensitive key lookup (Gitea auth bypass). +- Disable `ssh-rsa` with SHA-1. Set handshake and auth timeouts (Gogs DoS). +- Accept only `GIT_PROTOCOL` from SSH env requests (Gogs CVE-2024-39930). - Store tokens and session tokens as sha256 hashes. Compare in constant time. Show tokens once. - Keep tokens out of URLs and logs. - Return 404 for both missing and forbidden private repos. @@ -402,16 +401,16 @@ Don't: - Don't use dumb HTTP or `http.getanyfile`. - Don't recurse into submodules or trust repo-local config. - Don't let users write hooks or config. -- Don't hard-delete users. Reassign their issues and comments to a ghost user (M3). +- Don't hard-delete users. Reassign their issues and comments to a ghost user. - Don't let the browser use the app origin for raw content. -- Don't bypass branch rules through a non-PR path (the Gitea gap: required checks only applied to PR merges, research §3). +- Don't bypass branch rules through a non-PR path (the Gitea gap: required checks only applied to PR merges). - Don't rely on Turso Sync or Litestream until spiked. --- -## 10. Milestones +## 10. Roadmap -### M1: clone and push work (this plan) +### Clone and push - Scaffold the workspace (`cargo add`, latest versions), config template, `.gitignore`, systemd unit, SCSS build. - Local accounts with argon2id. First user becomes admin, via `admin create-user` or `/setup` while zero users exist. Registration is `closed` by default. @@ -421,7 +420,7 @@ Don't: - Pre-receive policy (archived, default-branch delete and force-push, bad ref names) and post-receive `push_events`. Minimal UI: setup, login, dashboard, new repo, repo page, settings, admin users, `/healthz`. - Tests: unit tests in core and git; end-to-end `git_e2e.rs` over HTTPS and SSH, with negative cases (bad token, cross-user private 404, forced default-branch push rejected, unknown SSH command rejected, traversal rejected, POST without CSRF rejected). -### M2: repo browsing and raw domain (implemented) +### Repo browsing and raw files Built: @@ -457,15 +456,15 @@ Known gaps: - Symlink-safe path resolution, and `cat-file --batch-command` pool. - Caches: last commit per file, archives. Maintenance schedule and commit-graph. -### M3: issues +### Issues - Issues with per-repo numbers, state, author, timestamps, and edit history. - Comments on issues (polymorphic `comments` table), with ghost-user reassignment on account deletion. - Labels and milestones, with per-repo scope. - Issue list and detail pages, filters, and permissions through `authorize()`. -- Markdown bodies sanitized as in M2. +- Markdown bodies are sanitized the same way as repo READMEs. -### M4: pull requests +### Pull requests - PR head stored as `refs/pull/N/head` in the base repo, updated on every push to the head branch in post-receive. - Mergeability checked with `git merge-tree --write-tree`, recomputed when base or head moves. Optional `refs/pull/N/merge`. @@ -474,7 +473,7 @@ Known gaps: - Merge strategies: merge commit (`commit-tree` from merge-tree output), squash, rebase, fast-forward only. - `range-diff` for "what changed since the last review." AGit (`refs/for/`) is considered later. -### M5: webhooks, push mirrors, replication, backups, export +### Webhooks, push mirrors, replication, backups, export - Webhooks: HMAC-SHA256 signature over the raw body, delivery id header, 10s timeout, retry queue, delivery log. - Pull mirrors on an interval with a minimum; push mirrors with sealed credentials, run after each push with backoff. SSRF rules from section 9 apply. @@ -483,12 +482,12 @@ Known gaps: - Backups per section 8.4: immutable tier, append-only push, restore drills, dead-man alerts. - Manual failover runbook per section 8.5, tested once end to end. -### M6: custom CI runner and commit-status API +### Custom CI runner and commit-status API -- Commit-status API (`commit_statuses`: commit oid, context, state, target URL, creator). Required checks enforced on push and PR merge, not only on PR merge (research §3). -- Webhooks from M5 drive CI job dispatch. +- Commit-status API (`commit_statuses`: commit oid, context, state, target URL, creator). Required checks enforced on push and PR merge, not only on PR merge. +- Webhooks drive CI job dispatch. - Custom runner: a separate process with a narrow protocol, that reports status back through the API. Runner credentials are scoped tokens. -- Consider a Gitea-compatible API subset later, which would let Woodpecker, Renovate, and `tea` work (research §9). Decide when the API surface is known. +- Consider a Gitea-compatible API subset later, which would let Woodpecker, Renovate, and `tea` work. Decide when the API surface is known. - Log retention and secret masking for job output. --- @@ -496,5 +495,5 @@ Known gaps: ## 11. Open questions 1. **Project name.** "forge" is a placeholder. Renaming is a find-and-replace, but pick it before public URLs and crate names are used. -2. **Does Litestream work with Turso files?** Unverified. Turso says mixed SQLite and Turso access across processes is unsupported. Run a spike before relying on it for replication. Fallback is the `VACUUM INTO` path in section 8.3. -3. **Hosting providers.** Primary, standby, and backup providers must differ in provider, payment method, contact email, and jurisdiction (section 8.1). Candidates are not chosen. Confirm after reviewing the provider risk notes in research §11 (some are unverified). +2. **Does Litestream work with Turso files?** Not yet tested. Turso says mixed SQLite and Turso access across processes is unsupported. Run a spike before relying on it for replication. Fallback is the `VACUUM INTO` path in section 8.3. +3. **Hosting providers.** Primary, standby, and backup providers must differ in provider, payment method, contact email, and jurisdiction (section 8.1). Candidates are not chosen. Confirm after reviewing the provider risk notes. diff --git a/docs/backlog.md b/docs/backlog.md index 8cd53bf..66c1991 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -35,7 +35,7 @@ Status: `[ ]` todo, `[~]` in progress, `[x]` done. - [x] Webhooks (HMAC-SHA256, delivery log, retries, SSRF guard) - [x] Webhook follow-ups: audit entries, sent headers in the delivery log - [x] Notifications (in-app inbox for mentions, assignments, comments on watched issues) -- [x] Push and pull mirrors (contract: `docs/mirrors-interfaces.md`) +- [x] Push and pull mirrors - [x] Mirror follow-ups: add a pull mirror in settings to an empty repo; e2e pull over real HTTP; pin git's DNS to the checked address (rebinding race) - [x] Backups: verified sets (DB snapshot + bundles), scheduler with retention and healthchecks, `fsck` schedule, `/admin/backups`, restore command, `docs/backup.md` - [x] Replication to the standby (`push --mirror` after each push, hourly reconcile by refs checksum, DB snapshots; `/admin/replication`; runbook in `docs/backup.md`) @@ -60,7 +60,7 @@ Status: `[ ]` todo, `[~]` in progress, `[x]` done. - [x] Signed commit verification (SSH/GPG) badges - [x] Compression for HTML pages (tower-http layer with a text-only, path-excluding policy; `docs/architecture.md` §5.6) -## M6: CI (contract: `docs/ci-interfaces.md`) +## M6: CI (see `docs/ci.md`) - [x] `forge-ci` crate: `.forge/ci.toml` parsing and validation, triggers, runner protocol types, secret masking - [x] Schema and store: runners, registration tokens, runs, jobs, artifacts, sealed secrets - [x] Scheduling on push, tag, PR and manual runs; fork PR approval; commit statuses; lost-runner reaper; retention @@ -70,17 +70,17 @@ Status: `[ ]` todo, `[~]` in progress, `[x]` done. - [x] `forge-runner` binary: rootless podman executor, workspace checkout, log streaming, artifacts, timeouts - [x] CI end-to-end test and `docs/ci.md` -## Runner without podman (contract: `docs/ci-builtin-executor.md`) +## Runner without podman (see `docs/ci.md`) - [x] Images: in-process registry pull, digest-verified blob cache, safe layer unpacking (whiteouts, no escapes), GC - [x] Sandbox: `forge-runner __sandbox` helper on youki `libcontainer` (rootless userns, pure-Rust seccomp via seccompiler, no caps, overlay rootfs, cgroup limits) - [x] `BuiltinExecutor` as the default, `forge-runner check`, runner config and `docs/ci.md` updates -## CI sandbox v2 (contract: `docs/ci-sandbox-v2.md`) +## CI sandbox v2 - [x] Subordinate id mapping via newuidmap/newgidmap, auto fallback to single uid, `__sandbox-rm` - [x] Image layers unpacked with real ownership inside the mapped userns (`__sandbox-unpack`) - [x] Sandbox, executor, config (`[sandbox] userns`), `check` and docs use the mapping -## Wave C (contract: `docs/wave-c-interfaces.md`) +## Wave C - [x] O1 organizations core (accounts of kind org, members, teams, authz) - [x] O2 organizations UI (org pages, owner select, transfer to org) - [x] M1 mail core (lettre, outbox worker, admin mail settings) diff --git a/docs/backup-interfaces.md b/docs/backup-interfaces.md deleted file mode 100644 index 022eccb..0000000 --- a/docs/backup-interfaces.md +++ /dev/null @@ -1,51 +0,0 @@ -# Backups, phase 1 (contract between workers) - -The background is in `docs/architecture.md` §8.2–8.4. Phase 1 makes complete, verifiable backups **locally**: a directory that an external tool (restic, rclone, or borg with append-only keys) ships off-site. Shipping it, standby replication and push mirrors come later. - -The global rules apply: -- No unwrap in non-test code. -- Tests use `tempfile::TempDir`. -- Never put cargo target dirs or big files in /tmp. - -## Backup set layout -``` -/forge-backup-/ - manifest.json # format version, forge version, created_at, instance base_url, files [{path, bytes, sha256}], repos [{id, owner, name, refs_sha256, bundle | null (empty repo)}] - db/forge.db # consistent snapshot - repos/.bundle # `git bundle create --all`, then `git bundle verify` before the manifest is written - keys/forge.key # only with --include-key; otherwise the manifest records "key_included": false -``` -- `refs_sha256` is the sha256 of sorted `git for-each-ref --format='%(objectname) %(refname)'` (the reconcile checksum from architecture §8.2). It's computed from the bundle-time ref list, so a restore can compare against it. -- The directory is written as `.partial-…` and renamed atomically when complete. A crash never leaves something that looks like a finished backup. -- Files are 0600 and directories 0700. - -## DB snapshot -- Use `VACUUM INTO ''` if Turso 0.8.x supports it; the worker must verify this with a test. -- **Fallback:** hold the store's connection mutex so there are no concurrent writers, run `PRAGMA wal_checkpoint(TRUNCATE)` (or the Turso equivalent), copy the DB file (and the WAL, if any is left), then release. -- Verify the result by opening it read-only with a fresh connection and running `PRAGMA integrity_check` (or `quick_check`), with the migrations version check. - -## Commands (`forge-web admin …`) -- `backup --out DIR [--include-key] [--repos-only | --db-only]`: prints the path and a summary, and exits non-zero on any failure. -- `backup-verify PATH`: recomputes every sha256, runs `git bundle verify` on each bundle (in a scratch repo under PATH's parent, **not /tmp**), opens the DB snapshot read-only and runs `integrity_check`, and checks the manifest's repo list against the DB snapshot's `repos` table. -- `restore --from PATH --data-dir NEW_DIR`: refuses a non-empty NEW_DIR. Copies the DB, then for each repo runs `git clone --mirror ` into `repo_path(NEW_DIR, id)` (or `init --bare` + `fetch` from the bundle with `+refs/*:refs/*`) and removes the remote. Then writes the managed gitconfig and hooks the same way boot does, compares `refs_sha256` per repo, and writes `forge.key` if the set has one (otherwise warns loudly that the key must be restored by hand). -- `fsck [--full]`: `git fsck` (`--full` if asked) on every repo plus the DB `integrity_check`. Reports per repo, and exits non-zero on any problem. - -## Scheduler (config `[backup]`) -```toml -[backup] -dir = "" # empty = disabled -interval_hours = 24 # full backup set -keep = 7 # keep the newest N complete sets in dir (delete older complete sets only; never touch other files) -healthcheck_url = "" # optional; GET /start, then on success or /fail with the error (healthchecks.io style) -fsck_interval_days = 7 -``` -- A tokio task started at boot runs the same code as the CLI. Healthcheck pings use a plain reqwest client with a 10s timeout; the URL is admin-configured and trusted. -- `GET /admin/backups` (instance admins): the last 20 runs (time, duration, size, ok or error), backup and fsck statuses, and a "Run backup now" POST with CSRF. Runs are recorded in a table `backup_runs(id, kind 'backup'|'fsck', started_at, finished_at, ok, path, bytes, error)`, migration `0014_backup_runs.sql`. - -## Docs -`docs/backup.md` covers: -- what is in a set and what isn't (the key); -- how to ship it off-site with restic append-only or rclone, plus a sample systemd timer; -- how to restore, step by step; -- a quarterly restore drill; -- the fencing reminder from architecture §8.5. diff --git a/docs/backup.md b/docs/backup.md index cbf3434..21a6378 100644 --- a/docs/backup.md +++ b/docs/backup.md @@ -1,6 +1,6 @@ # Backups -This is the operator guide for forge backups. The design is in `docs/architecture.md` §8 and the format is in `docs/backup-interfaces.md`. Read this page before you rely on backups, and run the restore drill below at least once a quarter. +This is the operator guide for forge backups. The design is in `docs/architecture.md` §8. Read this page before you rely on backups, and run the restore drill below at least once a quarter. ## What a backup set contains diff --git a/docs/branch-protection-interfaces.md b/docs/branch-protection-interfaces.md deleted file mode 100644 index dfb579b..0000000 --- a/docs/branch-protection-interfaces.md +++ /dev/null @@ -1,60 +0,0 @@ -# Branch protection (contract between workers) - -The global rules from `docs/m1-interfaces.md` apply. - -## Migration `crates/forge-core/migrations/0003_branch_protection.sql` -```sql -CREATE TABLE branch_protections ( - id TEXT PRIMARY KEY, -- ULID - repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, - pattern TEXT NOT NULL, -- "main", "release/*", "**" - allow_force_push INTEGER NOT NULL DEFAULT 0, - allow_deletion INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - UNIQUE (repo_id, pattern) -); -``` -`Store::delete_repo` must delete these rows too, in the same transaction. - -## forge-core `src/protection.rs` -```rust -#[derive(Debug, Clone, PartialEq)] -pub struct BranchRule { pub id: String, pub repo_id: String, pub pattern: String, - pub allow_force_push: bool, pub allow_deletion: bool, pub created_at: String } - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Protection { pub allow_force_push: bool, pub allow_deletion: bool } - -/// Pattern syntax: a literal branch name, `*` matches any run of chars except `/`, `**` matches anything -/// including `/`. Max 200 bytes, it must be a valid branch name otherwise (no `..`, no leading `-`, no -/// control or space chars, no `~^:?[\`). The pattern must not include the `refs/heads/` prefix. -pub fn validate_pattern(p: &str) -> Result<()>; -pub fn pattern_matches(pattern: &str, branch: &str) -> bool; - -/// Rules for `branch` (short name, without refs/heads/): -/// 1. If any rule matches: the most specific one wins. A literal (no `*`) beats a glob; among globs the -/// longest pattern wins, and ties go to the earliest created_at. -/// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}. -/// 3. Otherwise: unprotected {force_push: true, deletion: true}. -pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Protection; -``` - -## Store (forge-core) -```rust -pub async fn list_branch_rules(&self, repo_id: &str) -> Result>; // ordered by pattern -pub async fn upsert_branch_rule(&self, repo_id: &str, pattern: &str, allow_force_push: bool, allow_deletion: bool) -> Result; -pub async fn delete_branch_rule(&self, repo_id: &str, rule_id: &str) -> Result<()>; // scoped by repo_id -``` - -## Enforcement (forge-web `internal.rs` pre-receive) -For each updated `refs/heads/`, compute `effective(rules, repo.default_branch, branch)`: -- deletion (new = zero oid) with `!allow_deletion` → reject: `deleting protected branch '' is not allowed` -- non-fast-forward (the existing `rev-list` check) with `!allow_force_push` → reject: `force-push to protected branch '' is not allowed` -- Pushes to the archived repo and the ref-name checks stay as they are. Tags are not covered by these rules. - -## UI (forge-web `pages/repo_settings.rs`) -- On `/{owner}/{repo}/settings`, a "Branch protection" section above the Danger zone: - - A table of rules: pattern, force push allowed (yes/no), deletion allowed (yes/no), and a Remove button (POST with CSRF). - - If no rule matches the default branch, show a muted row: "`` (default branch): protected by default; add a rule for it to change this." - - An add/update form: pattern (prefilled with the default branch), checkboxes "Allow force pushes" and "Allow deletion", and a Save button. Saving an existing pattern updates it. -- Who can manage rules: `Action::Admin` (the repo owner, instance admins, and collaborators with the Admin role). Others get 404 or 403, like the existing settings. diff --git a/docs/ci-builtin-executor.md b/docs/ci-builtin-executor.md deleted file mode 100644 index 9aee5cd..0000000 --- a/docs/ci-builtin-executor.md +++ /dev/null @@ -1,104 +0,0 @@ -# Built-in executor for forge-runner (contract between workers) - -**Goal:** `forge-runner` runs jobs in containers with **no external container tool**. There's no podman: images are pulled and unpacked in-process, and the job runs in a rootless sandbox built with youki's `libcontainer` crate. `PodmanExecutor` stays as an option. Runner config gains `executor = "builtin"` (the default) or `"podman"`. - -The global rules apply: -- No unwrap in non-test code. -- Tests use `tempfile::TempDir`. -- Never put cargo target dirs or big files in /tmp. -- Crates go in at their latest version via `cargo add`, recorded in the root `[workspace.dependencies]`. -- Only rustfmt your own files. - -Crates (latest): `oci-client`, `oci-spec`, `libcontainer` (youki; **check its 0.7 API in ~/.cargo/registry/src/*/libcontainer-*/ after adding it**), `tar`, `flate2`, `zstd` (if layers can be zstd), `sha2`, `nix` or `rustix`. - -## Design decisions (fixed) -- **Self re-exec.** libcontainer forks and clones, which is unsafe inside a multi-threaded tokio process. So the runner never calls libcontainer in its own process. It spawns `/proc/self/exe __sandbox` (a hidden subcommand in main.rs) as a single-threaded child **with no tokio runtime**. The child reads a JSON `SandboxRequest` from **stdin** (the secrets travel there, never in argv or files), builds the container, runs it, forwards stdout and stderr, and exits with the job's exit code. Killing the helper (SIGTERM, then SIGKILL after a grace period) must tear the container down: the helper handles SIGTERM by killing and deleting the container. -- **User namespace, v1: single-uid mapping.** Container uid 0 maps to the runner's uid, with no `newuidmap` needed. Layers are unpacked with ownership flattened to the runner's user, and setuid/setgid bits are stripped. Document that package managers which `chown` to other users may fail. (v2, later and not in this task: a subuid range through `newuidmap` when available.) -- **Namespaces:** user, mount, pid, ipc, uts, cgroup. **Network:** `network = false` gets a new empty net namespace (loopback only). `network = true` **shares the host network namespace**, because rootless isolated networking needs pasta or slirp, which are external tools. Document this clearly in docs/ci.md: on `network = true` jobs can reach services on the runner host's localhost. -- **Hardening:** - - no capabilities, in any of the sets; - - `no_new_privileges`; - - a seccomp profile: default allow, deny with EPERM for `keyctl`, `add_key`, `request_key`, `bpf`, `perf_event_open`, `ptrace`, `mount`, `umount2`, `pivot_root`, `swapon`, `swapoff`, `reboot`, `kexec_load`, `kexec_file_load`, `init_module`, `finit_module`, `delete_module`, `unshare`, `setns`, `open_by_handle_at`, `userfaultfd`, `acct`, `settimeofday`, `clock_settime`, `syslog`, `iopl`, `ioperm`, `quotactl`, `name_to_handle_at`, `lookup_dcookie`; - - masked paths and read-only paths as docker does (`/proc/kcore`, `/proc/keys`, `/proc/sys` read-only, and so on); - - rlimits: `RLIMIT_NPROC` set from `limits.pids`, and `RLIMIT_NOFILE` 65536. -- **Limits:** use a cgroup v2 rootless cgroup through libcontainer (systemd or fs driver, whichever works rootless) for memory, cpus and pids from `[limits]`. **If cgroups can't be set up, run anyway**, and log one warning line into the job log ("resource limits unavailable: …"). The job timeout still applies. -- **Filesystem:** - - The rootfs is an **overlay** mount with the cached image rootfs as `lowerdir`, plus `upperdir`/`workdir` in `/jobs//overlay/`. Rootless overlayfs inside the user namespace needs kernel ≥ 5.11, and this host has 7.2. - - If the overlay mount fails, fall back to a full copy of the rootfs into the job dir (try a reflink copy first) and log that. - - `/workspace` is a bind mount of the job workspace (rw); `/tmp` is a tmpfs; `/proc`, `/dev` (tmpfs plus the standard null, zero, full, random, urandom and tty device bind mounts from the host), `/dev/pts`, `/dev/shm`, `/sys` (ro). - - `/etc/resolv.conf` is bind-mounted from the host (ro) when `network = true`. `/etc/hosts` and `/etc/hostname` are generated. - - Everything under `jobs/` is deleted after the job. -- **Process:** `sh -eu -c `, cwd `/workspace`. - - Env: the image config's `Env`, then `HOME=/root`, `CI=true`, `FORGE_CI=true`, then the job env, then the secrets. - - PATH comes from the image config, or the default `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`. - -## Worker E1: images, `crates/forge-runner/src/oci/{mod.rs, pull.rs, unpack.rs, store.rs}` -```rust -pub struct ImageStore { root: PathBuf } // /oci -impl ImageStore { - pub fn new(root: PathBuf) -> Self; - /// Resolves `image` ("docker.io/rust:1", "alpine", "ghcr.io/o/i@sha256:…"), pulls the manifest for linux/, - /// downloads missing layer blobs (verified by sha256 digest, written temp+rename), unpacks once per manifest digest, - /// and returns the rootfs path + image config. Concurrent calls for the same image must not corrupt (lock file per digest). - pub async fn ensure(&self, image: &str, auth: Option<&RegistryAuth>, log: &mpsc::Sender>) -> Result; - /// Deletes unpacked rootfs dirs and blobs not used for `keep_days` (by an mtime "last used" stamp file). - pub fn gc(&self, keep_days: u32) -> Result; -} -pub struct PreparedImage { pub rootfs: PathBuf, pub digest: String, pub env: Vec, pub working_dir: Option, pub user: Option } -pub struct RegistryAuth { pub username: String, pub password: String } // Debug redacts -``` -- **Image references:** `alpine` normalizes to `docker.io/library/alpine:latest`. Use oci-client's `Reference`. -- **Pull policy:** always check the manifest digest (a HEAD or GET manifest), and reuse the unpacked rootfs when the digest matches. When the registry is unreachable and a rootfs for that tag was pulled before, use it and log a warning. To support this, keep a `tags/` file holding the last digest. -- **Unpacking (security-critical):** - - Process the layers in order. Support gzip, zstd and uncompressed layers. - - **Never write outside the rootfs.** Reject entries whose normalized path is absolute or contains `..`. - - Resolve every parent component **without following symlinks that lead out**: create files with `openat`-style handling, or check each parent with `symlink_metadata`, and never follow a symlink in a parent path. - - Hardlinks must point inside the rootfs. - - Whiteouts: `.wh.` deletes ``; `.wh..wh..opq` clears the directory's earlier-layer contents. - - Skip device and fifo nodes, logging the count. - - Strip setuid/setgid. Keep the other permission bits, and set the owner to the current user. - - Cap total unpacked size at `[limits] image_max_gb` (default 20). -- **Tests:** - - craft tar layers in the test (with the `tar` builder) to cover traversal (`../x`, `/abs`), a symlink-parent escape (`a -> /etc`, then `a/passwd`), a hardlink escape, whiteouts and opaque dirs, setuid stripping, and gzip and zstd; - - a reference-normalization test; - - one `#[ignore]` test that pulls `docker.io/library/alpine:latest` for real. - -## Worker E2: sandbox, `crates/forge-runner/src/sandbox/{mod.rs, spec.rs, helper.rs}` -```rust -#[derive(Serialize, Deserialize)] -pub struct SandboxRequest { pub job_id: String, pub rootfs: PathBuf, pub job_dir: PathBuf /* overlay + container state */, pub workspace: PathBuf, - pub env: Vec<(String, String)>, pub run: String, pub network: bool, pub limits: Limits /* existing config::Limits */ } -pub fn build_spec(req: &SandboxRequest, uid: u32, gid: u32, rootfs_mount: &Path) -> Result; // pure, unit-tested -pub fn helper_main() -> i32; // entry for `forge-runner __sandbox`: read SandboxRequest JSON from stdin, set up overlay (or copy fallback), run via libcontainer, forward output, return exit code (125 = sandbox setup failure, with the reason on stderr prefixed "forge-sandbox: ") -``` -- Use libcontainer's rootless support. **Check what libcontainer 0.7 needs**: whether it requires a `bundle` dir with `config.json` (write it under `job_dir`; the env, including secrets, is inside it, so write it 0600 in a 0700 dir and delete it right after start if libcontainer allows, otherwise when the job ends), its state dir (`job_dir/state`), and its stdio handling (inherit the helper's stdout and stderr). -- The helper must be **single-threaded with no tokio runtime**. In main.rs, intercept `__sandbox` before building the tokio runtime: switch `#[tokio::main]` to a manual runtime build after argument parsing. -- **Tests:** - - `build_spec` unit tests: namespaces, the uid map, no capabilities, no_new_privileges, seccomp contents, mounts, net namespace on and off, env order, and secrets never in `process.args`; - - a **real sandbox test with no network or registry**: - - build a tiny rootfs in a TempDir by copying `/bin/sh` (or busybox if present) and the shared libraries `ldd` lists for it (parse the ldd output); - - run `echo hi; id -u; cat /proc/self/status | grep CapEff; touch /workspace/f` through the helper (via `cargo`'s built test binary? It's simpler to invoke `helper_main` logic through a spawned `env!("CARGO_BIN_EXE_forge-runner") __sandbox` from an integration test in `crates/forge-runner/tests/sandbox.rs`); - - assert that the output contains hi, uid 0, `CapEff: 0000000000000000`, and that the workspace file exists on the host; - - a second test with `network = false` asserts there's no non-loopback interface (`cat /proc/net/dev`); - - a third asserts that writing to `/proc/sys/kernel/hostname` fails; - - if user namespaces are unavailable on the machine (check `/proc/sys/kernel/unprivileged_userns_clone`, or a failing `unshare -U`), skip with a message. - -## Worker E3: wiring, after E1 and E2: `BuiltinExecutor` in `crates/forge-runner/src/executor.rs`, plus config, CLI, docs -- `BuiltinExecutor { images: ImageStore, limits: Limits, helper: PathBuf /* std::env::current_exe() */ }` implements `Executor`: - 1. `ensure` the image, logging "pulling …" lines into the job log; - 2. spawn the helper with a piped stdin carrying `SandboxRequest`, and piped stdout and stderr, through the existing `forward_lines`; - 3. on cancel or timeout send SIGTERM, wait `STOP_GRACE`, then SIGKILL; - 4. map the outcome: exit 0 is Success; 125 with a "forge-sandbox:" stderr line is Error; anything else is Failure with the exit code. -- **Runner config:** - - `executor = "builtin" | "podman"`, default builtin; - - `[limits] image_max_gb = 20`; - - `[images] keep_days = 7`, with optional `[[registry]] host, username, password`; the password is only in the 0600 runner.toml; - - GC runs at startup and daily. -- **`forge-runner check`:** a new subcommand that reports whether user namespaces, overlayfs in a userns, cgroup delegation (which controllers) and seccomp work, so operators can diagnose a host. -- **docs/ci.md:** - - replace "rootless podman" as the requirement with "Linux ≥ 5.11 with unprivileged user namespaces; cgroup v2 delegation for limits (systemd does this for user sessions)"; - - podman becomes optional; - - document the `network = true` host-namespace caveat and the single-uid caveat. -- **Tests:** - - a flow test using `BuiltinExecutor` with a locally prepared rootfs; inject a fake `ImageStore` result, or add an `ImageSource` trait so tests can supply a rootfs dir; - - the existing flow tests stay as they are. diff --git a/docs/ci-interfaces.md b/docs/ci-interfaces.md deleted file mode 100644 index a364ff3..0000000 --- a/docs/ci-interfaces.md +++ /dev/null @@ -1,234 +0,0 @@ -# M6 CI (contract between workers) - -**Decided with the user (don't re-open):** -- Workflow file `.forge/ci.toml`. **No YAML anywhere.** -- Jobs run in **rootless podman**. -- The runner is a **separate `forge-runner` binary that pulls jobs** over HTTPS. The forge never connects to a runner. -- v1 has **secrets, artifacts and live logs**. No cache. - -**Global rules:** -- No JS and no inline styles. -- No unwrap in non-test code. -- Tests use `tempfile::TempDir`. -- Never put cargo target dirs or big files in /tmp. -- New crates go in at their latest version with `cargo add`, recorded in the root `[workspace.dependencies]`. -- User values come after `--end-of-options` when passed to git. - -## 0. Crates -- **New `crates/forge-ci`** (library; deps: serde, toml, serde_json, globset, thiserror). It is shared by forge-web and forge-runner, and has **no** turso, topcoat or tokio dependency. -- **New `crates/forge-runner`** (binary). Depends on forge-ci, reqwest (rustls, stream), tokio, clap, serde, toml, tempfile, sha2 and tracing. **Not** forge-core or forge-web. -- Add both to the root `members`. - -## 1. `forge-ci` (worker W1) -```rust -// config.rs : parse .forge/ci.toml -pub struct CiConfig { pub on: Triggers, pub jobs: BTreeMap } // job names: ^[a-z0-9][a-z0-9_-]{0,39}$, max 20 jobs -pub struct Triggers { pub push: Vec /* branch globs, e.g. "main", "release/*" */, pub tags: Vec /* tag globs */, - pub pull_request: bool, pub manual: bool /* default true */ } -pub struct JobSpec { pub image: String, pub run: String, pub needs: Vec, pub secrets: Vec /* ^[A-Z_][A-Z0-9_]{0,63}$ */, - pub env: BTreeMap, pub artifacts: Vec /* relative globs, no "..", no leading "/" */, - pub runs_on: Vec /* runner labels, all must match; default [] */, pub timeout_minutes: u32 /* default 60, 1..=360 */, - pub network: bool /* default true */ } -pub fn parse_config(text: &str) -> Result // deny_unknown_fields; validates names, needs refer to existing jobs, no cycles, image non-empty without whitespace, run non-empty, ≤ 64 KiB file -pub enum Event<'a> { Push { branch: &'a str }, Tag { tag: &'a str }, PullRequest, Manual } -impl CiConfig { pub fn triggered_by(&self, ev: &Event) -> bool; pub fn job_order(&self) -> Vec<&str> /* topological, stable by name */ } - -// proto.rs : runner <-> forge JSON (serde, snake_case) -pub struct RegisterRequest { pub token: String, pub name: String, pub labels: Vec } -pub struct RegisterResponse { pub runner_id: String, pub runner_secret: String } -pub struct ClaimRequest { pub labels: Vec } // POST, long-poll ≤ 30s; 204 = nothing -pub struct JobAssignment { pub job_id: String, pub job_token: String, pub repo: String /* owner/name */, pub clone_url: String, - pub commit: String, pub git_ref: String, pub job_name: String, pub image: String, pub run: String, - pub env: BTreeMap, pub secrets: BTreeMap, pub artifacts: Vec, - pub timeout_minutes: u32, pub network: bool } -pub struct HeartbeatResponse { pub cancel: bool } -pub struct FinishRequest { pub outcome: Outcome, pub exit_code: Option, pub message: Option } -pub enum Outcome { Success, Failure, Cancelled, Error } - -// mask.rs -pub struct Masker // new(secrets: impl IntoIterator); ignores values shorter than 4 chars; mask(&str) -> String replaces every - // occurrence (and the base64 standard encoding of each value) with "***"; must handle a value split across two - // chunks: `MaskStream` with push(&[u8]) -> Vec that holds back max_len-1 bytes, and finish() -> Vec -``` -Unit tests cover every validation error, glob triggers, topological order, cycle detection, and masking across chunk boundaries. - -## 2. Schema and store (migration `0024_ci`, worker W2) -```sql -CREATE TABLE ci_runners (id TEXT PRIMARY KEY, name TEXT NOT NULL, labels TEXT NOT NULL /* json */, secret_hash TEXT NOT NULL UNIQUE, - created_at TEXT NOT NULL, last_seen_at TEXT, disabled INTEGER NOT NULL DEFAULT 0); -CREATE TABLE ci_registration_tokens (token_hash TEXT PRIMARY KEY, created_by TEXT NOT NULL REFERENCES users(id), - created_at TEXT NOT NULL, expires_at TEXT NOT NULL, used_at TEXT); -CREATE TABLE ci_runs (id TEXT PRIMARY KEY, repo_id TEXT NOT NULL REFERENCES repos(id), number INTEGER NOT NULL, - trigger TEXT NOT NULL /* push|tag|pull_request|manual */, git_ref TEXT NOT NULL, commit_oid TEXT NOT NULL, pull_number INTEGER, - actor_id TEXT NOT NULL, state TEXT NOT NULL /* waiting_approval|queued|running|success|failure|cancelled|error */, - config_error TEXT, created_at TEXT NOT NULL, finished_at TEXT, UNIQUE (repo_id, number)); -CREATE TABLE ci_jobs (id TEXT PRIMARY KEY, run_id TEXT NOT NULL REFERENCES ci_runs(id) ON DELETE CASCADE, name TEXT NOT NULL, - spec TEXT NOT NULL /* JobSpec json */, state TEXT NOT NULL /* blocked|queued|running|success|failure|cancelled|error|skipped */, - runner_id TEXT, job_token_hash TEXT, exit_code INTEGER, message TEXT, queued_at TEXT, started_at TEXT, finished_at TEXT, - heartbeat_at TEXT, cancel_requested INTEGER NOT NULL DEFAULT 0, log_bytes INTEGER NOT NULL DEFAULT 0, UNIQUE (run_id, name)); -CREATE INDEX ci_jobs_queue ON ci_jobs(state, queued_at); -CREATE TABLE ci_artifacts (id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES ci_jobs(id) ON DELETE CASCADE, name TEXT NOT NULL, - size INTEGER NOT NULL, sha256 TEXT NOT NULL, created_at TEXT NOT NULL, UNIQUE (job_id, name)); -CREATE TABLE ci_secrets (repo_id TEXT NOT NULL REFERENCES repos(id), name TEXT NOT NULL, sealed BLOB NOT NULL, - created_at TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (repo_id, name)); -``` -`crates/forge-core/src/ci.rs` holds the models. `crates/forge-core/src/store/ci.rs` holds the functions below; they follow the read-pool rules in `~/.cache/forge-orch/read-pool-rules.md`, with pure SELECTs on `read_conn()`. -```rust -pub enum RunState { WaitingApproval, Queued, Running, Success, Failure, Cancelled, Error } // as_str/FromStr -pub enum JobState { Blocked, Queued, Running, Success, Failure, Cancelled, Error, Skipped } // as_str/FromStr, is_terminal() -pub struct CiRunner { id, name, labels: Vec, created_at, last_seen_at: Option, disabled: bool } -pub struct CiRun { id, repo_id, number: i64, trigger: String, git_ref, commit_oid, pull_number: Option, actor_id, state: RunState, - config_error: Option, created_at, finished_at: Option } -pub struct CiJob { id, run_id, name, spec_json: String, state: JobState, runner_id: Option, exit_code: Option, - message: Option, queued_at, started_at, finished_at, heartbeat_at: Option, cancel_requested: bool, log_bytes: i64 } -pub struct CiArtifact { id, job_id, name, size: i64, sha256, created_at } -pub struct NewJob<'a> { pub name: &'a str, pub spec_json: &'a str, pub needs: &'a [String] } - -// runners -create_registration_token(created_by, ttl_hours: u32) -> Result // stores sha256 -register_runner(token_plain, name, labels: &[String]) -> Result<(CiRunner, String /*runner secret plaintext*/)> // token single-use, not expired; Invalid otherwise -runner_by_secret(secret_plain) -> Result> // constant-time compare via hash lookup; also updates last_seen_at -list_runners() / set_runner_disabled(id, bool) / delete_runner(id) -// runs and jobs -create_run(repo_id, trigger, git_ref, commit_oid, pull_number: Option, actor_id, needs_approval: bool, jobs: &[NewJob], config_error: Option<&str>) -> Result - // number = max+1 per repo, in one transaction. Jobs with no needs start Queued (or Blocked when needs_approval), others Blocked. - // With config_error: no jobs, state Error. -approve_run(run_id) -> Result<()> // WaitingApproval -> Queued; needless jobs -> Queued -claim_job(runner: &CiRunner) -> Result> - // oldest Queued job whose spec.runs_on ⊆ runner.labels, in a transaction; sets Running, runner_id, started_at, heartbeat_at, token hash; run -> Running -job_by_token(job_id, token_plain) -> Result> // only while Running -heartbeat(job_id) -> Result -add_log_bytes(job_id, n: i64) -> Result<()> -finish_job(job_id, state: JobState, exit_code: Option, message: Option<&str>) -> Result - // terminal; then unblock dependants (all needs Success -> Queued; any need not Success -> Skipped, cascading); - // run state recomputed: any running/queued/blocked -> Running; else Failure if any failure/error, Cancelled if any cancelled, else Success -request_cancel(run_id) -> Result<()> // Queued/Blocked jobs -> Cancelled at once; Running jobs get cancel_requested = 1 -rerun(run_id, actor_id) -> Result // new run with the same commit, ref, trigger and job specs -reap_lost_jobs(older_than: &str /*stamp*/) -> Result> // Running jobs with heartbeat_at < older_than -> Error "runner lost" -run_by_number(repo_id, n) / run_by_id(id) / list_runs(repo_id, page, per_page) -> (Vec, total) / jobs_for_run(run_id) / job_by_id(id) -add_artifact(job_id, name, size, sha256) / list_artifacts(job_id) / artifact(job_id, name) -purge_old(logs_before: &str, artifacts_before: &str) -> Result<(Vec /*job ids whose logs to delete*/, Vec /*artifact ids*/)> -// secrets (sealed with the instance key like mirror secrets) -set_ci_secret(repo_id, name, value: &[u8]) / delete_ci_secret(repo_id, name) -> Result / list_ci_secret_names(repo_id) -> Result> -ci_secret_values(repo_id, names: &[String]) -> Result> // only for claim; missing names omitted -``` -- `delete_repo` deletes the ci_runs (cascade) and ci_secrets rows. -- User deletion reassigns `actor_id` and `created_by` to the ghost user. - -## 3. forge-web: scheduling (worker W3), `crates/forge-web/src/ci/{mod.rs, schedule.rs, reaper.rs}` -- `pub async fn on_ref_update(state, repo, actor_id, refname, new_oid)` is called from `post_update::after_ref_update` for each updated `refs/heads/*` or `refs/tags/*` (not deletions; not pull mirrors pulling? **yes, pull mirrors also trigger**, with the system actor). - - It reads `.forge/ci.toml` at `new_oid` (forge-git blob read, capped at 64 KiB), parses it, and checks `triggered_by`. - - It creates the run with jobs in `job_order`, then sets a commit status `ci/` = pending for each job, with `target_url` = the job page. - - A parse error creates a run in state Error with `config_error` and a status `ci/config` = error. - - No file means nothing happens. -- `pub async fn on_pull_event(state, repo, pull, actor_id)` runs on PR open, synchronize and reopen (hook into the same places that emit the `pull_request` webhook). - - It reads the config at the PR **head** commit, with event `PullRequest`. - - **If the head repo is a fork, or the author doesn't have Write on the base repo:** `needs_approval = true`, the state is WaitingApproval, and the statuses are pending with the description "Waiting for approval". -- `pub async fn manual_run(state, repo, branch, actor_id) -> Result` runs only when `manual` is true. -- **Statuses:** whenever a job changes state, `crate::ci::sync_status(state, run, job)` sets `ci/`: - - queued/blocked/running → pending; - - success → success; - - failure → failure; - - error/cancelled → error; - - skipped → error, "skipped". -- **Reaper task, started at boot:** - - every 30s it runs `reap_lost_jobs(now - 120s)` and syncs the statuses; - - daily it runs `purge_old` with `[ci] log_retention_days` (default 90) and `artifact_retention_days` (default 30), and deletes the files. -- **`AppState.ci_waker: Arc`** is notified whenever a job becomes Queued, so long-polling claims wake. -- **Config `[ci]`:** - - `enabled = true` - - `max_log_mb = 16` - - `max_artifact_mb = 512` - - `max_artifacts_per_job = 50` - - `log_retention_days = 90` - - `artifact_retention_days = 30` - - `registration_token_hours = 24` - -## 4. forge-web: runner API (worker W4), `crates/forge-web/src/ci/api.rs` -All responses are JSON (`forge_ci::proto`). Runner auth is `Authorization: Bearer `. Job auth is `Authorization: Bearer ` on `/jobs/{id}/…`, checked with `job_by_token`. -- `POST /api/v1/ci/runners/register` takes RegisterRequest and returns RegisterResponse. -- `POST /api/v1/ci/runners/claim` takes ClaimRequest. It loops `claim_job`; if nothing is found, it awaits `ci_waker` or 25s, then tries once more. It returns 200 with a JobAssignment, or 204. - - The labels in the request are ignored; the stored labels are used. - - Disabled runners get 403. - - Secrets come from `ci_secret_values(repo, spec.secrets)`, **except for runs whose trigger is pull_request from a fork** (always empty there). - - `clone_url` is the repo's HTTPS clone URL. -- `POST /api/v1/ci/jobs/{id}/logs`: the body is a raw text chunk (≤ 1 MiB), with header `X-Forge-Log-Offset: `. - - It appends to `/ci/logs/.log` only if the offset equals the current size (idempotent retry: an equal end returns 200 without writing; a mismatch returns 409 with `X-Forge-Log-Size`). - - The server **masks again** with `Masker` built from the job's secret values before writing. - - The cap is `max_log_mb`. Past it, the server writes "[log truncated]" once and drops the rest. - - It calls `add_log_bytes`. -- `POST /api/v1/ci/jobs/{id}/heartbeat` returns HeartbeatResponse (`cancel_requested`). -- `PUT /api/v1/ci/jobs/{id}/artifacts/{name}` streams the raw body to the BlobStore (`crate::blobs`, key `ci/`), with a sha256 and the `max_artifact_mb` cap. - - The name must be `[A-Za-z0-9._+-]{1,128}` and must not start with ".". - - At most `max_artifacts_per_job`. -- `POST /api/v1/ci/jobs/{id}/finish` takes FinishRequest and calls `finish_job`. It syncs statuses for this job and for every job that became skipped or queued, and notifies `ci_waker`. -- **Git read with a job token:** smart-HTTP `authenticate` in `git_http.rs` also accepts Basic auth with username `ci-job` and password `:`. That gives read-only access to exactly that job's repo while the job is Running. Every write is refused. -- Compression is excluded for `/api/v1/ci/` paths (add the path to `compression.rs`). - -## 5. forge-web UI: runs (worker W5), `crates/forge-web/src/pages/ci_runs.rs`, `ci_job.rs` -- **"CI" repo tab.** - - `/{o}/{r}/ci` lists runs, newest first: number, state icon, trigger, ref, short commit, actor, and age. - - A "Run workflow" form (Write, `manual` allowed) offers a branch select. -- **`/{o}/{r}/ci/runs/{n}`** shows the jobs table with state, duration and runner name, plus `config_error` in a `
`.
-  - Buttons, each a POST with CSRF: Cancel (Write), Re-run (Write), and "Approve and run" (Write, only in WaitingApproval).
-- **`/{o}/{r}/ci/jobs/{job_id}`** shows the job log: the last 512 KiB of the log file in `
`, with a link to the full log.
-  - **No JS:** while the job is not terminal, the page has ``.
-  - Artifacts are listed with download links.
-- **`/{o}/{r}/ci/jobs/{job_id}/log.txt`** serves `text/plain; charset=utf-8`, `X-Content-Type-Options: nosniff`, and **streams live**. It sends the current file, then keeps following it (poll every 1s) until the job is terminal and the file is fully sent. This is the live log; a browser shows it progressively.
-- **`/{o}/{r}/ci/jobs/{job_id}/artifacts/{name}`** downloads as an attachment, with nosniff.
-- Read access follows repo Read. Logs of private repos are never on the user-content domain.
-- The commit list and PR page already show statuses through the status API, so check that the `ci/*` contexts render there.
-
-## 6. forge-web UI: secrets and runners (worker W6)
-- **`/{o}/{r}/settings/secrets`** (Admin):
-  - lists names and when each was updated, never the values;
-  - has an add/update form (name plus value textarea; the value is write-only);
-  - deletes with CSRF;
-  - records audit events `ci_secret_set` and `ci_secret_deleted` (name only).
-- **`/admin/runners`** (instance admin):
-  - lists runners with labels, last seen and disabled state;
-  - has disable/enable and delete buttons;
-  - has "Create registration token", which shows the token once along with the exact command `forge-runner register --url  --token  --name  --labels linux`;
-  - records audit events `ci_runner_registered`, `ci_runner_deleted` and `ci_registration_token_created`.
-
-## 7. `forge-runner` (worker W7)
-- **CLI:**
-  - `forge-runner register --url URL --token T --name N [--labels a,b] [--config PATH]` writes the config (TOML, 0600, default `~/.config/forge-runner/runner.toml`): url, runner_id, runner_secret, labels, `work_dir`, `concurrency = 1`, and the `[limits] memory = "4g"`, `cpus = "2"` and `pids = 4096` defaults.
-  - `forge-runner run [--config PATH]` loops claim → execute → finish, with `concurrency` jobs in parallel.
-- **Executor trait:**
-```rust
-#[async_trait-free: use Pin> or an enum] 
-trait Executor { async fn run(&self, job: &JobAssignment, workspace: &Path, log: &mut LogSink, cancel: CancellationToken) -> Outcome+exit code }
-```
-  - **`PodmanExecutor`** runs `podman run --rm --name forge-job- --pull=newer --network= --memory M --cpus C --pids-limit P --security-opt no-new-privileges --cap-drop ALL -v :/workspace:Z -w /workspace -e NAME...  sh -eu -c `.
-    - Env and secret values are passed through the child's environment with `-e NAME` (name only), **never in argv**.
-    - On cancel or timeout it runs `podman kill forge-job-`, then `podman rm -f`.
-    - The podman argv construction is unit-tested.
-  - **`HostExecutor`** exists only for tests, behind `#[cfg(any(test, feature = "test-host-executor"))]`. It runs `sh -eu -c` in the workspace with the env, and has no isolation.
-- **Workspace:** a fresh `work_dir/`. Run `git init`, then `git fetch --depth=1  ` with `GIT_CONFIG_*` env carrying `http.extraHeader: Authorization: Basic base64(ci-job::)`, never in argv, with `GIT_TERMINAL_PROMPT=0`. Then `git checkout --detach `. The workspace is deleted afterwards.
-- **Logs:**
-  - stdout and stderr are merged line-wise and prefixed with nothing.
-  - They pass through `MaskStream` and are batched (≤ 64 KiB or 1s), then POSTed with the offset. On 409 the runner resyncs to `X-Forge-Log-Size`.
-  - The first lines are runner info: runner name, image, and commit.
-- **Heartbeat** every 10s; `cancel: true` triggers the cancellation token. The timeout is `timeout_minutes`.
-- **Artifacts:** after a successful run, expand the globs inside the workspace (the canonicalized path must stay inside it, symlinks must not escape, and only regular files count). Upload each file under its relative path flattened with `/` → `_`, respecting the limits.
-- **Finish:** report `Success` on exit 0, `Failure` on a non-zero exit, `Cancelled`, and `Error` for runner or podman failures, with a message.
-- **Tests:** a mock forge (a small hyper or tokio TCP server in tests) plus `HostExecutor` cover:
-  - claim → logs → artifacts → finish;
-  - masking;
-  - cancel;
-  - timeout;
-  - 409 resync.
-  - Real podman only in an `#[ignore]` test.
-
-## 8. End to end and docs (worker W8, after W1–W7)
-- **`crates/forge-web/tests/ci_e2e.rs`:**
-  1. Boot the forge and register a runner through the API.
-  2. Push a repo with `.forge/ci.toml` (two jobs, with needs, a secret and an artifact).
-  3. Drive the job with forge-runner's library API and `HostExecutor` (forge-runner exposes `lib.rs`).
-  4. Assert the commit statuses, the masked secret in the log, the artifact download, the skip on failure, and that a fork PR waits for approval.
-- **`docs/ci.md`:**
-  - the format reference with examples;
-  - runner install (rootless podman setup: subuid/subgid, `loginctl enable-linger`, a systemd user unit);
-  - the security model (fork PRs, secrets, masking limits);
-  - the runner protocol.
diff --git a/docs/ci-sandbox-v2.md b/docs/ci-sandbox-v2.md
deleted file mode 100644
index 834a52e..0000000
--- a/docs/ci-sandbox-v2.md
+++ /dev/null
@@ -1,122 +0,0 @@
-# CI sandbox v2: subordinate id mapping (contract between workers)
-
-**Goal:** jobs get a real range of uids and gids, so package managers that `chown` to other users work (`apt`, `apk add`, `useradd`, …). Container uid 0 maps to the runner's uid, and container ids `1..=N` map to the runner's `/etc/subuid` and `/etc/subgid` range. This uses the setuid helpers `newuidmap` and `newgidmap` from shadow-utils, if present. Without them, the runner falls back to the v1 single-uid mapping.
-
-The global rules in `~/.cache/forge-orch/waveb-common.md` apply.
-
-The existing sandbox is described in `docs/ci-builtin-executor.md` and `~/.cache/forge-orch/libcontainer-notes.md`. Read both.
-
-## Host facts
-- `/usr/bin/newuidmap` and `/usr/bin/newgidmap` exist.
-- The subuid range is `tahinli:524288:65536`.
-- `unshare --map-auto --map-root-user chown 1000:1000 f` works and gives host owner `525287`. That is `start + 999`, because container 0 is the runner and container 1 is `start`.
-- Tests can use this command to create files with a subordinate owner. Skip the test when it fails.
-
-## Mapping
-- **subuid mode:** container `0` maps to the runner uid (count 1), and container `1` maps to `start` (count `n`), where `n = min(count, 65536)`. The same applies to gids. Container size is `1 + n`.
-- **single mode:** today's behaviour, `0 → uid`, count 1.
-
-## Worker V-A: `crates/forge-runner/src/sandbox/idmap.rs`, plus the hidden-command dispatch
-```rust
-#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "lowercase")]
-pub enum UsernsMode { #[default] Auto, Single, Subuid }
-
-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
-pub struct IdMap { pub uid: u32, pub gid: u32, pub sub_uid: Option<(u32, u32)>, pub sub_gid: Option<(u32, u32)> } // (start, n)
-impl IdMap {
-    pub fn single() -> Self;                                      // current uid/gid, no ranges
-    pub fn resolve(mode: UsernsMode) -> Result; // see below
-    pub fn is_subuid(&self) -> bool;
-    pub fn size(&self) -> u32;                                    // 1 + n, or 1
-    pub fn describe(&self) -> String;                             // "subuid 524288+65536" | "single uid 1000"
-}
-impl Default for IdMap  // = single()
-pub fn parse_subid(content: &str, user: &str, uid: u32) -> Vec<(u32, u32)>; // match name OR numeric uid, skip comments/bad lines
-/// SINGLE-THREADED processes only. unshare(NEWUSER|NEWNS), install the maps, make "/" rec-private.
-pub fn enter_mapped_userns(map: &IdMap) -> Result<(), IdMapError>;
-/// ` __sandbox-rm `, IdMap JSON on stdin: enter the userns, give dirs u+rwx, remove_dir_all. Exit 0, or 125 + "forge-sandbox: " line.
-pub fn rm_helper_main(args: &[OsString]) -> i32;
-/// Blocking. Single mode: remove_dir_all with a chmod-u+rwx retry, no spawn. Subuid mode: run ` __sandbox-rm ` with the map on stdin.
-/// Missing path = Ok.
-pub fn remove_tree(map: &IdMap, path: &Path, exe: &Path) -> io::Result<()>;
-```
-
-**`resolve`**
-- **Auto:** use subuid when all of these hold:
-  - `newuidmap` and `newgidmap` exist in `/usr/bin`, `/bin`, `/usr/sbin` or `/sbin`;
-  - `/etc/subuid` and `/etc/subgid` each have an entry for the user (by name, from `getpwuid`, or by numeric uid);
-  - that entry has `count >= 65536`. Take the first such range. A smaller range is accepted with a warning only if it is ≥ 1000.
-
-  Otherwise use single.
-- **Subuid:** return an error instead of falling back.
-- **Single:** `single()`.
-
-**`enter_mapped_userns`, subuid mode**
-1. Before unsharing, create a pipe and fork a child. The child blocks reading the pipe.
-2. The parent runs `unshare(CLONE_NEWUSER | CLONE_NEWNS)`, then writes one byte.
-3. The child runs these commands:
-   - `newuidmap  0  1 1  `
-   - `newgidmap  0  1 1  `
-
-   It runs them via `std::process::Command` (the child is single-threaded, so this is allowed), then `_exit`s with 0 or 1.
-4. The parent waits with `waitpid` and checks the status. On failure it returns an error including newuidmap's stderr.
-5. **Do NOT write `setgroups deny`**, because newgidmap needs `allow`. After mapping, call `setgroups(&[])`. Then make the mounts rec-private as today.
-
-**Single mode** keeps today's code: `setgroups deny` and direct map writes. Move it here from `helper.rs`; the helper then calls `enter_mapped_userns`.
-
-**Dispatch:**
-- `cli::is_sandbox_invocation()` becomes true for any argv[1] starting with `__sandbox`.
-- Add `pub fn hidden_main() -> i32` in `cli.rs`, which routes:
-  - `__sandbox` → `sandbox::helper_main()`
-  - `__sandbox-rm` → `idmap::rm_helper_main`
-  - `__sandbox-unpack` → `crate::oci::unpack_helper_main()`. This belongs to V-C; if it doesn't exist yet, add a stub returning 125 in `oci/mod.rs` that V-C replaces.
-- Use `hidden_main` from `cli::main_with_args`, `forge-runner`'s `main.rs` and forge-web's `main.rs`.
-
-**Tests**
-- `parse_subid` cases.
-- `size` and `describe`.
-- `resolve(Auto)` on this host yields subuid.
-- An integration test in `tests/sandbox.rs` (or a new `tests/idmap.rs`) that runs `forge-runner __sandbox-rm` on a TempDir holding a file chowned to 1000 by `unshare --map-auto --map-root-user`. The dir must be gone afterwards. Skip when `unshare --map-auto` fails.
-
-## Worker V-C: images with real ownership, in `crates/forge-runner/src/oci/`
-- **`unpack_layers` gains a `ownership: Ownership` parameter:**
-  - `pub enum Ownership { Flatten, Preserve { size: u32 } }`.
-  - `Flatten` is today's behaviour.
-  - `Preserve`:
-    - `lchown` every entry, including symlinks, to the tar header uid and gid.
-    - Ids `>= size` become 0 and are counted in `UnpackStats.remapped_ids`.
-    - setuid and setgid are still stripped.
-    - Directories get their exact mode at the end, deepest first, instead of `mode | 0o700`.
-  - Update all callers and tests.
-- **`ImageStore::with_idmap(map: IdMap, helper_exe: PathBuf)`:**
-  - When the map is subuid, the rootfs dir is `rootfs/-s-`, so a changed range re-unpacks. Single keeps `rootfs/`.
-  - Unpacking in subuid mode runs ` __sandbox-unpack` from `spawn_blocking`. The JSON `UnpackRequest { map, rootfs, layers, max_bytes }` goes on stdin and `UnpackStats` JSON comes back on stdout.
-  - `pub fn unpack_helper_main() -> i32` (in `oci/mod.rs` or a new `oci/helper.rs`):
-    - reads the request;
-    - calls `idmap::enter_mapped_userns`;
-    - calls `unpack_layers(.., Ownership::Preserve { size: map.size() })`;
-    - prints the stats and exits 0, or 125 with a "forge-sandbox:" line.
-- **GC and staging cleanup** remove trees with `idmap::remove_tree(&map, path, &helper_exe)`, because subuid-owned files can't be deleted by the runner directly.
-- **Tests:**
-  - `Preserve` unit tests that only check the remapping logic (a pure function, `fn map_id(id, size) -> (u32, bool)`).
-  - Path naming per mode.
-  - An integration test that unpacks a crafted layer with a file owned by 1000:1000 through `forge-runner __sandbox-unpack`, then checks that the host owner is `start + 999`. Skip when subuid is unavailable.
-
-## Worker V-B, after V-A: sandbox, executor, config, check, docs
-- **`SandboxRequest`** gains `#[serde(default)] pub idmap: IdMap`. The helper calls `idmap::enter_mapped_userns(&req.idmap)`. The container spec's uid and gid mappings become a single line each, `0 0 `, which is relative to the helper's namespace.
-- **Workspace ownership:** after the job ends, the helper (still root in the userns) walks `req.workspace` without following symlinks and `lchown`s every entry whose uid or gid is not 0 to 0:0. The host runner then owns everything for artifacts and cleanup.
-- **Executor:** `reap_job` and any job-dir cleanup use `idmap::remove_tree`. `BuiltinExecutor` gets the map.
-- **Config:** `[sandbox] userns = "auto" | "single" | "subuid"` (default auto). It is resolved once at startup, logs `describe()`, and is passed to `ImageStore::with_idmap` and `BuiltinExecutor`. A failure to resolve in subuid mode is a startup error.
-- **`forge-runner check`:** prints the mode. In subuid mode it also checks that a probe job can `chown 1000:1000` a file in `/tmp`.
-- **docs/ci.md:**
-  - replace the single-uid caveat with the v2 behaviour;
-  - document the requirements: shadow-utils `newuidmap`/`newgidmap` and an `/etc/subuid` and `/etc/subgid` entry (`usermod --add-subuids 100000-165535 --add-subgids 100000-165535 `);
-  - document the fallback;
-  - explain that cached image files on the host are owned by subordinate ids.
-- **Tests (`tests/sandbox.rs`, skip when subuid is unavailable):**
-  - a job that does `touch /tmp/f && chown 1000:1000 /tmp/f && stat -c '%u %g' /tmp/f` prints `1000 1000`;
-  - `cat /proc/self/uid_map` has size `1 + n`;
-  - a job that creates `/workspace/a` and chowns it to 1000 leaves `a` owned by the runner uid on the host;
-  - the job dir is gone afterwards;
-  - all existing single-mode tests still pass, with the map forced to single.
diff --git a/docs/ci.md b/docs/ci.md
index a5b87b3..ba18659 100644
--- a/docs/ci.md
+++ b/docs/ci.md
@@ -274,6 +274,7 @@ labels = ["linux", "x86_64"]
 work_dir = "/home/ci/.cache/forge-runner/work"
 concurrency = 1
 executor = "builtin"   # or "podman"
+auto_update = true     # replace the runner binary with the forge's when idle
 
 [limits]
 memory = "4g"       # the job cgroup's memory.max, or podman --memory
@@ -290,6 +291,12 @@ username = "bot"
 password = "..."    # keep private, the file is mode 0600
 ```
 
+`auto_update` (default `true`) lets the runner keep its binary in step with the forge. Claim
+responses tell the runner which binary the forge serves. When it differs from the runner's, and no
+jobs are running, the runner stops claiming, replaces its binary, and exits with status 75 so systemd
+restarts it. It is skipped when the forge's binary is for a different OS or architecture. Set
+`auto_update = false` to pin the binary by hand.
+
 `concurrency` is the number of jobs run in parallel. The default is 1. Each job runs with no
 capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp
 profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`.
diff --git a/docs/m1-interfaces.md b/docs/m1-interfaces.md
deleted file mode 100644
index 2cf25ed..0000000
--- a/docs/m1-interfaces.md
+++ /dev/null
@@ -1,197 +0,0 @@
-# Milestone 1: shared interfaces (contract between workers)
-
-Every worker codes against these names and signatures. If a signature must change, keep the change minimal and say so in your report.
-The full plan is at `/home/tahinli/.claude/plans/purring-prancing-wirth.md`. The research behind it is in `docs/research.md`.
-
-## Global rules
-- Edition 2024, resolver 3. **Every dependency at its latest release**, added with `cargo add` into `[workspace.dependencies]`; crates use `{ workspace = true }`.
-- No `unsafe`. No `unwrap()`/`expect()` in non-test code, except at boot with a clear message.
-- Errors: `thiserror` inside library crates, `forge_core::Error` across crates.
-- IDs are ULID strings (`ulid` crate). Timestamps are UTC RFC 3339 strings with 9 fractional digits and a `Z` suffix, produced by `forge_core::time::now_stamp()`.
-- Never invoke a shell. Never pass user input to git except through `forge_git::GitCommand`.
-
-## Module and file ownership
-```
-crates/forge-core/src/
-  lib.rs           mod declarations + re-exports
-  error.rs         Error enum
-  time.rs          now_stamp(), stamp_after(Duration)
-  model.rs         domain types (below)
-  config.rs        Config + load()
-  secret.rs        load_or_create_key(), seal(), open()
-  names.rs         normalize_name(), validate_name(), RESERVED
-  password.rs      hash_password(), verify_password()
-  token.rs         generate_token(), hash_token(), constant_time_eq()
-  session.rs       new_session_token(), new_csrf_token()
-  authz.rs         Action, Denied, authorize()
-  store/mod.rs     Store (all DB methods)
-  store/migrate.rs migration runner (schema_migrations table)
-crates/forge-core/migrations/0001_init.sql
-
-crates/forge-git/src/
-  lib.rs, error.rs
-  command.rs       GitCommand builder
-  version.rs       git_version(), require_min_version()
-  pktline.rs       encode/flush helpers
-  repo.rs          repo_path(), init_bare(), list_branches()
-  setup.rs         write_managed_gitconfig(), write_hook_shims()
-  service.rs       GitService, service_command()
-
-crates/forge-ssh/src/
-  lib.rs, error.rs
-  backend.rs       GitBackend trait
-  parse.rs         parse_exec()
-  server.rs        run(), host key load/create, russh Handler
-
-crates/forge-web/src/
-  main.rs          arg dispatch: serve (default) | hook  | admin create-user
-  boot.rs          serve(): config, store, git checks, gitconfig/hooks, routers, ssh task
-  state.rs         AppState
-  auth.rs          session cookie, current_user(), CSRF check, Basic-auth parse, token auth
-  git_http.rs      smart-HTTP routes
-  internal.rs      internal hook API router (unix socket)
-  hook_cmd.rs      `hook` subcommand client
-  ssh_backend.rs   impl forge_ssh::GitBackend
-  admin_cli.rs     `admin create-user`
-  views/mod.rs     layout + shared view helpers
-  pages/{setup,login,dashboard,repo,new_repo,settings_keys,settings_tokens,settings_sessions,admin_users}.rs
-```
-
-## forge-core types
-```rust
-pub type Id = String;
-pub enum Visibility { Public, Private }               // stored as "public" / "private"
-pub enum Role { Read, Triage, Write, Maintain, Admin } // stored lowercase
-pub struct User { pub id: Id, pub username: String, pub email: Option, pub password_hash: String, pub is_admin: bool, pub created_at: String }
-pub struct Repo { pub id: Id, pub owner_id: Id, pub owner_name: String, pub name: String, pub description: String, pub visibility: Visibility, pub default_branch: String, pub archived: bool, pub created_at: String }
-pub struct SshKey { pub id: Id, pub user_id: Id, pub title: String, pub algorithm: String, pub key_blob: Vec, pub fingerprint: String, pub created_at: String, pub last_used_at: Option }
-pub struct AccessToken { pub id: Id, pub user_id: Id, pub name: String, pub scopes: Vec, pub expires_at: Option, pub created_at: String, pub last_used_at: Option }
-pub struct Session { pub id: Id, pub user_id: Id, pub csrf_token: String, pub created_at: String, pub expires_at: String, pub last_seen: String, pub user_agent: Option }
-```
-`key_blob` is the raw SSH wire-format public key blob, the bytes base64-encoded in an `authorized_keys` line. Lookup is an exact byte comparison.
-
-## forge-core functions
-```rust
-// config.rs
-pub struct Config { pub database: PathBuf, pub data_dir: PathBuf, pub listen: SocketAddr, pub base_url: String,
-                    pub user_content_base_url: String, pub ssh_listen: SocketAddr, pub ssh_public_host: String,
-                    pub ssh_public_port: u16, pub registration: Registration }
-pub enum Registration { Closed, Invite, Open }
-impl Config { pub fn load(path: &Path) -> Result }   // writes dev defaults if the file is missing
-
-// secret.rs (XChaCha20-Poly1305)
-pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]>  // 0600, 32 random bytes
-pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> String     // "v1:" + base64(nonce || ciphertext)
-pub fn open(key: &[u8; 32], sealed: &str) -> Result>
-
-// names.rs
-pub fn normalize_name(input: &str) -> String                // NFKC + lowercase
-pub fn validate_name(input: &str) -> Result         // returns the folded name or Error::InvalidName
-
-// password.rs (argon2id)
-pub fn hash_password(pw: &str) -> Result
-pub fn verify_password(pw: &str, hash: &str) -> bool
-
-// token.rs
-pub fn generate_token() -> String                           // "forge_" + base64url(32 random bytes)
-pub fn hash_token(token: &str) -> String                    // hex sha256
-pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool
-
-// session.rs
-pub fn new_session_token() -> String                        // base64url(32 random bytes)
-pub fn new_csrf_token() -> String
-
-// authz.rs (pure, no IO)
-pub enum Action { Read, Write, Admin }
-pub enum Denied { NotFound, Forbidden }                     // NotFound when the actor can't even see the repo
-pub fn authorize(actor: Option<&User>, repo: &Repo, collaborator_role: Option, action: Action) -> Result<(), Denied>
-// Rules: owner or instance admin → all. Public repo → Read for anyone, including anonymous.
-// Private repo with no role → NotFound. Role Read/Triage → Read. Write/Maintain → Read+Write. Admin → all.
-// Can see but lacks the right → Forbidden. Archived repos deny Write (Forbidden).
-```
-
-## forge-core Store (async, `Clone`, wraps the turso connection)
-```rust
-impl Store {
-  pub async fn open(path: &Path) -> Result;           // WAL, synchronous=FULL, foreign_keys=ON, busy_timeout, runs migrations
-  // users
-  pub async fn user_count(&self) -> Result;
-  pub async fn create_user(&self, username: &str, email: Option<&str>, password_hash: &str, is_admin: bool) -> Result;
-  pub async fn user_by_id(&self, id: &str) -> Result>;
-  pub async fn user_by_username(&self, username: &str) -> Result>;   // normalized lookup
-  pub async fn list_users(&self) -> Result>;
-  // sessions
-  pub async fn create_session(&self, user_id: &str, token_hash: &str, csrf_token: &str, expires_at: &str, user_agent: Option<&str>) -> Result;
-  pub async fn session_by_token_hash(&self, token_hash: &str) -> Result>;  // only unexpired
-  pub async fn touch_session(&self, id: &str) -> Result<()>;
-  pub async fn delete_session(&self, id: &str) -> Result<()>;
-  pub async fn delete_user_sessions(&self, user_id: &str) -> Result<()>;
-  pub async fn list_sessions(&self, user_id: &str) -> Result>;
-  // ssh keys
-  pub async fn add_ssh_key(&self, user_id: &str, title: &str, algorithm: &str, key_blob: &[u8], fingerprint: &str) -> Result;
-  pub async fn ssh_key_by_blob(&self, key_blob: &[u8]) -> Result>;
-  pub async fn list_ssh_keys(&self, user_id: &str) -> Result>;
-  pub async fn delete_ssh_key(&self, user_id: &str, key_id: &str) -> Result;
-  pub async fn touch_ssh_key(&self, key_id: &str) -> Result<()>;
-  // tokens
-  pub async fn create_token(&self, user_id: &str, name: &str, token_hash: &str, scopes: &[String], expires_at: Option<&str>) -> Result;
-  pub async fn token_by_hash(&self, token_hash: &str) -> Result>;  // only unexpired
-  pub async fn list_tokens(&self, user_id: &str) -> Result>;
-  pub async fn delete_token(&self, user_id: &str, token_id: &str) -> Result;
-  pub async fn touch_token(&self, token_id: &str) -> Result<()>;
-  // repos
-  pub async fn create_repo(&self, owner_id: &str, name: &str, description: &str, visibility: Visibility, default_branch: &str) -> Result;
-  pub async fn repo_by_owner_and_name(&self, owner: &str, name: &str) -> Result>;  // normalized; a trailing ".git" on name stripped by caller
-  pub async fn repo_by_id(&self, id: &str) -> Result>;
-  pub async fn list_repos_by_owner(&self, owner_id: &str) -> Result>;
-  pub async fn set_repo_archived(&self, repo_id: &str, archived: bool) -> Result<()>;
-  pub async fn collaborator_role(&self, repo_id: &str, user_id: &str) -> Result>;
-  // events
-  pub async fn record_push_event(&self, repo_id: &str, actor_id: &str, ref_name: &str, old_oid: &str, new_oid: &str, protocol: &str) -> Result<()>;
-}
-```
-
-## forge-git
-```rust
-pub struct GitEnv { pub git_bin: PathBuf, pub data_dir: PathBuf }   // gitconfig at data_dir/gitconfig, hooks at data_dir/hooks
-pub struct GitCommand { .. }
-impl GitCommand {
-  pub fn new(env: &GitEnv, subcommand: &'static str) -> Self;  // env_clear(); PATH=/usr/bin:/bin; HOME=data_dir; GIT_CONFIG_NOSYSTEM=1; GIT_CONFIG_GLOBAL=data_dir/gitconfig
-  pub fn arg(self, a: &'static str) -> Self;                   // trusted static flags only
-  pub fn git_dir(self, p: &Path) -> Self;                      // --git-dir=

, placed before the subcommand - pub fn user_revs(self, revs: &[&str]) -> Self; // appends --end-of-options then the revs; rejects revs starting with '-' - pub fn paths(self, paths: &[&str]) -> Self; // appends -- then the paths - pub fn env(self, k: &'static str, v: impl AsRef) -> Self; - pub fn into_tokio(self) -> tokio::process::Command; -} -pub fn repo_path(data_dir: &Path, repo_id: &str) -> PathBuf; // data_dir/repos///.git (lowercased ULID) -pub async fn init_bare(env: &GitEnv, path: &Path, default_branch: &str) -> Result<()>; -pub async fn list_branches(env: &GitEnv, path: &Path) -> Result>; -pub async fn git_version(env: &GitEnv) -> Result<(u32, u32, u32)>; -pub async fn require_min_version(env: &GitEnv, min: (u32, u32, u32)) -> Result<()>; // min (2,38,0) -pub fn write_managed_gitconfig(data_dir: &Path) -> Result<()>; -pub fn write_hook_shims(data_dir: &Path, forge_bin: &Path) -> Result<()>; // pre-receive, post-receive; 0755 -pub enum GitService { UploadPack, ReceivePack } // "git-upload-pack" / "git-receive-pack" -impl GitService { pub fn from_name(s: &str) -> Option; pub fn name(&self) -> &'static str; } -pub fn service_command(env: &GitEnv, svc: GitService, repo: &Path, stateless_rpc: bool, advertise_refs: bool, git_protocol: Option<&str>) -> GitCommand; -pub fn pkt_line(data: &str) -> Vec; pub const FLUSH_PKT: &[u8] = b"0000"; -``` - -## forge-ssh -```rust -pub struct SshConfig { pub listen: SocketAddr, pub host_key_path: PathBuf, pub auth_timeout: Duration, pub inactivity_timeout: Duration } -pub trait GitBackend: Send + Sync + 'static { - /// Exact-match lookup of the raw public key blob → user id - fn authenticate_key(&self, algorithm: &str, key_blob: &[u8]) -> impl Future> + Send; - /// Authorize and build the git process (stdin/stdout piped by the caller). Err → message sent on stderr, exit 1. - fn prepare(&self, user_id: &str, service: forge_git::GitService, repo_path: &str, git_protocol: Option<&str>) - -> impl Future> + Send; -} -pub fn parse_exec(cmd: &str) -> Result<(forge_git::GitService, String), ParseError>; // "git-upload-pack '/owner/repo.git'" -pub async fn run(config: SshConfig, backend: Arc) -> Result<()>; -``` - -## Hook protocol (forge-web internal API, over a unix socket at data_dir/internal.sock) -- receive-pack runs with these env vars: `FORGE_INTERNAL_SOCKET`, `FORGE_INTERNAL_TOKEN`, `FORGE_ACTOR_ID`, `FORGE_REPO_ID`, `FORGE_PROTOCOL` (`http` | `ssh`). -- `forge-web hook pre-receive|post-receive` reads stdin lines ` `. It POSTs JSON `{repo_id, actor_id, protocol, updates:[{old,new,ref}], quarantine_env:{GIT_QUARANTINE_PATH, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES}}` to `/hook/pre-receive` or `/hook/post-receive`, with header `X-Forge-Internal-Token`. -- Response JSON is `{allow: bool, message: String}`. The hook prints `message` to stderr and exits 0 if allowed, 1 if not. diff --git a/docs/m2-interfaces.md b/docs/m2-interfaces.md deleted file mode 100644 index a7faef6..0000000 --- a/docs/m2-interfaces.md +++ /dev/null @@ -1,101 +0,0 @@ -# Milestone 2: repo browsing and the raw domain (contract between workers) - -Scope comes from `docs/architecture.md` §5.5, §7.4 and "M2". Global rules from `docs/m1-interfaces.md` still apply: latest dependencies added to root `[workspace.dependencies]` with `{ workspace = true }` in crates, no shell, no unwrap in non-test code, and clippy `-D warnings` must be clean. - -## Rules for user-supplied revisions -- **The git CLI only ever receives full hex OIDs.** User input like a branch, tag or short SHA is resolved to a full commit OID first with `browse::resolve_commit` (gix, in-process). -- Accepted rev input is either a ref name that exists under `refs/heads/` or `refs/tags/`, or a 4–64-char hex OID prefix. Anything else (`..`, `@{`, `:`, `^`, `~`, a leading `-`, control characters) resolves to `None`. -- Paths inside a repo are `/`-separated, with no empty segment, `.` or `..`, no NUL, and at most 4096 bytes. -- **Symlinks:** blobs are read from the object database, never from the filesystem, so symlinks can't be followed. A symlink entry (mode 120000) is shown as its target text and is never resolved. - -## forge-git/src/browse.rs (gix, blocking; callers use `tokio::task::spawn_blocking`) -```rust -pub enum RefKind { Branch, Tag } -pub struct RefInfo { pub name: String, pub full_name: String, pub target: String, pub kind: RefKind } // target = peeled commit oid -pub fn list_refs(repo: &Path) -> Result>; -pub fn default_branch_commit(repo: &Path, branch: &str) -> Result>; -pub fn resolve_commit(repo: &Path, rev: &str) -> Result>; // full commit oid -/// "feature/x/src/main.rs": longest existing branch/tag prefix wins; else a leading hex oid segment. -/// Returns (ref_as_given, commit_oid, path) with path possibly "". -pub fn split_ref_and_path(repo: &Path, rest: &str) -> Result>; -pub enum EntryKind { Blob, Executable, Symlink, Tree, Submodule } -pub struct TreeEntry { pub name: String, pub kind: EntryKind, pub oid: String, pub size: Option } -pub fn read_tree(repo: &Path, commit: &str, path: &str) -> Result>>; // dirs first, then name order -pub struct BlobData { pub oid: String, pub kind: EntryKind, pub size: u64, pub data: Vec, pub truncated: bool, pub is_binary: bool } -pub fn read_blob(repo: &Path, commit: &str, path: &str, max_bytes: usize) -> Result>; -pub struct CommitInfo { pub oid: String, pub parents: Vec, pub author_name: String, pub author_email: String, - pub author_time: i64, pub committer_name: String, pub committer_email: String, pub committer_time: i64, - pub summary: String, pub message: String } -pub fn read_commit(repo: &Path, oid: &str) -> Result>; -pub fn validate_repo_path(path: &str) -> Result<()>; // the rules above -``` -`is_binary` means a NUL byte appears in the first 8000 bytes. - -## forge-git/src/history.rs (git CLI, async, OIDs only) -```rust -pub async fn log(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>, skip: usize, limit: usize) -> Result>; -pub enum DiffStatus { Added, Deleted, Modified, Renamed, Copied, TypeChanged } -pub enum LineKind { Context, Add, Del, NoNewline } -pub struct DiffLine { pub kind: LineKind, pub old_no: Option, pub new_no: Option, pub text: String } -pub struct Hunk { pub header: String, pub lines: Vec } -pub struct FileDiff { pub old_path: Option, pub new_path: Option, pub status: DiffStatus, - pub is_binary: bool, pub additions: u32, pub deletions: u32, pub hunks: Vec, pub truncated: bool } -pub struct DiffLimits { pub max_files: usize, pub max_lines_per_file: usize, pub max_total_lines: usize } -pub struct CommitDiff { pub files: Vec, pub truncated_files: bool } -pub async fn commit_diff(env: &GitEnv, repo: &Path, oid: &str, limits: DiffLimits) -> Result; - // vs first parent (root commit vs empty tree), rename detection -M, --no-color, --no-ext-diff, --no-textconv -pub async fn last_commits(env: &GitEnv, repo: &Path, commit: &str, dir: &str, names: &[String], max_walk: usize) - -> Result>; // one `git log` walk, not N calls -pub enum ArchiveFormat { TarGz, Zip } -pub fn archive_command(env: &GitEnv, repo: &Path, commit: &str, format: ArchiveFormat, prefix: &str) -> Result; -``` - -## forge-core/src/raw_token.rs (signed URLs for private raw files) -```rust -pub fn sign_raw(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> String; // "." -pub fn verify_raw(key: &[u8; 32], token: &str, repo_id: &str, now_unix: i64) -> bool; // constant-time; rejects expired -``` -The key is derived for this purpose: HMAC over `"raw-v1:" + repo_id + ":" + expires`. - -## forge-web/src/render/ (pure functions) -```rust -// markdown.rs: comrak (GFM: tables, tasklists, strikethrough, autolink, footnotes, alerts), then ammonia -pub struct LinkContext { pub tree_base: String, pub blob_base: String, pub raw_base: String } // each ends at the current dir, with no trailing slash -pub fn render_markdown(src: &str, ctx: Option<&LinkContext>) -> String; -// Relative links: page links go to blob_base/tree_base, images to raw_base. Absolute http(s) and mailto are kept; -// any other scheme is dropped. Headings get id="user-content-". No inline styles (the CSP has no 'unsafe-inline'). -// highlight.rs: syntect with ClassedHTMLGenerator (class-based, never inline style) -pub fn highlight_lines(file_name: &str, text: &str) -> Option>; // one HTML fragment per line; None if unknown or >512 KiB or >20k lines -pub fn highlight_css() -> String; // light + dark (prefers-color-scheme), served at /assets/highlight.css -``` - -## Web routes (app origin) -- `/{owner}/{repo}`: repo home. Shows the default-branch tree plus the rendered README (README.md, README, readme.markdown), or the empty-repo help. -- `/{owner}/{repo}/tree/{*rest}`: a directory listing with the last commit per entry. A breadcrumb links each path segment. The branch/tag selector is a plain list of links. -- `/{owner}/{repo}/blob/{*rest}`: a file view. - - Text files are highlighted with line numbers and `#L12` anchors. - - Markdown files are rendered, with a toggle to see the source. - - Images get an `` that points at the **raw origin**. - - Binary files get a "download raw" link. - - Large files are truncated with a link to raw. -- `/{owner}/{repo}/commits/{*rest}`: commit history for a ref and optional path, paginated with `?page=`, 50 per page. -- `/{owner}/{repo}/commit/{oid}`: commit metadata plus the diff (file list with stats, unified hunks). Large or binary diffs are collapsed. -- `/{owner}/{repo}/archive/{ref}.tar.gz` and `.zip`: streamed, with `Content-Disposition: attachment`. -- `/{owner}/{repo}/branches` and `/{owner}/{repo}/tags`. -- Every route authorizes Read through `forge_core::authz::authorize`. A missing repo or one the user can't see returns **404**. - -## Raw origin (separate listener `user_content_listen`, explicit routes, NOT `.discover()`) -- `GET /{owner}/{repo}/{*rest}`: `rest` is `/`, split with `split_ref_and_path`. -- Public repo: no auth. Private repo: requires `?token=` that passes `verify_raw` (the app embeds signed links valid for 10 min). No cookies are read or set on this origin. -- Headers: - - `X-Content-Type-Options: nosniff` - - `Content-Security-Policy: default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox` - - `Cross-Origin-Resource-Policy: cross-origin` - - `Referrer-Policy: no-referrer` - - `Cache-Control: private, max-age=300` (or public for public repos) -- Content-Type: - - png, jpg, jpeg, gif, webp, avif and ico are served as their image types - - other text is `text/plain; charset=utf-8` - - everything else is `application/octet-stream` -- Additionally `Content-Disposition: attachment` for svg, html, htm, xhtml, xml and any non-image binary. -- Missing, hidden or bad token: 404. diff --git a/docs/m3-interfaces.md b/docs/m3-interfaces.md deleted file mode 100644 index 93fbc44..0000000 --- a/docs/m3-interfaces.md +++ /dev/null @@ -1,189 +0,0 @@ -# Milestone 3: issues, labels and milestones (contract between workers) - -The global rules from `docs/m1-interfaces.md` apply: latest dependencies, no unwrap in non-test code, clippy `-D warnings`, fmt, no inline styles, no JS, and every page goes through `load_repo` and `authorize`. Times are shown with `tz::format_in_tz(.., ctx.viewer_tz())` plus `views::relative_time`. Markdown goes through `render_markdown` and is embedded only via `Unescaped::new_unchecked`. - -## Permissions (forge-core `authz.rs`) -Add `Action::Triage`. It's granted to the owner, instance admins, and collaborators with role Triage, Write, Maintain or Admin. Archived repos are read-only for issues too: every issue write action returns Forbidden when `repo.archived` (handled in the pages). - -| What | Who | -|---|---| -| View issues, labels, milestones | `Action::Read` (anonymous OK on public repos) | -| Open an issue, comment | signed in **and** `Action::Read` | -| Edit/delete own comment, edit own issue title/body, close/reopen own issue | the author (signed in, still has Read) | -| Edit anyone's issue/comment, close/reopen any, set labels, assignees, milestone | `Action::Triage` | -| Create/edit/delete labels and milestones | `Action::Triage` | - -## Migration `0004_issues.sql` -```sql -ALTER TABLE repos ADD COLUMN next_issue_number INTEGER NOT NULL DEFAULT 1; - -CREATE TABLE milestones ( - id TEXT PRIMARY KEY, repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, - title TEXT NOT NULL, title_folded TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', - due_on TEXT, -- 'YYYY-MM-DD' or NULL - state TEXT NOT NULL DEFAULT 'open',-- 'open' | 'closed' - created_at TEXT NOT NULL, closed_at TEXT, - UNIQUE (repo_id, title_folded)); - -CREATE TABLE issues ( - id TEXT PRIMARY KEY, repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, - number INTEGER NOT NULL, - kind TEXT NOT NULL DEFAULT 'issue', -- 'issue' now; 'pull' in M4 (shared numbering) - title TEXT NOT NULL, body TEXT NOT NULL DEFAULT '', - state TEXT NOT NULL DEFAULT 'open', -- 'open' | 'closed' - state_reason TEXT, -- NULL | 'completed' | 'not_planned' - author_id TEXT NOT NULL REFERENCES users(id), - milestone_id TEXT REFERENCES milestones(id) ON DELETE SET NULL, - comment_count INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, updated_at TEXT NOT NULL, closed_at TEXT, - UNIQUE (repo_id, number)); -CREATE INDEX issues_repo_state ON issues(repo_id, kind, state, number); - -CREATE TABLE comments ( - id TEXT PRIMARY KEY, issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, - author_id TEXT NOT NULL REFERENCES users(id), - body TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, - edited INTEGER NOT NULL DEFAULT 0); -CREATE INDEX comments_issue ON comments(issue_id, created_at); - --- Edit history: the previous version is saved on every edit. -CREATE TABLE edit_history ( - id TEXT PRIMARY KEY, target_kind TEXT NOT NULL, -- 'issue' | 'comment' - target_id TEXT NOT NULL, old_title TEXT, old_body TEXT NOT NULL, - editor_id TEXT NOT NULL REFERENCES users(id), edited_at TEXT NOT NULL); -CREATE INDEX edit_history_target ON edit_history(target_kind, target_id, edited_at); - --- Timeline events (everything except comments). -CREATE TABLE issue_events ( - id TEXT PRIMARY KEY, issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, - actor_id TEXT REFERENCES users(id), -- NULL = system - kind TEXT NOT NULL, -- closed reopened labeled unlabeled assigned unassigned milestoned demilestoned renamed referenced - data TEXT NOT NULL DEFAULT '{}', -- JSON, e.g. {"label":"bug"} {"from":"a","to":"b"} {"commit":""} {"reason":"completed"} - created_at TEXT NOT NULL); -CREATE INDEX issue_events_issue ON issue_events(issue_id, created_at); - -CREATE TABLE labels ( - id TEXT PRIMARY KEY, repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, - name TEXT NOT NULL, name_folded TEXT NOT NULL, - color TEXT NOT NULL, -- '#rrggbb' lowercase - description TEXT NOT NULL DEFAULT '', - UNIQUE (repo_id, name_folded)); - -CREATE TABLE issue_labels (issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, - label_id TEXT NOT NULL REFERENCES labels(id) ON DELETE CASCADE, PRIMARY KEY (issue_id, label_id)); -CREATE TABLE issue_assignees (issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, - user_id TEXT NOT NULL REFERENCES users(id), PRIMARY KEY (issue_id, user_id)); -``` -`Store::delete_repo` must delete every row above for the repo in its single transaction, explicitly, child tables first. Don't rely on the engine's FK cascade. `create_repo` seeds no labels. A default label set can come later. - -**Number allocation:** in one transaction, read `next_issue_number`, insert the issue with it, then increment the counter. Numbers are never reused. - -## forge-core model (`src/issues.rs`, re-exported) -```rust -pub enum IssueState { Open, Closed } // as_str / parse: "open" | "closed" -pub enum StateReason { Completed, NotPlanned } // "completed" | "not_planned" -pub struct Issue { pub id: Id, pub repo_id: Id, pub number: i64, pub title: String, pub body: String, - pub state: IssueState, pub state_reason: Option, pub author_id: Id, - pub milestone_id: Option, pub comment_count: i64, - pub created_at: String, pub updated_at: String, pub closed_at: Option } -pub struct Comment { pub id: Id, pub issue_id: Id, pub author_id: Id, pub body: String, - pub created_at: String, pub updated_at: String, pub edited: bool } -pub struct IssueEvent { pub id: Id, pub issue_id: Id, pub actor_id: Option, pub kind: String, - pub data: serde_json::Value, pub created_at: String } -pub struct Label { pub id: Id, pub repo_id: Id, pub name: String, pub color: String, pub description: String } -pub struct Milestone { pub id: Id, pub repo_id: Id, pub title: String, pub description: String, - pub due_on: Option, pub state: IssueState, pub created_at: String, pub closed_at: Option, - pub open_issues: i64, pub closed_issues: i64 } // counts filled by list/get queries -pub struct IssueFilter { pub state: Option, pub label: Option /*name*/, - pub milestone: Option /*title*/, pub author: Option /*username*/, - pub assignee: Option /*username*/, pub query: Option /*substring of title, case-insensitive*/, - pub sort: IssueSort, pub page: u32 /*1-based*/, pub per_page: u32 } -pub enum IssueSort { Newest, Oldest, RecentlyUpdated } -pub struct IssueListItem { pub issue: Issue, pub author: String /*display username*/, - pub labels: Vec

"Home"

}) } -#[route(GET "/api/health")] -async fn health() -> Result<&'static str> { Ok("ok") } -pub fn router() -> Router { Router::builder().page(home).route(health).build() } -``` - -Builder methods: `.page(f)`, `.route(f)`, `.layout(f)`, `.layer(f)`, `.discover()`, `.build()`. Source: `REG/topcoat-router-0.10.0/src/builder.rs`. - -### 2c. Attributes - -```rust -#[route(GET "/x")] // one method -#[route([GET, POST] "/x")] // several -#[route(* "/x")] // any method; specific-method routes win over `*` -#[page] // GET, module path -#[page("/x")] // GET, explicit -#[page(POST "/x")] // POST page -``` - -Route handlers return `Result` where `T: AsyncIntoResponse`. Pages return `Result`. Parameters: optional `cx: &Cx` and at most one body extractor, in either order. Overlapping methods at the same path fail at `.build()`. - -### 2d. Path params: `/{owner}/{repo}/info/refs` - -```rust -use topcoat::{Result, context::Cx, router::{path_param, route}, view::{View, view}}; -path_param!(owner); // unparsed: path_param::(cx) -> &str (percent-decoded) -path_param!(repo); -path_param!(id: u64); // parsed with FromStr: path_param::(cx) -> Result<&u64, _> -path_param!(id2: u64, error = not_found); // error = not_found|bad_request|unauthorized|forbidden|redirect("/x") -path_param!(*rest); // catch-all: "{*rest}", path_param::(cx) -> CatchAllSegments - -#[route(GET "/{owner}/{repo}/info/refs")] -async fn info_refs(cx: &Cx) -> Result<&'static str> { - let owner: &str = path_param::(cx); - let repo: &str = path_param::(cx); - let _ = (owner, repo); - Ok("ok") -} -``` - -- `path_param!(name)` generates `Name` (Pascal-cased). Name the parameter in the path as `{name}`. Reading a parameter the route did not capture panics. -- Module form: `module_param!(post_id: u64, error = bad_request);` in `src/app/posts/post_id.rs` serves `/posts/{post_id}` (the module adds one segment). `module_param!(*path)` for catch-all. -- Source: `REG/topcoat-router-macro-0.10.0/docs/path_param.md`, `.../docs/module_param.md`. - -### 2e. Query params - -```rust -use topcoat::{Result, context::Cx, router::{page, query_params}, view::{View, view}}; -#[query_params(error = bad_request)] -struct InfoRefsQuery { service: Option } - -#[page] -async fn page(cx: &Cx) -> Result { - let q = query_params::(cx)?; // &InfoRefsQuery, memoized - Ok(view! {

(q.service.as_deref().unwrap_or(""))

}) -} -``` - -Derives `serde::Deserialize`. Works from any handler with `cx`. Source: `REG/topcoat-router-macro-0.10.0/docs/query_params.md`. - -### 2f. Registration summary - -- `module_router!()` (module-derived), `Router::builder()` (manual), `.discover()` (all explicit-path items), `.public_dir("./public")` / `.serve_dir("/p/{*f}", "./dir")` (feature `fs`, static files). - ---- - -## 3. Request access - -Import helpers from `topcoat::router::request`. All take `cx: &Cx`. - -| Need | Call | Returns | -|---|---|---| -| method | `method(cx)` | `&http::Method` | -| uri / query | `uri(cx)` | `&http::Uri` (`uri(cx).query()`) | -| headers | `headers(cx)` | `&HeaderMap` | -| content type | `content_type(cx)` | `Option<&str>` | -| all parts | `parts(cx)` | `&http::request::Parts` | -| client IP | `client_ip(cx)` | `Option` (proxy-aware) | -| peer addr | `remote_addr(cx)` | `Option` (None on Unix sockets) | -| pre-rewrite | `original_uri(cx)`, `original_headers(cx)`, ... | same types | - -`client_ip` returns the direct peer unless `.trusted_proxies(TrustedProxies::new()...)` is set on the builder. `ForwardedHeader` variant names: **UNVERIFIED** (`REG/topcoat-router-0.10.0/src/proxy.rs`). - -Body extractors (one per handler): - -| Type | Behavior | -|---|---| -| `Body` (`topcoat::router::Body`) | Streaming. Not limited. `body.into_data_stream()` yields `Result` | -| `Bytes` (`topcoat::router::request::Bytes`) | Buffered, body limit applies (413) | -| `String` | Buffered UTF-8, body limit applies | -| `Json` (`topcoat::router::content::Json`) | Requires `Content-Type: application/json` (400 otherwise); malformed = 400 | -| `Form` (`topcoat::router::content::Form`) | `x-www-form-urlencoded`. On GET/HEAD reads the query string | -| `RawForm` | Raw form bytes | -| `Multipart` (feature `multipart`) | **UNVERIFIED** field API (`REG/topcoat-router-0.10.0/docs/content/multipart.md`) | -| `Option` | Wraps any extractor to accept an absent body | - -```rust -use topcoat::{Result, context::Cx, router::{Body, route, content::Form}}; - -#[route(POST "/{owner}/{repo}/git-receive-pack")] -async fn receive(cx: &Cx, body: Body) -> Result<&'static str> { let _ = (cx, body); Ok("") } - -#[derive(serde::Deserialize)] struct NewRepo { name: String } -#[route(POST "/repos")] -async fn create(Form(input): Form) -> Result<&'static str> { let _ = input.name; Ok("created") } -``` - -Custom extractor: `impl FromRequest { async fn from_request(cx: &Cx, body: Body) -> Result }`. Delegate buffering to `Bytes` or `to_bytes(body, body_limit(cx))`. - ---- - -## 4. Responses and errors - -### 4a. Return types - -- `&'static str`, `String`, `Vec`, `Bytes`, `()` -> 200 with body. `StatusCode` -> empty body. `Body` -> as-is. `Json` -> JSON. `Response` (`http::Response`) -> full control. -- Tuples: a leading `StatusCode`, `Parts`, or `Response<()>` sets the status; middle items are `IntoResponseParts` (`HeaderMap`, `[(K, V); N]`, `Extensions`, `Option`); the last item is the body. Source: `REG/topcoat-router-0.10.0/src/response.rs`. - -```rust -use topcoat::{Result, router::{Body, HeaderMap, StatusCode, header, route}}; -#[route(GET "/{owner}/{repo}/info/refs")] -async fn info_refs() -> Result<(StatusCode, HeaderMap, Body)> { - let mut h = HeaderMap::new(); - h.insert(header::CONTENT_TYPE, "application/x-git-upload-pack-advertisement".parse().unwrap()); - Ok((StatusCode::OK, h, Body::from("001e# service=git-upload-pack\n0000"))) -} -// or: Ok((StatusCode::OK, [(header::CONTENT_TYPE, "text/plain")], Body::from("ok"))) -``` - -### 4b. Streaming from a child process - -Pattern from `REG/topcoat-router-0.10.0/src/route/directory.rs` (`fn stream`): `Body::new(StreamBody::new(stream_of_frames))`. - -```rust -use std::process::Stdio; -use futures_util::TryStreamExt; -use http_body::Frame; -use http_body_util::StreamBody; -use tokio::process::Command; -use tokio_util::io::ReaderStream; -use topcoat::{Result, router::{Body, HeaderMap, StatusCode}}; - -async fn stream_child(mut cmd: Command) -> Result<(StatusCode, HeaderMap, Body)> { - let mut child = cmd.stdout(Stdio::piped()).spawn()?; // io::Error -> 500 - let stdout = child.stdout.take().expect("piped"); - let chunks = ReaderStream::new(stdout).map_ok(Frame::::data); - Ok((StatusCode::OK, HeaderMap::new(), Body::new(StreamBody::new(chunks)))) -} -``` - -- `bytes` is re-exported as `topcoat::router::request::Bytes`. -- Caveat: `child` drops when this function returns. With `kill_on_drop(true)` the process would die immediately, so either omit it or move the `Child` into the stream (a struct owning `child` and the stream). Without `kill_on_drop`, the child is not killed on client disconnect; it exits on SIGPIPE. **UNVERIFIED** that the router does anything here. -- Request body to child stdin: `tokio_util::io::StreamReader::new(body.into_data_stream().map_err(std::io::Error::other))` then `tokio::io::copy`. - -### 4c. Errors -> status codes - -`topcoat::Result` = `Result`. Any `std::error::Error` converts with `?`. Non-router errors become **500** (body `internal server error`). Handler panics also become 500 (`REG/topcoat-router-0.10.0/src/router.rs`, `handle`). - -| Constructor (`topcoat::router::error`) | Status | Ext on `Option`/`Result` | -|---|---|---| -| `not_found()` | 404 | `ok_or_not_found()` | -| `bad_request("msg")` | 400 | `ok_or_bad_request(..)` | -| `unauthorized()` | 401 | `ok_or_unauthorized()` | -| `forbidden()` | 403 | `ok_or_forbidden()` | -| `method_not_allowed(methods)` | 405 (+ `Allow`) | - | -| `content_too_large()` | 413 | - | -| `too_many_requests(secs)` | 429 | - | -| `service_unavailable(secs)` | 503 | - | -| `redirect(uri)` | 307 | `ok_or_redirect(uri)` | -| `redirect_permanent(uri)` | 308 | `ok_or_redirect_permanent(uri)` | -| `see_other(uri)` | 303 (`SeeOther`, usable as `Ok(..)`) | - | -| `internal_server_error(e)` | 500 | - | - -```rust -use topcoat::{Result, context::Cx, router::{error::{RouterErrorExt, forbidden, see_other, SeeOther}, route}}; -#[route(POST "/repos")] -async fn create(cx: &Cx) -> Result { let _ = cx; Ok(see_other("/repos")) } -fn lookup() -> Result<&'static str> { Ok(None::<&str>.ok_or_not_found()?) } // 404 -fn gate() -> Result<()> { Err(forbidden().into()) } // 403 -``` - -Error boundary: a layout can wrap `slot` in `error_boundary(fallback: |error| ..., (slot))` and `error.downcast_ref::()` for a branded 404 (`REG/topcoat-0.10.0/docs/router.md`). - -Headers that must appear on error responses: `topcoat::router::response::response_headers(cx).append(name, value)` in a layer (`REG/topcoat-router-0.10.0/src/response/headers.rs`). - ---- - -## 5. Views, components, layouts, escaping, forms - -```rust -use topcoat::{Result, router::{Slot, layout}, view::{View, component, view, class}}; - -#[component] -async fn badge(label: &str, ok: bool) -> Result { - Ok(view! { (label) }) -} - -#[layout] // or #[layout("/settings")] -async fn root(slot: Slot<'_>) -> Result { - Ok(view! { - - - -

"Repo"

- badge(label: "New", ok: true) // component call, named args - (slot) // inner page - - - }) -} - -#[component] -async fn list(items: Vec) -> Result { - Ok(view! { -
    - for item in items.iter() {
  • (item)
  • } -
- }) -} -``` - -- Syntax: HTML tags with real names; void tags without closing; text in quotes; Rust expressions in parentheses (child and attribute position); `if`, `for`, `match`, `let` in markup; dynamic names `<(tag) (attr)="x">`; attribute names may contain `-`, `:`, `.`. Source: `REG/topcoat-view-macro-0.10.0/docs/view.md`, `.../docs/component.md`. -- Components take typed params; `Slot` for layouts; `cx: &Cx` optional, any order. -- **Escaping: yes, auto-escaped.** Text and `(expr)` interpolations escape `<`, `&`, etc., and attribute values are escaped too (tests in `REG/topcoat-view-0.10.0/src/buffer/handle.rs`, `.../src/html/attribute.rs`). Opt-out is `push_*_unescaped` and an `Unescaped` wrapper (`REG/topcoat-view-0.10.0/src/string.rs`); facade path **UNVERIFIED**. Do not wrap commit messages, file names, or diffs in it. -- Links and forms: `href!(handler_fn)` builds URLs from the handler's registered path; `href!(mod::handler, mod::Param(1))` passes params. `
` from source docs. HTML forms only send GET/POST. Source: `REG/topcoat-router-0.10.0/docs/href.md`. -- Active nav: `href.is_current(cx)` plus `class!`. -- A `#[page]` sets status or headers with a `StatusCode` or `HeaderMap` element inside `view!` (per `REG/topcoat-0.10.0/docs/router.md`; not run). For git endpoints use `#[route]` returning `Response` or a tuple. - ---- - -## 6. Cookies - -```rust -use topcoat::{cookie::RouterBuilderCookieExt, router::{Router, RouterBuilderDiscoverExt, module_router}}; -pub fn router() -> Router { module_router!().discover().cookies().build() } // required - -use topcoat::{Result, context::Cx, cookie::{Cookie, Cookies, cookies}, router::route}; -#[route(POST "/theme")] -async fn set_theme(cx: &Cx) -> Result<&'static str> { - let jar = cookies(cx); // &CookieJar; `Cookies` trait in scope - let _current = jar.get("theme"); // includes pending writes - jar.add(Cookie::build(("theme", "dark")).path("/").http_only(true).secure(true).build()); - jar.remove(Cookie::build(("theme", "")).path("/")); // same Path/Domain as when set - Ok("ok") -} -``` - -- `add`/`remove` accept `Into`, so `jar.add(("k", "v"))` works. -- Attributes: `Path`, `Domain`, `HttpOnly`, `Secure`, `SameSite`, `MaxAge`, set via builder or `cookie!("s" = "v"; Path = "/"; Secure; HttpOnly; SameSite = Lax)` (`topcoat::cookie::cookie`). -- Defaults/overrides on the jar: `cookies(cx).default_secure(true).default_http_only(true).default_same_site(SameSite::Lax).default_path("/")`. The `override_*` form forces a value. Wrap this in one helper `fn cookies(cx) -> impl Cookies`. -- `__Host-`: works. `jar.override_prefix_host()` stores `__Host-name`, forces `Secure`, `Path=/`, no `Domain`; reads strip the prefix. `override_prefix_secure()` gives `__Secure-`. Browsers reject `Secure` cookies over plain `http://` except on localhost (**UNVERIFIED** for your deployment). -- Signed/private: `signed_cookies(cx)`, `private_cookies(cx)` need a `Key` in app context: `.app_context(Key::generate())`. Calling them without a key panics. Persist the key across restarts. `cookies(cx).private(&key)` takes it explicitly. -- Typed store: `cookie_store::(private_cookies(cx), "cart").parse_or_default().update(|t| ..).commit()?`. Nothing is written until `commit()`. -- Timing: writes must happen before the handler returns. After the jar is sealed (e.g. inside a streaming body) writes **panic**. Reads still work. -- Source: `REG/topcoat-0.10.0/docs/cookie.md`, `REG/topcoat-cookie-0.10.0/src/{lib,prefix,store}.rs`. - ---- - -## 7. Layers, body limit, timeouts, compression, origin - -### 7a. Layers - -```rust -use topcoat::{Result, context::Cx, router::{Body, Next, layer, response::Response}}; -#[layer("/api")] // no path = wraps every request -async fn timing(cx: &Cx, body: Body, next: Next<'_>) -> Result { - next.run(cx, body).await -} -// register: Router::builder().layer(timing) -``` - -- Matching is by path prefix; outer = least specific. Same-path layers from `module_router!` are rejected; use explicit `.layer()` for ordering. A path-less layer also sees 404/405 as `Err` from `next.run`. Per-request values: `let cx = cx.with(value)`. -- Source: `REG/topcoat-router-0.10.0/docs/router.md`, `.../docs/layer.md`. - -### 7b. Tower (feature `tower`) - -`TowerLayer::new(mw).at("/api")`, `TowerRoute::any("/legacy/{*rest}", svc)`. Example: `TowerLayer::new(tower::timeout::TimeoutLayer::new(Duration::from_secs(5))).at("/api")`. Source: `REG/topcoat-router-0.10.0/docs/tower.md`. - -### 7c. Body limit - -- Default **2 MiB** (`REG/topcoat-router-0.10.0/src/body_limit.rs`), enforced by `Bytes`, `String`, `Json`, `Form`. Over it: **413**. `Body` is not limited. -- Override per path: - -```rust -use topcoat::router::{BodyLimit, module_router}; -let router = module_router!() - .layer(BodyLimit::max(64 << 20).at("/upload")) - .layer(BodyLimit::disable().at("/{owner}/{repo}/git-receive-pack")) // `{param}` in .at(): UNVERIFIED - .build(); -``` - -- `body_limit(cx)` returns the effective limit for custom extractors. - -### 7d. Timeouts - -- **No request, header, or idle timeout** found in router or serve code (grepped `REG/topcoat-router-0.10.0/src` and `REG/topcoat-0.10.0/src/serve.rs`). -- Only timeout: graceful shutdown, `RouterService::new(router).shutdown_timeout(d)`, default **30 s**. Request timeout, if wanted: TowerLayer with `TimeoutLayer` (7b). - -### 7e. Compression (on by default; matters for git) - -- Negotiated from `Accept-Encoding` after all layers (`REG/topcoat-router-0.10.0/src/compression.rs`). -- Streaming bodies of unknown size are always compressed. Excluded types: gRPC, images, SSE. `application/x-git-*-result` is not excluded, so pack responses would be compressed. -- Fix (applied): `Router::builder().compression(Compression::off())` on the public router, plus `crates/forge-web/src/compression.rs` (`ResponseCompression`, a tower layer). Topcoat has no per-route or content-type switch, so the policy is in that layer. See architecture.md 5.6. - -### 7f. Origin policy (CSRF guard, default on) - -- Before layers run: state-changing cross-origin browser requests and cross-origin WebSocket handshakes get **403**. Requests with no Origin or Fetch-Metadata headers pass, as do same-origin and direct navigations. -- Configure: `.origin_policy(OriginPolicy::new().trust_origins([...]))` (`REG/topcoat-router-0.10.0/src/origin.rs`). -- Git clients: expected to pass (no browser headers). **UNVERIFIED** per client. - ---- - -## 8. Shared application state (answer to the critical question) - -Shared state uses **app context**: values keyed by Rust type, registered once on the builder. Not an extension, and not a field on `Cx`. - -```rust -// src/state.rs -pub struct AppState { pub repos_root: std::path::PathBuf, pub db: std::sync::Arc } - -// router setup -pub fn router(state: AppState) -> topcoat::router::Router { - topcoat::router::module_router!().discover().app_context(state).build() -} - -// any handler/layout/component with cx -use topcoat::context::{Cx, app_context, try_app_context}; -pub fn state(cx: &Cx) -> &AppState { app_context::(cx) } // panics if missing -pub fn maybe_state(cx: &Cx) -> Option<&AppState> { try_app_context(cx) } -``` - -- Bounds: `T: Any + Send + Sync + 'static`. Duplicate type panics at registration. -- Use `Arc` inside for mutable resources (pools, locks). -- Per-request values: `request_context::(cx)` / `try_request_context`, added by a layer with `cx.with(value)`. -- Background work: `let cx = cx.clone()` and move it into `tokio::spawn`. A cloned `Cx` still reads app context, but cannot set response headers. -- Source: `REG/topcoat-0.10.0/docs/context.md`, `REG/topcoat-router-0.10.0/src/builder.rs` (`app_context`), `REG/topcoat-core-0.10.0/src/context/app_context.rs`. - ---- - -## 9. Serving - -```rust -topcoat::start(service: impl Into) -> io::Result<()> // HOST (127.0.0.1) / PORT (3000) -topcoat::serve(listener: impl Listener, service) -> io::Result<()> // Ctrl+C / SIGTERM -topcoat::serve_until(listener, service, signal: impl Future) -> io::Result<()> -``` - -Source: `REG/topcoat-0.10.0/src/serve.rs`. `Listener` is implemented for `tokio::net::TcpListener` and `tokio::net::UnixListener` (`REG/topcoat-router-0.10.0/src/listener.rs`). `Router` converts to `RouterService` via `From`. - -Two routers (public TCP, internal Unix socket) with one shared shutdown: - -```rust -use tokio::net::{TcpListener, UnixListener}; -use topcoat::router::RouterService; - -#[tokio::main] -async fn main() -> std::io::Result<()> { - let _ = std::fs::remove_file("/run/forge-internal.sock"); // stale socket is not removed for you - let tcp = TcpListener::bind("0.0.0.0:8080").await?; - let unix = UnixListener::bind("/run/forge-internal.sock")?; - let (stop, _) = tokio::sync::watch::channel(()); - let (mut a, mut b) = (stop.subscribe(), stop.subscribe()); - tokio::try_join!( - topcoat::serve_until(tcp, RouterService::new(public::router(state())), async move { let _ = a.changed().await; }), - topcoat::serve_until(unix, RouterService::new(internal::router(state())), async move { let _ = b.changed().await; }), - async { tokio::signal::ctrl_c().await?; stop.send_replace(()); Ok::<(), std::io::Error>(()) }, - )?; - Ok(()) -} -``` - -- `serve` and `start` each install their own signal handlers, so use `serve_until` for several listeners. Unix listener: `remote_addr` and `client_ip` return `None`. Placeholders (`public::router`, `state()`) are not compiled. - ---- - -## 10. Assets and CSS - -```rust -use topcoat::{Result, asset::{Asset, asset}, router::{Slot, layout}, view::{View, view}}; -const APP_CSS: Asset = asset!("assets/app.css"); // relative to CARGO_MANIFEST_DIR; "./x" is relative to the source file -#[layout] -async fn root(slot: Slot<'_>) -> Result { - Ok(view! { - - (slot) - }) -} -``` - -- Renders as `/_topcoat/assets/app-.css` (cache-safe). Build the bundle with `topcoat asset bundle` (or `topcoat dev`); output is `//assets`. -- Load before `.build()`: `module_router!().discover().assets(AssetBundle::load().unwrap()).build()`; use `AssetBundle::load_dir("dist/assets")` for a custom directory. Rendering a missing asset panics. -- Tailwind (feature `tailwind`): `build.rs` calls `topcoat::tailwind::BuildConfig::new().render().unwrap()`, then `tailwind::stylesheet!()` (`REG/topcoat-0.10.0/docs/tailwind.md`). Fixed-URL files: feature `fs`, `public_dir("./public")`. - ---- - -## 11. Testing without a socket - -```rust -use topcoat::router::{Body, Router, request::Request, to_bytes}; - -#[tokio::test] -async fn info_refs_ok() { - let router: Router = my_app::router(test_state()); - let req = Request::builder().method("GET") - .uri("/tahinli/repo/info/refs?service=git-upload-pack") - .body(Body::empty()).unwrap(); - let res = router.handle(req).await; // http::Response - assert_eq!(res.status(), 200); - let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); - assert!(!bytes.is_empty()); -} -``` - -- `Router::handle(&self, Request) -> Response`. Panics become 500. Needs no `serve` feature. -- `handle_with(request, values)` injects request-context values. `to_bytes` is exported from `topcoat::router`. - ---- - -## 12. Differences from 0.9 - -- `module_param!` is new in 0.10 (CHANGELOG: "Added: module_param! macro", PR #460). Grep found no `module_param` in `REG/topcoat-router-macro-0.9.0/src`. -- 0.10 changelog recommends the module router as the default example. -- Same names exist in 0.9 (existence checked only): `serve`, `serve_until`, `start`, `Router::handle`, `app_context`, `request_context`, `cookies`, `signed_cookies`, `cookie_store`. -- Not compared: `Cookies` trait, `Compression`, `OriginPolicy`, `TrustedProxies`, `session`. Use 0.10 source. Other 0.10 changelog items (CLI, runtime) are not relevant here. - ---- - -## 13. Forge notes - -1. Smart HTTP routes: `GET /{o}/{r}/info/refs?service=..` (query struct), `POST /{o}/{r}/git-upload-pack`, `POST /{o}/{r}/git-receive-pack`. Use explicit `#[route]` paths with `path_param!`. -2. Pack bodies: take `Body` (streaming). The 2 MiB default would reject pushes otherwise. Use `BodyLimit::disable()` or a large `max` on receive-pack. -3. Compression off on pack routes (7e). Serve pack output via `Body` from child stdout (4b). No request timeout by default (7d). -4. Repos root, config, and DB pool go in one `AppState` (section 8). -5. Web sessions: `private_cookies` with a persisted `Key`, `override_prefix_host()`, `HttpOnly`, `SameSite=Lax`. -6. Escape all user text (commit messages, paths). Never `Unescaped` for user data. -7. Internal API on a Unix socket via `serve_until` (section 9). `client_ip` is None there. - ---- - -## 14. UNVERIFIED - -- Facade path for `Unescaped`. -- Per-route compression disable (only `Compression::off()` on the builder is confirmed). -- `BodyLimit::at` accepting `{param}` segments. -- `ForwardedHeader` / `TrustedProxies` variant names. -- Multipart field API. `session` API. -- Whether the router kills child processes on client disconnect (not tested). -- Whether a 401 from `unauthorized()` sends `WWW-Authenticate`. -- Exact Origin/Fetch-Metadata headers sent by git clients. -- `HeaderMap` inside `view!` for `#[page]` headers (documented, not run). -- Sections 8, 9, 11 snippets: derived from signatures, not compiled or run. diff --git a/docs/wave-b-interfaces.md b/docs/wave-b-interfaces.md deleted file mode 100644 index 2702580..0000000 --- a/docs/wave-b-interfaces.md +++ /dev/null @@ -1,121 +0,0 @@ -# Wave B: releases, LFS, signed commits, standby replication (contracts between workers) - -The global rules apply: -- No JS and no inline styles. -- No unwrap in non-test code. -- Tests use `tempfile::TempDir`. -- Never put cargo target dirs or big files in /tmp. -- New crates go in at their latest version via `cargo add`, recorded in the root `[workspace.dependencies]`. -- User values come after `--end-of-options`. - -Migration numbers are fixed: `0020_releases`, `0021_lfs`, `0022_signatures`, `0023_replication`. Keep `store/migrate.rs` sorted. - -## 1. Releases (migration 0020) -```sql -CREATE TABLE releases (id TEXT PRIMARY KEY, repo_id TEXT NOT NULL REFERENCES repos(id), tag TEXT NOT NULL, - target_oid TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL DEFAULT '', draft INTEGER NOT NULL DEFAULT 0, - prerelease INTEGER NOT NULL DEFAULT 0, author_id TEXT NOT NULL REFERENCES users(id), created_at TEXT NOT NULL, - published_at TEXT, UNIQUE (repo_id, tag)); -CREATE TABLE release_assets (id TEXT PRIMARY KEY, release_id TEXT NOT NULL REFERENCES releases(id) ON DELETE CASCADE, - name TEXT NOT NULL, size INTEGER NOT NULL, sha256 TEXT NOT NULL, content_type TEXT NOT NULL, - download_count INTEGER NOT NULL DEFAULT 0, uploader_id TEXT NOT NULL REFERENCES users(id), created_at TEXT NOT NULL, - UNIQUE (release_id, name)); -``` -- **Storage:** - - Use the `object_store` crate (latest) with `LocalFileSystem` rooted at `/blobs`, behind a small `BlobStore` wrapper in forge-web (`put_stream`, `get_stream`, `delete`), so S3 can be added later. - - Keys are `assets/`. - - Uploads stream to a temp object while computing sha256, capped at `[releases] max_asset_mb = 512`. -- **Tags:** - - Creating a release for a tag that doesn't exist creates it as a lightweight tag at the chosen branch's head, through the existing ref update path (`after_ref_update`). - - Deleting a release keeps the tag. -- **Pages** (Write to create, edit or delete; Read to view, and drafts are visible only to Write): - - `/{o}/{r}/releases`: list, newest first, with a "Latest" badge. - - `/releases/new`, `/releases/tag/{tag}`, `/releases/{id}/edit`, `/releases/{id}/delete`. - - Asset upload is a `multipart/form-data` POST, streamed. Check what Topcoat 0.10 offers for multipart, or use the `multer` crate on the raw body. - - Downloads: `/{o}/{r}/releases/download/{tag}/{name}`. Stream with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, and increment the counter. -- **Other surfaces:** - - Source archives: link to the existing archive route if there is one. - - Webhook event `release` (`published`, `updated`, `deleted`). - - Repo home sidebar: "Latest release". -- **Cleanup:** - - `Store::delete_repo` deletes the release rows. - - The web layer deletes the blobs; the repo purge path must call it. - - Backups: the blobs dir is included in a backup set as `blobs/` (extend `backup/create.rs` and restore) **only if** it is simple. Otherwise document it in `docs/backup.md` as an rsync-safe directory (blobs are immutable; write temp, fsync, rename). - -## 2. Git LFS (migration 0021) -```sql -CREATE TABLE lfs_objects (repo_id TEXT NOT NULL REFERENCES repos(id), oid TEXT NOT NULL, size INTEGER NOT NULL, - created_at TEXT NOT NULL, PRIMARY KEY (repo_id, oid)); -``` -- **Storage:** content-addressed at `/lfs///`, shared across repos. Access is per repo through `lfs_objects`. Write temp, verify sha256 and size, fsync, rename. -- **Batch API:** `POST /{o}/{r}.git/info/lfs/objects/batch`, plus the path without `.git`. - - Content type `application/vnd.git-lfs+json`. - - Basic transfer only. Operation `download` needs Read; `upload` needs Write, and the repo must not be archived or a pull mirror. - - **Auth:** HTTP Basic with a personal access token, exactly like smart-HTTP (reuse its auth code), or anonymous for public reads. 401 sends `LFS-Authenticate: Basic realm="forge"`. - - **Response actions:** `href` points at `/{o}/{r}.git/info/lfs/objects/{oid}` (GET and PUT) with header `Authorization: RemoteAuth `. - - The token is a short-lived (1h) HMAC derived from the instance key over (repo id, oid, op, expiry), so action requests don't need the PAT again. - - Uploads also get a `verify` action. - - **Validation:** oid is 64 lowercase hex; size is at most `[lfs] max_object_mb = 2048`. -- **Transfers and verify:** - - GET streams the file. - - PUT streams to temp with a hash check, then inserts the `lfs_objects` row. - - `POST .../objects/verify` checks that the row exists and the size matches. -- **Locks API:** not implemented. Return 404 for `/locks*`, which the client handles as "locking unsupported". -- **SSH:** the `git-lfs-authenticate ` exec in forge-ssh returns JSON `{href, header: {Authorization: "RemoteAuth "}, expires_in}` with a repo-scoped token. The token is the same HMAC with op `any`, valid for both ops subject to the role check, so add a `lfs_token` helper in forge-core. -- **UI:** blob view detects LFS pointer files (`version https://git-lfs.github.com/spec/v1`) and shows "Stored with Git LFS (size)" with a download link to the media route `/{o}/{r}/media/{ref}/{path}`, which serves the LFS object, on the user-content domain if the raw route is served there. -- **Cleanup:** `delete_repo` removes rows. A GC of unreferenced files is an admin CLI, `admin lfs-gc`: a file with no row in any repo is deleted if it is older than 1 day. -- **Test:** the e2e uses the real `git lfs` binary only if it is installed; otherwise skip with a message. Unit and route tests cover the batch, PUT, GET and verify flows directly. - -## 3. Signed commit badges (migration 0022) -```sql -CREATE TABLE gpg_keys (id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), fingerprint TEXT NOT NULL UNIQUE, - armored TEXT NOT NULL, emails TEXT NOT NULL /* json array from the key's uids */, created_at TEXT NOT NULL); -CREATE TABLE commit_signatures (repo_id TEXT NOT NULL, oid TEXT NOT NULL, status TEXT NOT NULL /* verified|unverified|unsigned|unknown_key|bad */, - kind TEXT /* ssh|gpg */, signer_user_id TEXT, key_fingerprint TEXT, checked_at TEXT NOT NULL, PRIMARY KEY (repo_id, oid)); -``` -- **SSH signatures:** - - Build an allowed-signers file under `/run/allowed_signers`, rewritten atomically whenever any SSH key is added or removed. Each line is ` namespaces="git" `, for every SSH key of every user. Users' emails are on the users table. - - Verify with `git -c gpg.ssh.allowedSignersFile= verify-commit --raw `. Its output gives the principal and the fingerprint; map the fingerprint back to `ssh_keys`. - - **Verified** means a good signature, the key belongs to user U, and the committer email equals U's email. -- **GPG signatures:** - - Use a forge-managed `GNUPGHOME=/gnupg` (0700). Import every `gpg_keys.armored` on add and remove the key on delete, via the `gpg` binary. - - If `gpg` is missing, the GPG status is `unknown_key` and the settings page says GPG verification is unavailable. - - Run `verify-commit` with `gpg.program` defaulted. - - **Verified** means a good signature by a key whose fingerprint is in `gpg_keys` for a user whose key emails include the committer email. -- **Cache:** results go in `commit_signatures`. When a user's SSH or GPG keys change, delete that user's cache rows (`signer_user_id`) **and** every row with status `unknown_key`. -- **UI:** - - Settings → "GPG keys" page: add (paste armored), list with fingerprint and emails, delete. - - Commit list and commit page show a badge: "Verified" (green, title shows signer and key) or "Unverified" (signed but unmatched or bad). Unsigned commits show nothing. - - Verification is per page, for at most the 50 commits shown, using the cache. Uncached commits are verified inline with a 5s total budget; anything left unchecked shows no badge and gets checked next time. - -## 4. Standby replication (migration 0023) -The standby is a **passive SSH host**: a dedicated unix account on another provider that holds bare repos and DB snapshots. It is not a running forge. At failover, `admin restore` is run from its data (see `docs/backup.md` and architecture §8.5). - -- **Config:** -```toml -[replication] -target = "" # "user@host:/srv/forge-standby" ; empty = disabled -ssh_port = 22 -identity_file = "" # private key for the standby account (0600) -known_hosts_file = "" # pinned host key; StrictHostKeyChecking=yes always -db_snapshot_minutes = 15 -reconcile_minutes = 60 -``` -- **Transport:** - - Use the system `ssh` binary with `-i identity -o IdentitiesOnly=yes -o UserKnownHostsFile= -o StrictHostKeyChecking=yes -o BatchMode=yes -p port`. Git gets it through `GIT_SSH_COMMAND` built the same way. - - The remote base path is validated against `^/[A-Za-z0-9._/-]+$` with no `..`. - - Remote shell commands are built only from validated paths and fixed words; still quote each arg with single quotes. -- **Remote layout:** `/repos/.git`, `/db/forge-.db` (keep the newest 24), `/db/latest -> forge-.db` (symlink, updated atomically with `ln -sfn` and `mv -T`), and `/keys/` (never written by forge; the operator escrows the key). -- **Repo replication:** - - After every `after_ref_update` (debounced 5s per repo), and for every repo at each reconcile: - 1. `ssh … "git init --bare --quiet '/repos/.git'"` (idempotent); - 2. `git push --mirror --force ssh://user@host:port/repos/.git`; - 3. compute `refs_sha256` locally (`forge_git::backup::refs_checksum`) and remotely (`ssh … "git -C '' for-each-ref --format='%(objectname) %(refname)'"`, then hash it the same way locally); a mismatch triggers a re-push, and a second mismatch records an error. - - Deleted repos: delete the remote repo dir at reconcile (`rm -rf` of exactly `/repos/.git` after validation). -- **DB:** every `db_snapshot_minutes`, `Store::snapshot_to` into `/run/replica-snap.db`, `verify_snapshot`, then `scp`-equivalent via `ssh … "cat > '/db/.tmp-' && mv '/db/.tmp-' '/db/forge-.db'"`, streaming the file to stdin. Then update `latest` and prune to 24. -- **Status:** - - Table `replication_status(subject TEXT PRIMARY KEY /* 'db' or repo id */, last_ok_at TEXT, last_error TEXT, last_attempt_at TEXT, refs_sha256 TEXT)`. - - `/admin/replication` (admin): target, last DB snapshot shipped, a repos table (ok, lagging, error), a "Reconcile now" button (POST, CSRF), and audit `replication_reconcile_started`. - - The healthcheck reuses `[backup] healthcheck_url`? No: add an optional `[replication] healthcheck_url` pinged after each reconcile. -- **Test:** no real SSH in unit tests. Abstract the transport behind a trait `StandbyTransport { run(cmd) -> output, push_mirror(repo_path, remote) , upload(local, remote_path) }`, with a `LocalTransport` used in tests that maps the remote base to a local temp dir (it runs the same commands without ssh). The real `SshTransport` is unit-tested only for argument construction. -- **Docs:** a new section in `docs/backup.md`, "Standby replication", covering setting up the standby account (restricted key with `restrict` in authorized_keys), the known_hosts pin, and a failover runbook pointing at architecture §8.5. diff --git a/docs/wave-c-interfaces.md b/docs/wave-c-interfaces.md deleted file mode 100644 index 6cdbceb..0000000 --- a/docs/wave-c-interfaces.md +++ /dev/null @@ -1,248 +0,0 @@ -# Wave C: orgs, email, wiki and polish (contract between workers) - -The global rules in `~/.cache/forge-orch/waveb-common.md` apply. Background research: -- `~/.cache/forge-orch/orgs-study.md`: every place where the owner is assumed to be a user. -- `~/.cache/forge-orch/email-study.md`: the im and iz mail designs. -- `~/.cache/forge-orch/polish-audit.md`: what exists already. - -## Shared-file rules (many workers in parallel) -- **Migrations:** each worker owns exactly one number. Add one line to the array in `crates/forge-core/src/store/migrate.rs`, re-reading the file first. - - | Migration | Owner | - |---|---| - | 0025_orgs | O1 | - | 0026_mail | M1 | - | 0027_wiki | W1 | - | 0028_discussions | D1 | - | 0029_snippets | S1 | - | 0030_ui_prefs | T1 | - | 0031_advisories | A1 | - | 0032_repo_transfers | P1 | -- **Store code:** put it in a new `crates/forge-core/src/store/.rs`. Don't grow `store/mod.rs`, apart from the `mod` line and changes your section explicitly requires. -- **Shared files** (`pages/mod.rs` route lists, `views/mod.rs` (shell and repo tabs), `names.rs` reserved words, `lib.rs`, `style/main.scss`): small hunks, and re-read the file right before every edit. -- **SCSS:** each feature appends its own clearly commented block at the end of `style/main.scss`, or a partial if the file already uses partials. -- **Audit:** every state-changing action writes an audit entry, as the existing features do. Use new action names, and grep the tests that assert audit counts. One of them asserts a total (48); if you add actions, update it. -- **No JS anywhere.** Use forms and links only. -- **Tests:** unit tests in the store module, plus one e2e file per feature in `crates/forge-web/tests/_e2e.rs` using `tests/common/mod.rs`. - -## O1: organizations core (wave 1) -**Model:** an org is a row in `users` with `kind = 'org'`. That keeps one namespace (`/{name}` works for both), keeps `repos.owner_id → users(id)`, and leaves every `owner_name` join unchanged. - -**Migration `0025_orgs.sql`:** -```sql -ALTER TABLE users ADD COLUMN kind TEXT NOT NULL DEFAULT 'user' CHECK (kind IN ('user','org')); -ALTER TABLE users ADD COLUMN description TEXT; -- only if no such column exists (check 0002_profile) -CREATE TABLE org_settings (org_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - default_repo_role TEXT NOT NULL DEFAULT 'read' CHECK (default_repo_role IN ('none','read','write')), - members_can_create_repos INTEGER NOT NULL DEFAULT 1); -CREATE TABLE org_members (org_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - role TEXT NOT NULL CHECK (role IN ('owner','member')), created_at TEXT NOT NULL, - PRIMARY KEY (org_id, user_id)); -CREATE TABLE teams (id TEXT PRIMARY KEY, org_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - name TEXT NOT NULL, name_folded TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', - role TEXT NOT NULL CHECK (role IN ('read','triage','write','maintain','admin')), - all_repos INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, UNIQUE (org_id, name_folded)); -CREATE TABLE team_members (team_id TEXT NOT NULL REFERENCES teams(id) ON DELETE CASCADE, - user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, PRIMARY KEY (team_id, user_id)); -CREATE TABLE team_repos (team_id TEXT NOT NULL REFERENCES teams(id) ON DELETE CASCADE, - repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, PRIMARY KEY (team_id, repo_id)); -``` -**Org rows:** -- They get an unusable `password_hash` (`"!org"`). -- **Hard rule:** an org can never authenticate. Every authentication path must reject `kind = 'org'` explicitly: - - password login, sessions, tokens, SSH keys (including the add-key paths), LFS tokens, TOTP; - - admin `create-user`/`reset-password`/`set-username` (refuse orgs); - - the CI actor. - Add a test for each. -- The `User` struct gets `kind: AccountKind { User, Org }`, with a `is_org()` helper. - -**`store/orgs.rs`:** -- `create_org(name, creator_id)`: the creator becomes owner, and the org gets the same name validation as a username, plus `org_settings` defaults. -- `org_members`, `add_org_member`, `set_org_member_role`, and `remove_org_member`, which refuses to remove the last owner. -- Teams CRUD, team members and team repos. -- `orgs_for_user`. -- `delete_org`, which refuses while the org owns repos. -- `org_repo_role(org_id, user_id, repo_id) -> Option`: owner gives admin. Otherwise the max of `default_repo_role` (for members) and the roles of the user's teams that include the repo, or that have `all_repos`. - -**authz:** extend the existing authorization input (see `crates/forge-core/src/authz*` and its callers in `access.rs`) with `org_role: Option`, and load it in the same place collaborators are loaded. The effective role is the max of the collaborator role and the org role. An owner check (`owner_id == actor.id`) never matches an org. - -**Audit every existing site that compares `owner_id == user.id`** (orgs-study lists them: `internal.rs:526/820`, `repo.rs:282`, `admin_users.rs`, `notify.rs`) and route it through the effective role instead. - -**Notifications:** wherever "the repo owner" is a recipient, an org owner expands to the org's owners. - -**User deletion:** refuse to delete a user who is the last owner of any org. Show the message on the admin page and the CLI. - -**Tests:** -- the role math; -- auth refusal for orgs; -- the last-owner rules; -- a store-level `repo_by_owner_and_name` for an org-owned repo. - -## O2: organizations UI (wave 2, after O1) -**Routes:** the prefix `org` is already reserved. -- `GET/POST /org/new`. Allowed for everyone, unless the config `[orgs] creation = "admin"`; the default is `"all"`. -- `/org/{name}/members`: add by username (owners only), change role, remove, leave. -- `/org/{name}/teams`, `/org/{name}/teams/{team}`: members, repos, role. -- `/org/{name}/settings`: description, default role, members-can-create, delete. - -**Other pages:** -- `/{name}` (`profile.rs`): when the target is an org, show the repos visible to the viewer, the members list and the teams count. -- New repo form: an owner `