summaryrefslogtreecommitdiffstats
path: root/README.md
blob: 0bac6cab944084a4fa35b3357c4782355dfdb2bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# aur-build

A build server for AUR packages: it watches recipes, shows a human what changed,
and publishes a signed pacman repository containing **only what a human
approved**. One process, no async runtime, no external services.

## The rule everything else follows

Nothing reaches a consumer without an `approval` row behind it. Every other
behaviour is downstream of that: the review page freezes the exact bytes a human
looked at and hashes them, the approve request must echo both hashes, the build
re-checks the recipe pin and the resolved version before it runs, and publish
refuses if the accepted pointer moved underneath it.

## Quick start

```sh
cargo build --release
target/release/aur-build --root /var/lib/aur-build init --repo aur
sudo -u aurbuild target/release/aur-build --root /var/lib/aur-build serve
```

Then subscribe and drive a package through once by hand:

```sh
aur-build subscribe some-pkg
aur-build detect some-pkg          # or wait for the watcher
aur-build reviews                  # candidate ids
aur-build show 12                  # the diff panels + the two hashes
aur-build approve 12 --yes         # approves exactly what was just rendered
aur-build build 12                 # enqueue; the dispatcher picks it up on serve
aur-build packages                 # what the index is serving
```

`serve` runs the watcher, the HTTP UI, the dispatcher and the reaper in one
process. The CLI and the UI drive the same code paths, so anything the web
interface can do, an operator can do from a shell at 3am.

## Where builds run

One `sandbox` object in `config.json` says where untrusted recipe code executes.
It names exactly one kind, and a kind that is missing a field it needs — or a
kind that does not exist — is a startup error, not a fallback:

```jsonc
{ "sandbox": { "kind": "loopback" } }          // the default: subprocesses of this process

{ "sandbox": { "kind": "remote",                 // sandboxes dial in; you boot them
    "listen": "0.0.0.0:8787", "token": "…",
    "shared_workspace": true } }

{ "sandbox": { "kind": "agent-sandbox",          // Kata VMs, provisioned per lease by the cluster
    "api": "https://k8s:6443", "namespace": "builds", "bearer": "…",
    "image": "aur-build-sandbox:latest",
    "listen": "0.0.0.0:8787", "token": "…",
    "shared_workspace": true } }
```

`loopback` is the default and needs nothing, which is what keeps a fresh
`init` working with no configuration at all — and it is honest about what it is:
the sandbox is the hub's own user, with no isolation. `remote` and
`agent-sandbox` differ only in who boots the sandbox: an operator, or the
cluster from an agent-sandbox CR whose `activeDeadlineSeconds` is the lease TTL,
so the orchestrator enforces the deadline even if the hub dies.

`shared_workspace` is required (explicitly, `true`) by both remote kinds. The
build workspace is not shipped to the sandbox yet — `Run` frames carry a
hub-side working directory — so a remote build only works where the staging
directory is visible at the same path on both sides. Asserting it is what stops
`"remote"` from silently meaning "on the hub".

## Layout

Each layer may name only the layers beneath it. `tests/architecture.rs` encodes
the ranks and fails the build on an upward edge, so the order below is enforced
rather than documented in hope.

```
src/
  main.rs            CLI: init, subscribe, detect, reviews, show, approve, reject,
                     build, rebuild, run, builds, status, packages, serve, audit,
                     metrics, gc, backup — argument parsing, one use-case call,
                     and printing; no workflow of its own
  usecase/           rank 9 — the workflows both front ends run: bootstrap
                     (open/init/serve), detect, reviews (approve/reject/bulk),
                     subscriptions, builds, maintenance (gc/backup/notices)
  http/              rank 10 — tiny_http server: routes, render, auth, SSE log
                     tail; renders use-case results, holds no workflow itself
  ops.rs             retention, metrics, VACUUM INTO backups
  pipeline/          rank 7 — the step machine, the dispatcher + worker pool,
                     publishing
  watch/             rank 6 — detection: scheduler, cheap/expensive polls,
                     upstream probes, source digests, staleness; `sources` is
                     the one interface the pipeline builds against
  review/            rank 5 — candidates, diff panels, risk scoring, approval;
                     `intake::record` is the single way a candidate is recorded
  shims/             the fake toolchain that makes the pipeline testable
                     (test-support only)
  sandbox/           rank 3 — where build code runs: the backend seam, loopback,
                     remote agent protocol + agent binary, kata adapter
  db/                rank 3 — SQLite: migrations, model rows, per-aggregate
                     query modules, build state machine; `mod.rs` lists its
                     exports explicitly, and a single writer actor owns writes
  recipe.rs          rank 4 — PKGBUILD and .SRCINFO parsing
  config.rs          rank 2 — one config file at <root>/config.json
  fetch.rs, git.rs   rank 2 — the two seams over the outside world
  pkgver/, pkginfo.rs, hash.rs, time.rs, urlutil.rs
                     rank 1 — pure: vercmp and the dependency grammar, .PKGINFO
                     and .BUILDINFO parsing (no libalpm), sha256 and canonical
                     json, the clock seam, url and name shapes
  error.rs           rank 0 — the crate's error type; the six variants behavior
                     branches on carry typed payloads, not prose
testcorpus/          the fixture packages the tests build for real
templates/           askama templates, server-rendered
static/              app.css and one vendored htmx
```

Two tools keep this honest, and both are meant to be run, not read once:

```
cargo test --test architecture   # ranks, no cycles, no globs, interface budgets
python3 tools/arch-census.py     # the numbers; --list-dead names them, --budget checks the ratchet
python3 tools/arch-census.py --list-overwide  # pub(crate) items wider than anything reaches
```

Formatting and idiom are gates too, not opinions:

```
cargo fmt --all -- --check                                # rustfmt.toml: 120 columns, small items on one line
cargo clippy --all-targets --all-features -- -D warnings
cargo clippy --release --lib --bins -- -D warnings
```

`[lints.clippy]` in `Cargo.toml` names the idiom lints the tree holds itself to;
`must_use_candidate` and `missing_errors_doc` are left out on purpose, because
satisfying them would add doc-comment boilerplate rather than remove it. The
release-mode check is not a duplicate of the other: `--all-targets` pulls
`test-support` in through the dev-dependency, and an item that is `pub` under
that feature is `pub(crate)` without it — so only the release build sees what
clippy says about an item once it is crate-internal.

## Testing without root, network, or a real chroot

`cargo test` runs the whole thing on an ordinary user account. Two mechanisms
make that possible:

* **PATH shims.** `src/bin/` contains `makepkg`, `pacman`, `repo-add` and
  `gpg` — the tools the pipeline actually shells out to now that builds run
  in provisioned sandboxes — plus `mkarchroot` and `makechrootpkg`, kept as
  stand-ins for the real devtools so the shim protocol itself stays
  exercised. Pointing `path_prepend` at the directory cargo built them into
  makes the *unmodified* pipeline drive a fake toolchain: it still runs real
  subprocesses, still reads their stdout and exit codes, still gets real
  `.pkg.tar.zst` files with real `.PKGINFO` and `.BUILDINFO` inside them,
  and the fake `pacman -U` refuses bytes that do not hash to the digest
  their name claims. The step machine cannot tell it is not in a sandbox,
  which is the point. Each shim is as strict as the tool it replaces — the
  fake `repo-add` refuses a database filename the real one refuses — because a
  shim that accepts more than its tool is how a broken publish path passes 200
  tests and then fails on a real package.
* **The fixture corpus.** `testcorpus/` holds ~20 synthetic packages, each with
  a `PKGBUILD` and a manifest describing what the shims should emit: a split
  pkgbase, a build that fails, a recipe whose payload drifts under a `SKIP`
  checksum, a VCS package with a local upstream repo, a downgrade, an epoch bump,
  a package with an unsatisfiable dependency. Tests drive the real code against
  these rather than against mocks of the code.

Crash tests are real: `shim_kill_parent` makes a shim `SIGKILL` the pipeline
process mid-step, and a separate test spawns the compiled binary and kills *it*,
then asserts a fresh process resumes from the step checkpoints with no duplicate
work and the old index still byte-identical.

The sandbox seam is tested the same way — the interface is
executed, not mocked: `tests/remote_agent.rs` drives a **full build over the
real agent protocol** (frames, rendezvous, log streaming, blob round-trip,
bad-token refusal) against the shims on a loopback socket, and
`tests/failure_modes.rs` runs a `FakeBackend` that breaks sandboxes on
purpose: dies mid-run (lease expiry → reaper → requeue), TTL bites mid-build,
pool at quota (the build blocks on `sandbox-pool`, it does not fail), and a
sandbox whose `pacman -Q` lies (fail-closed world mismatch).

All of it is behind a `test-support` feature, which `cargo test` turns on through
its dev-dependency on this crate and `cargo build` does not turn on at all: the
shim binaries are not built, the `TestHooks` type has no fields, and the
fault-injection branches in `publish` are not in the binary. `tests/production_surface.rs`
fails if any of it leaks into the default build.

Some tests are gated on the host and skip themselves with a printed note rather
than failing:

* `pkgver::tests::the_live_vercmp_tier_is_recorded_not_silently_absent` needs
  pacman's `vercmp` on `PATH` and compares the hand-written comparator against it
  over ~1100 pairs. A second test, `vercmp_matches_the_recorded_oracle`, checks
  the same ~1100 pairs against a committed table, so the comparator is pinned on
  a machine with no pacman at all.
* The live kata tier needs `/dev/kvm` and a cluster (`AUR_KATA_API`); the kata
  rendezvous and TTL logic itself runs everywhere via a real `sandbox-agent`
  process with no VM. The old real-chroot tier retired with devtools.

### Where a test lives

A test goes in the module it tests, unless it needs something a unit test cannot
have — the fixture corpus, a database, a real subprocess, a listening socket.
`tests/` is for those, and `src/` holds the rest as `#[cfg(test)] mod tests`.

That is a rule with a consequence, and the consequence is the reason it is worth
stating: a test outside a module can only reach what the module exports, so every
test that sat in `tests/` while testing something module-private was quietly
keeping that thing `pub`. Moving the test home is what lets the item go private.
`tools/test-surface.py` finds the ones still outstanding and
`tools/test-surface.md` records what is being done about each.

## Operations

```sh
aur-build metrics                 # Prometheus text, same as GET /metrics
aur-build gc --keep 3             # evict files beyond the retention window
aur-build gc --keep 3 --dry-run   # show what would go
aur-build backup /backups/aur.db  # VACUUM INTO; refuses to overwrite
```

Retention never deletes a row. An evicted artifact keeps its digest, size and
provenance and gains a `purged_at`, so the database says "these bytes existed and
were dropped at T" instead of continuing to claim a file that is gone. The
currently accepted release and anything still backing an index entry are never
evicted, however old they are.

Metrics are computed from live state on every scrape — there are no counters
incremented at event sites, because a counter maintained by every code path is a
counter that quietly drifts the first time a code path is added.

## Web UI

Server-rendered HTML with at most one vendored JavaScript file (htmx, ~15.6 KB
gzipped on the wire) and no build step. The review surface ships no JavaScript
at all; a test greps the rendered page for `<script` to keep it that way.

| Surface | Path |
|---|---|
| Inbox (reviews) | `/`, `/reviews`, `/reviews/:id` |
| Builds | `/builds`, `/builds/:id`, `/builds/:id/log.txt`, `/builds/:id/log.stream` |
| Attention | `/attention` |
| Index | `/packages`, `/packages/:name` |
| Subscriptions | `/subscriptions` |
| Ops / audit | `/audit`, `/settings`, `/metrics`, `/healthz` |

Approve is a POST carrying `identity_hash` and `diff_digest`. If either no
longer matches what the candidate became while the reviewer was reading, the
server answers **409** and re-renders the current state, so a reviewer can never
approve bytes they did not see. Every POST requires a CSRF token bound
to the session; the whole site is gated behind a password by default.

## Constraints this codebase keeps

These are not suggestions:

* No `async`/`await`, no tokio. Threads and crossbeam channels; blocking HTTP
  with `tiny_http`, outbound HTTP with `ureq`.
* SQLite in WAL with exactly one writer thread reached over a channel. Readers
  are thread-local and read-only — asserted by a test. No transaction spans a
  build step.
* Git by shelling out; no libgit2.
* `vercmp` and the dependency grammar are hand-written; no libalpm. They are
  checked against pacman's own `vercmp` where that binary exists.
* Fail closed. A pin that does not match, a recipe hash that drifted, a package
  with no signature, a symlink in the srcdir: the build stops and says why. A
  change that is real but not publishable becomes a `notice` — never a candidate,
  never silently dropped.
* One direction of dependence. Every module in `src/` carries a rank in
  `tests/architecture.rs`, and a module may name only modules ranked below it,
  so the tree is written down rather than remembered. The same file holds each
  module's interface budget in `tests/architecture-budget.json`: how many `pub`
  items it hands out, and how many of them nothing outside the module ever
  names. Budgets may only shrink — a number that grows fails the suite, and a
  number that quietly got smaller has to be written back at the lower value.
  `tools/arch-census.py` prints the same numbers for a human to read, and
  `--list-dead` names every item behind them. A `pub` item that stays `pub`
  without an outside reader is allowed only by name, in the same budget file,
  with the reason beside it.
* `pub(crate)` is not the narrow state just because it is not `pub`. A
  `pub(crate)` item nothing outside its own file names is **over-wide**: it
  offers the whole crate a thing only its own file reaches, and it is one
  keystroke from being a hole. `overwide` counts them per module and is held to
  a budget exactly the way `deadonly` is — it may only shrink, and an item that
  stays `pub(crate)` is allowed only by name in `over_visibility.allowlist`,
  with the compiler fact that forces it beside it: a `pub(crate)` field cannot
  carry a private type, privacy does not reach up to a parent or across to a
  sibling module, and `pub(super)` is not a form this crate admits.
  `--list-overwide` names them. The count is a grep, so it is a lead and the
  compiler gives the verdict — and the verdict is asked under **both** profiles,
  because the `cfg(not(feature = "test-support"))` half of a feature-conditional
  declaration is never compiled by `cargo check --all-targets` and only a release
  build ever says whether it can go private.