.gitbay/wiki/Admin.org

v1.40.0
gitbay/.gitbay/wiki/Admin.org rendered · source · history · blame · raw

1313 lines · 70412 bytes

   1#+title: gitbay admin guide
   2
   3One static binary (=gitbayd=), one SQLite file, bare repositories on
   4disk, and the system =git=. Schema migrations run automatically on
   5startup and on every admin command.
   6
   7* Install
   8
   9Build from source (=go build ./cmd/gitbayd=), install via the vanity
  10module path (=go install gitbay.org/gitbay/cmd/gitbayd@latest=), or use
  11a release build: =deploy/release.sh <tag>= cross-compiles reproducible
  12linux/amd64, linux/arm64, and darwin/arm64 binaries with a SHA256SUMS
  13manifest (CGO off, trimpath, stripped — byte-identical per commit and
  14toolchain).
  15
  16#+begin_src sh
  17install -m 755 gitbayd /usr/local/bin/
  18adduser --system --group --home /var/lib/gitbay --shell /usr/sbin/nologin gitbay
  19install -d -o gitbay -g gitbay -m 750 /var/lib/gitbay
  20gitbayd --config /etc/gitbay/config.toml check-config
  21gitbayd --config /etc/gitbay/config.toml admin secrets init
  22chown gitbay:gitbay /etc/gitbay/secret.key
  23#+end_src
  24
  25=admin secrets init= refuses when the key file already exists, so a
  26reinstall on the same host should skip it — =deploy/install.sh= does
  27this with a file check before running it.
  28
  29=deploy/= in the source tree has a cloud-init file, a hardened systemd
  30unit, and a nightly backup timer. Run as the unprivileged =gitbay= user;
  31the unit's =AmbientCapabilities=CAP_NET_BIND_SERVICE= covers ports
  3222/80/443 without root.
  33
  34** The SSH port decision
  35
  36- =ssh.mode = "embedded"= (default): gitbayd itself listens, normally on
  37  22 — move the host's admin sshd to another port. Remotes read
  38  =git@host:owner/repo= with no port gymnastics.
  39- =ssh.mode = "system"=: the host sshd owns 22 and invokes gitbayd via
  40  =AuthorizedKeysCommand=:
  41  #+begin_example
  42  AuthorizedKeysCommand /usr/local/bin/gitbayd --config /etc/gitbay/config.toml authorized-keys %t %k
  43  AuthorizedKeysCommandUser gitbay
  44  #+end_example
  45  sshd requires that binary to be root-owned and not group/world
  46  writable. Unknown keys fail authentication inside sshd, so system mode
  47  requires =registration.mode = "closed"= (check-config enforces this).
  48  Under the forced command the CLI's leading =--term=<cols>[,color]=
  49  argument works as is; a client that sets =GITBAY_TERM= instead needs
  50  =AcceptEnv GITBAY_TERM= in =sshd_config=, since that env request is
  51  handled by the host's sshd, not gitbayd.
  52
  53* Configuration reference
  54
  55=/etc/gitbay/config.toml=. =check-config= validates and names every
  56contradiction; =--no-host-checks= skips port/path probes.
  57=gitbayd admin config show= prints the configuration in effect as TOML,
  58every default filled in and =smtp_pass= redacted. A file that fails
  59validation still prints, followed by the contradiction.
  60
  61** [server]
  62- =root= (default =/var/lib/gitbay=) — repositories, database, host
  63  keys, ACME cache all live here.
  64- =site_url= (required) — canonical =https://host=; drives ACME, clone
  65  URLs, mail links.
  66- =secret_key_file= (default =/etc/gitbay/secret.key=) — the keys that
  67  seal CI secrets, webhook secrets, mirror tokens and push device
  68  tokens in the database. Must be outside =root=, mode 0600, readable
  69  by the daemon's user. See "Secret key" below.
  70- =source_repo= (optional, =owner/name=) — the repository this instance
  71  develops itself in. Startup warns when the running build's commit is
  72  not on that repository's default branch, which is how a binary built
  73  from an unmerged branch stops being invisible. Leave it unset unless
  74  the instance hosts its own source.
  75
  76** [ssh]
  77- =mode= — =embedded= | =system= (above).
  78- =port= (22) — embedded listener port.
  79- =host_keys= — list of private key paths; empty generates an ed25519
  80  key at =<root>/ssh/host_ed25519=.
  81
  82** [http]
  83- =addr= (=:443=), =tls= — =acme= | =files= | =off=.
  84- =acme=: certificates via TLS-ALPN-01 on the HTTPS port, cached at
  85  =<root>/acme=; =acme_email= for the CA account; =acme_http_addr=
  86  (=:80=, ="off"= to disable) adds HTTP-01 and an https redirect —
  87  failing to bind it is a warning, not fatal. Requires an =https://=
  88  site_url with a public DNS name.
  89- =files=: =cert_file= + =key_file=.
  90- =off=: plain HTTP — development, or behind a TLS-terminating proxy.
  91- The HTTPS listener accepts TLS 1.2 and 1.3 only (=serverTLS= in
  92  =cmd/gitbayd/tls.go=), with the default cipher suites of the Go
  93  release the binary was built with. =openssl s_client -connect
  94  <host>:443 -tls1_1= fails the handshake.
  95
  96=trusted_proxies= lists the addresses or CIDRs of reverse proxies in
  97front of the daemon. A request from one of them is attributed, for API
  98rate limiting, to the last =X-Forwarded-For= hop that is not itself a
  99trusted proxy; from anyone else the header is ignored. Empty, the
 100default, is right when gitbayd terminates TLS itself.
 101
 102A reverse proxy in front of gitbay must not buffer responses, or the
 103build page's live log arrives only when the build ends;
 104=X-Accel-Buffering: no= covers nginx.
 105
 106** [web]
 107- =mode= — =view_only= (default) | =accounts=. In view_only the mutating
 108  web routes are never registered; in accounts, browser sessions are
 109  minted over SSH (=web login=), and users with write access can create
 110  repos, comment, and make simple file edits (which commit unsigned,
 111  honestly). =password_auth= is reserved and currently rejected.
 112- =title= — the instance's display name in the rail and page titles;
 113  empty falls back to the site host. Lower case is the convention for
 114  gitbay itself.
 115- =privacy_notice= — operator text shown on =/privacy= under the fixed
 116  statement.
 117
 118** [registration]
 119- =mode= — =closed= (default) | =invite= | =open=. invite/open require
 120  [mail]. See the user guide for the flows.
 121
 122- =pending_expiry= (empty, never) — a duration such as ="168h"=; a
 123  self-registered account still unverified after that long is removed,
 124  hourly and at start, audited as =pending.expired=.
 125
 126- =notify_admin= (false) — mail every instance admin when an account
 127  becomes active: an invite redeemed, or an open-mode signup that
 128  verified its address. The unverified row an open signup creates is
 129  not reported, because anyone can post the form and mailing on that
 130  would point a flood at the admins. Recipients are the verified
 131  primary addresses of active admins who have activity mail on, the
 132  same rule any other notice follows, so an admin with no verified
 133  address hears nothing. The notice is queued, so a dead SMTP host
 134  shows up in the admin page's Mail table instead of failing the
 135  registration. Requires [mail].
 136
 137** [mail]
 138- =smtp_host= (host:port; 587 assumed, 465 with =tls = "implicit"=),
 139  =from=, optional =smtp_user= / =smtp_pass=. Required for invite/open
 140  registration and self-service =email add=; in closed mode you may omit
 141  it entirely and assert addresses by hand (below).
 142- =tls= — =starttls= (default) or =implicit= (TLS from the first byte,
 143  for relays on 465).
 144- =require_tls= — with =starttls=, a relay that does not offer STARTTLS
 145  gets no mail: delivery fails and retries, and the admin page's Mail
 146  table shows the error. Unset, it is on for every relay except
 147  =localhost= and loopback addresses; set =false= to allow plaintext
 148  to a remote relay.
 149
 150** [mail.inbound]
 151Reply by mail: a reply to issue or merge request mail posts a comment
 152(#295). gitbayd polls a mailbox over IMAP; no port is opened for it.
 153Off unless =enabled=, and it requires =[mail] smtp_host=, since the
 154replies answer mail gitbayd sends.
 155
 156#+begin_src toml
 157[mail.inbound]
 158enabled       = true
 159imap_host     = "imap.example.org"       # host:port; 993, or 143 with tls = "starttls"
 160tls           = "implicit"               # or "starttls"; there is no plaintext setting
 161user          = "reply@gitbay.example"
 162password_file = "/etc/gitbay/imap.pass"  # one line, mode 0600, owned by gitbayd's user
 163mailbox       = "INBOX"                  # default
 164poll_interval = "1m"                     # default; at least 10s
 165reply_address = "reply@gitbay.example"
 166require_dkim  = true                     # recommended; see below
 167trusted_authserv_id = "mx.example.org"   # the mail host's Authentication-Results id
 168#+end_src
 169
 170- The password is read from =password_file= at every connection and
 171  never appears in the config, argv or the log. An unreadable file, or
 172  one readable by group or others, stops the daemon at start.
 173- =reply_address= is what each Reply-To is built from:
 174  =reply@gitbay.example= becomes =reply+<token>@gitbay.example=. The
 175  mailbox must receive that. Hosts that deliver subaddresses to the
 176  mailbox need nothing more; others need a wildcard rule. Migadu, for
 177  one, sent =threads+x@gitbay.org= nowhere until a rewrite from
 178  =threads+*= to =threads@gitbay.org= was added. A domain catch-all only
 179  works if it points at this mailbox, which then also holds everything
 180  else sent to the domain. Send a test to =<reply_address>+test= and
 181  expect a =refused mail reply= audit row with "malformed reply token"
 182  within a poll interval (=gitbay audit --action 'refused mail'=). Point
 183  the domain's MX at the mail host as for any other mailbox; nothing
 184  about it involves gitbayd.
 185- Use a mailbox that holds nothing else. gitbayd reads every unseen
 186  message in it and marks each one =\Seen= when it is handled, posted
 187  or refused. A message that fails for a reason that may pass (the
 188  database busy, the server refusing that one fetch) stays unseen and is
 189  tried again on the next poll, up to five times, then is marked seen
 190  and audited. A dropped connection or a timeout ends the poll and
 191  counts against no message. A
 192  message over 10 MiB is refused by its size without being fetched. A
 193  server that sends more than about 11 MiB, or more than a thousand
 194  untagged responses, for one command has its connection closed; one
 195  poll handles at most ten thousand messages.
 196- Whatever the settings, a message is refused when a header field name
 197  is not RFC 5322 =ftext= (=From : x=, a space or a non-ASCII byte in a
 198  name), when it does not have exactly one =From=, or when it has more
 199  than one =To=, =Cc=, =Message-ID=, =Content-Type= or
 200  =Content-Transfer-Encoding=.
 201- =require_dkim= (default false) should be on for any instance
 202  reachable from the internet. With it, a reply is posted only when
 203  gitbayd itself verifies one of its DKIM signatures (RFC 6376) with a
 204  =d== in relaxed alignment with the From domain (the same
 205  organizational domain by the public suffix list; =d=github.io= aligns
 206  with nothing) and an =h== that covers =From=, the =To= or =Cc= holding
 207  the reply address, =Content-Type=, and =Message-ID= when the message
 208  has one. A =Content-Transfer-Encoding= outside =h== is accepted only
 209  when it is =7bit=, =8bit= or =binary=, which leave the decoded body as
 210  it is; Thunderbird, for one, does not sign it. An unsigned
 211  =quoted-printable= or =base64= is refused. The reply
 212  address is read only from =To= or =Cc=: a reply that reached the
 213  mailbox by Bcc, with the address only in =Delivered-To=, is refused
 214  ("reply address not in To or Cc"). It needs nothing from the mail
 215  host, so it works where the host adds no =Authentication-Results=.
 216  rsa-sha256 (keys of 1024 bits or more) and ed25519-sha256 are
 217  accepted, with simple or relaxed canonicalization; rsa-sha1, a body
 218  length tag (=l==), an expired =x== and a =t== more than fifteen
 219  minutes ahead are refused. Only the first five signatures are
 220  checked. The key is looked up at =<s>._domainkey.<d>= with a
 221  five-second timeout and cached for fifteen minutes (the resolver does
 222  not report the record's TTL); a lookup that fails for a reason that
 223  may pass (a timeout, SERVFAIL) leaves the message for the next poll,
 224  up to the five tries above, while a missing key refuses it.
 225  Signatures are checked on the message as fetched. Each passing
 226  signature is recorded with the =Message-ID=, so a copy of the same
 227  signed message posts once even with unsigned fields changed.
 228- Either =require_dkim= or =trusted_authserv_id= passing is enough to
 229  authenticate =From=; when both are set, a reply needs only one of
 230  them, and a refusal names both reasons. With only
 231  =trusted_authserv_id=, the reply address may come from any recipient
 232  field (=Delivered-To=, =X-Original-To=, =Envelope-To=, =To=, =Cc=),
 233  since the mail host vouches for the sender and not for the fields.
 234  Set both when the mail host adds =Authentication-Results= for most
 235  senders but not all.
 236- =trusted_authserv_id= names the authserv-id the mail host writes at
 237  the start of its =Authentication-Results= header (Gmail's is =mx.google.com=).
 238  With it set, a reply is posted only when the topmost header with that
 239  id shows =dmarc=pass= with =header.from= equal to the From domain, or
 240  =dkim=pass= with a =header.d= in relaxed alignment with it (the same
 241  organizational domain by the public suffix list; a public suffix such
 242  as =github.io= aligns with nothing). The header is parsed per RFC
 243  8601, so text inside a quoted string or a comment (a quoted MAIL FROM
 244  local part, a reason) is never read as a result. Lower headers
 245  claiming the same id are the sender's and are not read. This is only safe when the mail host
 246  removes incoming =Authentication-Results= headers that claim its id,
 247  as RFC 8601 asks; Gmail, Fastmail and Migadu do. Check yours before
 248  relying on it. With neither this nor =require_dkim= set, the daemon
 249  logs a warning at start and =admin mail inbound check= repeats it:
 250  =From= is then whatever the sender wrote. Mail between two addresses
 251  at the same host may carry no =Authentication-Results= at all: at
 252  Migadu, mail from another
 253  Migadu-hosted domain is delivered through its outbound path and gets
 254  none, so setting the id alone refuses every reply from such users.
 255  That mail does carry a DKIM signature aligned with =From= (for
 256  example =d=cleberg.net; s=key1; a=rsa-sha256; c=simple/simple;
 257  h=from:to:subject:date:message-id:mime-version:content-type=), which
 258  is why gitbay.org sets =require_dkim= instead.
 259- =gitbay admin mail inbound check= logs in, opens the mailbox
 260  read-only (EXAMINE) and reports the message and unseen counts and how
 261  =From= is authenticated (=require_dkim=, =trusted_authserv_id=), so a
 262  check never marks a reply seen before the poller reads it. It warns
 263  when neither is set. With inbound off it says so and exits 0. Poll
 264  failures are logged as =mail reply: poll failed= with the server and
 265  the IMAP error.
 266
 267A reply is posted when all of these hold, checked when it is read:
 268
 2691. It is not an automatic reply (=Auto-Submitted=, =Precedence: bulk=
 270   and the like).
 2712. A recipient header carries a reply address whose token verifies
 272   and has not expired (thirty days from the mail it came on).
 2733. The token's account exists, is active and not disabled, still has
 274   reply by mail on, and was created before the token was: an id freed
 275   by a delete and reused is not the account the token named. The same
 276   holds for the repository.
 2774. =From= is one of that account's verified addresses, and, with
 278   =require_dkim= or =trusted_authserv_id= set, a DKIM signature
 279   gitbayd verified or the mail host's result authenticated it.
 2805. The message has a =text/plain= part (HTML-only mail is refused, not
 281   converted), and what is left after quoted text and the signature
 282   are removed is not empty and fits a comment (64 KiB).
 2836. No earlier copy of the message (same =Message-ID=, account and
 284   thread) posted.
 2857. =issue comment= or =mr comment=, dispatched as the account, accepts
 286   it: the account can still read the repository, the thread exists,
 287   the repository is not archived, the write budget is not spent.
 288
 289The comment's audit row is =cmd issue comment= (or =mr comment=) with
 290=source: mail=. A refusal writes a =refused mail reply= row with the
 291reason and the =Message-ID=, never the message's content, at most sixty
 292a minute, and sends nothing back. See Threat-Model for why the token
 293and the sender address are both required.
 294
 295** [push]
 296Push notifications to Apple devices, delivered by gitbayd talking to
 297APNs directly over HTTP/2, authenticated by an ES256 JWT signed with an
 298operator-supplied provider key. Off unless configured.
 299
 300- =enabled= (false).
 301- =key_file= — path to the =.p8= provider key from Apple's developer
 302  portal (Certificates, Identifiers & Profiles → Keys). It belongs at
 303  =/etc/gitbay/apns.p8=, mode 0600, owned by the account gitbayd runs
 304  as. Read and validated at startup: it must parse as a PEM-wrapped
 305  PKCS#8 EC (P-256) private key, or the daemon refuses to start rather
 306  than fill a queue nobody is watching.
 307- =key_id=, =team_id= — the key's id and your Apple developer team id,
 308  both from the same portal page.
 309- =topic= — the app's bundle identifier. *An APNs key belongs to a
 310  bundle ID.* gitbay.org pushes to the App Store build under its own
 311  bundle id; a self-hoster who wants push ships their own iOS build
 312  under their own bundle id, with its own =.p8= key from their own
 313  developer account, and points =topic= at that id. There is no way to
 314  push to someone else's build, by design — this is Apple's model, not
 315  gitbay's.
 316- =environment= — =production= or =sandbox=, naming the APNs host
 317  rather than taking a URL, so a typo cannot aim the key at a host that
 318  is not Apple's.
 319
 320All five of =key_file=, =key_id=, =team_id=, =topic= and =environment=
 321are required when =enabled= is true; validation runs at config load,
 322so a misconfigured =[push]= is caught before the daemon serves
 323anything. The delivery queue (a device's undelivered and attempted
 324pushes) is capped the same way the mail queue is, by =[retention]
 325push=.
 326
 327** [backup]
 328- =age_recipients= (optional) — age public keys (=age1...=). When set,
 329  =admin backup= encrypts every archive to them and appends =.age= to
 330  its name. Generate the pair off the host with =age-keygen=; only the
 331  public key goes here, so the host writes archives it cannot read.
 332  The restic copy is unaffected: the offsite job stages its own
 333  =VACUUM INTO= of the live database and snapshots =/var/lib/gitbay=,
 334  not the archives.
 335
 336** [api]
 337- =enabled= (false) — the JSON API surface; see [[API]]. Off
 338  means no credential-bearing HTTP endpoint exists at all.
 339
 340** [webhooks]
 341- =allow_local= (false) — permit webhook, mirror and import targets on
 342  loopback, private, shared (100.64.0.0/10), link-local or multicast
 343  addresses. Leave off unless you know why you need it (SSRF).
 344
 345** [limits]
 346- =clone_timeout= (3600s) — cap on =repo import= fetches. An import
 347  takes http and https URLs only, passes the same address check as a
 348  mirror sync and is pinned the same way, so it needs git 2.37 too.
 349- =max_blob_bytes= (100MB) — cap on raw file serving over the web.
 350- =max_asset_bytes= (512MB) — cap per uploaded release asset.
 351- =max_snippet_bytes= (1MB) — cap per snippet file.
 352- =max_snippets_per_user= (0, unlimited) — snippets an account may own.
 353- =max_repos_per_user= (0, unlimited) — repositories an account may own
 354  directly; =repo create=, =fork= and =import= refuse past it.
 355  Organizations are not capped.
 356- =max_bytes_per_user= (0, unlimited) — disk the account's own
 357  repositories may take; a push may be no larger than what is left.
 358- =pack_concurrency= (3), =pack_per_principal= (2), =pack_queue= (32),
 359  =pack_queue_wait= (="60s"=) — git pack generation (clones, fetches,
 360  =git archive --remote=, web archive downloads) over SSH, smart HTTP
 361  and git:// shares one
 362  budget: this many at once, this many per account (per client
 363  address when anonymous: an IPv4 address, or an IPv6 /64), and this
 364  many waiting for at most the wait. Anonymous clients together hold
 365  at most =pack_concurrency= − 1 slots when it is above 1: an account
 366  (SSH key, bearer token or web session) can take the last slot when it
 367  is free, and anonymous clients cannot hold it.
 368  Past that an SSH client gets "the server is busy…" and exit 1, HTTP
 369  gets 503 with =Retry-After: 30=, git:// an =ERR= line; the daemon
 370  logs a =pack limit= warning naming the transport and whether the
 371  client was signed in, at most once a minute per transport. An SSH client
 372  that disconnects while queued leaves the queue; an HTTP or git:// one
 373  keeps its place until the wait runs out. A running clone is killed
 374  when its client disconnects, or when no write to the client completes
 375  for two minutes: a client reading below about 550 B/s, or an HTTP
 376  request body that takes over two minutes with nothing written back,
 377  is cut. Ref listings (info/refs, protocol v2
 378  =ls-refs=), pushes and =repo download= are outside the budget. For the
 379  three counts 0 means the default and a negative value turns that
 380  bound off. The defaults suit a four-core host; see [[Performance]].
 381  With =ssh.mode = "system"= each SSH session is its own process and
 382  SSH clones are not counted.
 383- =max_pack_bytes= (2 GiB) — the largest pack one push may send,
 384  enforced as =receive.maxInputSize= and lowered to what an owner's
 385  storage quota has left.
 386- =ssh_auth_rate= (10) — SSH authentication failures per client address
 387  per minute on the embedded listener; see below.
 388
 389** [git_daemon]
 390- =enabled= (false), =port= (9418) — the anonymous =git://= listener.
 391  Serves only public repositories that additionally ran
 392  =repo settings git-daemon <repo> on=.
 393
 394** [mirrors]
 395- =pull_interval_minutes= (15) — how often pull mirrors fetch their
 396  upstream. Push mirrors sync shortly after each local ref update.
 397  Mirror URLs pass the same SSRF rules as webhook targets, when saved
 398  and again before every sync; git then connects only to the addresses
 399  that were checked (=http.curloptResolve=) and does not follow
 400  redirects, so a mirror of a renamed repository fails until its URL
 401  is updated. Needs git 2.37 or later on the server; with an older git
 402  the worker logs an error at start and syncs no mirror, recording the
 403  reason on each. Sync ignores the system and global gitconfig.
 404
 405** [go_import]
 406Vanity Go module paths, one per line: ="host/module" = "owner/repo"=.
 407Requests with =?go-get=1= at or under the module path answer with the
 408go-import meta tag pointing at the repository's HTTPS clone URL, so
 409=go install host/module/cmd/...@latest= resolves. The repository should
 410be public (the module path itself confirms it exists).
 411
 412* Users, email, invites
 413
 414Every =gitbayd admin= subcommand except =backup=, =gc= and the one-shot
 415backfills is a wrapper that dispatches the registry command of the same
 416name as the host: an admin context with no account behind it, so its
 417audit rows carry no actor and =source: host=. The same commands run in an
 418instance admin's SSH session (=ssh git@<host> admin ...=) and write the
 419same rows with the key fingerprint as source. One implementation, two
 420credentials.
 421
 422#+begin_src sh
 423gitbayd admin user create alice --key alice.pub --email a@example.org --verified [--admin]
 424gitbayd admin email verify alice a@example.org   # admin assertion, no SMTP needed
 425gitbayd admin invite --email b@example.org       # mails a code; prints it if no SMTP
 426#+end_src
 427
 428"Verified" means SMTP-confirmed or host-admin-asserted; the database
 429records which. Verified emails are what make commit signatures
 430meaningful — an unverified address never produces a =verified= badge.
 431
 432* Audit and account control
 433
 434The audit log is the security feed (events are the product feed): every
 435successful mutating command with its argv and source credential (SSH key
 436fingerprint or API), every refused one (exit 3 or 4) as =refused
 437<command>=, refused pushes as =refused git-receive-pack= (the access
 438check) or =refused push= (a branch or tag rule, a release anchor or an
 439unsigned commit, with the repository and ref names), hook socket
 440requests failing the peer or push-token check as =refused hook= (never
 441the token), registrations, admin actions, force-pushes, and auth
 442failures/throttling. A refusal row
 443keeps the flag names and the first positional, not the values.
 444Refusals are recorded up to ten a minute per account and 600 a minute
 445across the instance; past either, one =refused.throttled= row stands
 446for the rest of that minute. The caps bound the embedded listener, the
 447web and the API; under =ssh.mode = "system"= each =gitbayd shell=
 448connection counts separately. Secrets never appear — they travel on
 449stdin, never in argv.
 450
 451Each row carries the SHA-256 of the row before it. =gitbayd admin audit
 452verify= opens the store as other admin commands do, applying pending
 453migrations, so run it with the binary that matches the daemon. It
 454recomputes the chain and exits 1 naming the first row that was
 455edited or whose predecessor was removed. The chain is unkeyed: whoever
 456can write the database can recompute every hash after an edit, and
 457verify then finds nothing. It catches an edit only when the later
 458hashes were not recomputed. Retention removing the oldest
 459rows is not a break. Rows written before the chain existed are counted
 460and skipped; when every row is such a row, verify warns and exits 1,
 461since clearing the hash columns looks the same. After an upgrade that
 462clears with the first new audit row.
 463
 464Removing the newest rows leaves no break, and neither do rows written
 465afterwards under the freed ids. The database cannot show either. The
 466daemon logs every row it writes to its journal, outside the database
 467(=journalctl -u gitbayd -g 'INFO audit '=), and verify prints the last
 468id and hash: comparing them with the newest journal line is the check
 469for any change, recomputed hashes included. Rows written by
 470host =gitbayd admin= commands, and by =gitbayd shell= when =ssh.mode =
 471"system"=, are not copied to the journal.
 472
 473#+begin_src sh
 474gitbayd admin audit [--actor u|-] [--action prefix] [--since 24h|7d|date] [--limit n] [--json]
 475gitbayd admin audit verify           # check the hash chain; exit 1 names the first bad row
 476ssh git@<host> audit ...             # the same, from an admin session
 477ssh git@<host> admin user list [--state active|pending|disabled|admin]
 478ssh git@<host> admin user show <name>   # keys, emails, orgs, tokens, sessions
 479ssh git@<host> admin user limits <name> [--repos n|default] [--bytes n|default]   # per-account caps
 480ssh git@<host> admin user promote <name>   # grant instance admin
 481ssh git@<host> admin user demote <name>    # remove it; the last admin is refused
 482gitbayd admin user promote <name>    # host-local: recovery when no admin key is reachable
 483gitbayd admin user disable <name>    # suspend: SSH, web, API all refused;
 484gitbayd admin user enable <name>     #   sessions dropped, nothing deleted
 485gitbayd admin user delete <name> --yes  # only for accounts anchoring nothing:
 486                                     #   refused (with each blocker named) while
 487                                     #   the account owns repos, authored
 488                                     #   issues/MRs/comments/reviews, or is an
 489                                     #   org's only admin
 490#+end_src
 491
 492=--actor= takes a username, or =-= for rows with no actor: host commands
 493and auth failures. =--action= is a prefix, so =cmd repo= catches every
 494repository command and =admin= every host or admin-session action.
 495=--since= is a duration back from now (=30m=, =24h=, =7d=) or a date.
 496
 497=admin user list= pages by username (=--limit=, =--cursor=) and carries
 498each account's state and =last_seen=, the newest use of any of its SSH
 499keys or API tokens. =admin user show= adds the keys with their last use,
 500each address with how it was verified, PGP keys, org roles, the owned
 501repository count, API token names, and live browser sessions. Both are
 502Both are refused to non-admins, like =audit=, on every surface.
 503
 504=/admin/users= is the same list in a browser, linked from the admin
 505page: the state filter the command takes, keyset paging on its cursor,
 506and a row per account with promote, demote, disable and enable, each
 507dispatching the command. Demote and disable ask for the username to be
 508typed, since both take someone's access away. Creating and deleting an
 509account, issuing an invite and asserting an address stay on the command
 510line: each takes a key, mints a credential, or cannot be undone. A
 511non-admin gets the 404 a missing page would, so the URL confirms
 512nothing.
 513
 514Promotion needs an active account: a pending or disabled one is refused.
 515Demotion is refused when it would leave no admin, over SSH, in the
 516browser and on the host alike, so the host-local =promote= is the way
 517back in when the only admin key is lost.
 518
 519Instance admin carries no right on anyone's repository: policy does not
 520consult it, and a private repository still answers not-found to an
 521admin. Moderation goes through explicit overrides that skip the access
 522check and write their own audit row:
 523
 524#+begin_src sh
 525ssh git@<host> admin repo list [--owner o] [--visibility public|private]  # size, last push
 526ssh git@<host> admin repo archive|unarchive <owner/name>
 527ssh git@<host> admin repo visibility <owner/name> public|private
 528ssh git@<host> admin repo delete <owner/name> --yes
 529#+end_src
 530
 531Each lands in the audit log as =admin repo.<action>= naming the
 532repository, on top of the =cmd= row every mutating command gets.
 533
 534=limits.ssh_auth_rate= (10) throttles per-IP authentication *failures*
 535per minute — successful auths never count and clear the slate.
 536=limits.max_pack_bytes= is enforced as =receive.maxInputSize= on every
 537push.
 538
 539=limits.write_rate= (60) bounds *mutating commands per account per
 540minute*. It is counted in the dispatcher, so SSH, the JSON API and the
 541web spend one budget and a caller cannot refresh it by changing surface;
 542=limits.api_rate= stays in front of it, bounding a network source rather
 543than an account. A command is one token whatever it writes, so a bundle
 544import costs one and only a loop of separate commands spends the budget.
 545Read-only commands, the runner protocol (a build streams its log in many
 546small writes) and the host CLI are exempt. Refusals exit 4 and say when
 547to retry. A negative value turns the limit off; it matters most with
 548=registration = "open"=, where every write also queues notification mail
 549and webhook deliveries.
 550
 551* Queues
 552
 553Every background worker keeps a backlog and a failure state. An instance
 554admin reads them all in one place:
 555
 556#+begin_src sh
 557gitbay dashboard --json | jq .queues   # webhooks, mail, push, mirrors, builds, deps
 558#+end_src
 559
 560Per worker: pending, retrying (pending with a failed attempt) and
 561dead-lettered counts with the oldest pending age, and the retrying or
 562failed rows themselves, capped at twenty each. Builds list what is
 563running and then what is pending, each since when, so a build no runner
 564is scoped to claim is visible here rather than only in its repository;
 565mirrors list the ones whose last sync failed;
 566dependency checks list the ones whose last check errored. Non-admins get
 567no =queues= key at all.
 568
 569Push rows name the device id, never the token. Watch this one after
 570configuring =[push]=: a =key_id= or =team_id= Apple did not issue passes
 571config validation, which can only check that the =.p8= parses, and then
 572every send comes back =403 InvalidProviderToken= and dead-letters on its
 573first attempt.
 574
 575In accounts mode the same read renders at =/admin=, linked from the rail
 576for admins. Anyone else gets a 404 there.
 577
 578A dead-lettered mail is logged as =notification dead-lettered mail=<id>=,
 579with the address redacted out of the relay's error. The id is the queue
 580row: find it in the Mail table on =/admin=, or in =dashboard --json=,
 581where the recipient and the unredacted error are. That is deliberate —
 582see the Threat-Model page.
 583
 584* Maintenance
 585
 586#+begin_src sh
 587gitbayd admin stats [--json]         # counts, database size, per-repo disk
 588ssh git@<host> admin stats [--json]  # the same, from an admin session
 589gitbayd admin gc [--repo owner/name] # git gc: repack and prune; per-repo sizes
 590gitbayd admin gc --aggressive        # thorough repack; slow, rarely needed
 591gitbayd admin gc --lfs               # also drop LFS objects no pointer names (older than a day)
 592#+end_src
 593
 594A history rewrite leaves the commits it removed reachable through
 595=refs/merge-requests/N/head= of the merge requests that landed them, so
 596they stay fetchable by anyone who can read the repository. Nothing drops
 597a head ref on its own — an open or source-gone MR is merged through it,
 598and a merged or closed one keeps its diff readable through it — so the
 599cleanup is a command an instance admin runs, naming the MRs:
 600
 601#+begin_src sh
 602ssh git@<host> admin mr prune owner/name 1 2 3 --yes
 603#+end_src
 604
 605It refuses an open or source-gone MR, deletes the named refs, runs
 606=git gc --prune=now= on that one repository so the objects go at once
 607rather than after git's two-week grace, leaves a system comment on each
 608MR, and audits as =admin mr.prune=. The MR keeps its title, comments,
 609reviews and head sha; =mr diff= and the MR page say the head is gone.
 610Run it when nothing is pushing to that repository: without the grace, a
 611push caught between leaving quarantine and writing its ref loses its
 612objects. Objects also survive in offsite backups until those are
 613rewritten; see "Removing a repository's history from every snapshot".
 614
 615=deploy/cloud-init.yaml= ships a =gitbay-gc.timer= that runs =admin gc=
 616weekly (Sunday 07:00 UTC). Imported repositories keep whatever pack
 617layout the source sent, so a first manual =admin gc= after a bulk
 618import is worthwhile.
 619
 620* Backup and restore
 621
 622#+begin_src sh
 623gitbayd admin backup --out /var/backups/gitbay/backup.tar.gz
 624gitbayd admin backup --verify /var/backups/gitbay/backup.tar.gz   # read it back
 625#+end_src
 626
 627One archive: a consistent SQLite snapshot (taken *before* the
 628repositories are read, so the database never references objects the
 629archive missed), every repository, and the SSH host keys. Excluded:
 630hook socket, regenerated hook scripts, WAL files. Safe to run against a
 631live daemon. =--out= must be outside =server.root=, or the next full
 632backup would carry the archive. Each run removes the snapshot
 633directories (=.gitbay-snap-*=) and temporary archives (=.*.tmp-*=) a
 634killed run left beside its archive once they are a day old, and prints
 635each one it removes.
 636
 637=--verify= reads an archive back: the snapshot must pass SQLite's
 638integrity check, every repository the snapshot names must be in the
 639archive, and each must pass =git fsck --connectivity-only=. Every
 640release asset the snapshot names must be in its repository with its
 641recorded size and sha256, and every LFS object in the archive must
 642hash to its name. LFS objects are named by pointer files in git
 643history rather than by the database, so a pointer whose object was
 644never uploaded is not caught, and with =[lfs] root= outside
 645=server.root= the archive holds no LFS objects at all. It extracts the
 646repositories to a temporary directory for the checks, so it needs free
 647space the size of the repositories. A database-only archive is checked
 648for integrity and says so. Exit is non-zero on damage, a missing
 649repository, a missing object, or a missing or altered asset or LFS
 650object.
 651
 652A full backup holds =<root>/backup.lock= from its database snapshot to
 653its last repository. While it runs, =repo delete=, =repo rename=,
 654=repo transfer=, =admin repo delete=, =org rename=, =admin mr prune=
 655and =gitbayd admin gc= refuse with "a backup is running"; retry when it
 656finishes. Database-only backups take no lock. A pack that git's own
 657automatic gc removes during the walk is skipped; each repository's refs
 658are archived before its objects, so the refs still find their objects,
 659and =--verify= reports it if one does not.
 660
 661Verifying an archive of unknown origin: run it as an unprivileged
 662user. The connectivity check runs git with =--git-dir= on each
 663extracted repository, so a directory that is not a repository fails
 664rather than git checking an enclosing one. =objects/info/alternates=
 665and a =commondir= directly in a =*.git= directory are not extracted,
 666so an archive cannot use either to have git read another repository's
 667objects or refs on the host. Git still reads each archived
 668repository's own =config=.
 669
 670Archives carry a directory entry for every directory, including an
 671empty one, so a bare repository whose refs are all packed restores as
 672a repository. Archives written before this release do not: extracting
 673one can leave a repository's =refs/= directory missing, which stops
 674git from recognizing it as a repository at all. =gitbayd admin backup
 675--verify <archive>= names the repositories this affects; the fix is
 676=mkdir -p <root>/repos/<owner>/<name>.git/refs= for each one, after
 677which it opens normally.
 678
 679With =[backup] age_recipients= set the archive is =<name>.tar.gz.age=
 680and =--verify= needs the private key:
 681
 682#+begin_src sh
 683gitbayd admin backup --verify gitbay-20260927-090000.tar.gz.age --identity ~/.config/gitbay/backup-identity.txt
 684age -d -i ~/.config/gitbay/backup-identity.txt gitbay-20260927-090000.tar.gz.age | tar -xz -C /new/root
 685#+end_src
 686
 687The identity lives off the host (with the secret key file and the
 688restic credentials), so verifying an encrypted archive happens there
 689or on a restore host.
 690
 691Restore: extract into an empty directory, point =server.root= at it,
 692restore =server.secret_key_file= from its own copy (mode 0600, owned
 693by the account gitbayd runs as), then start gitbayd. No archive carries
 694the key file, and without it gitbayd refuses to start. Host keys are
 695preserved, so clients keep their known_hosts entries; hooks regenerate
 696at startup.
 697
 698** Schedule and recovery point
 699
 700Two timers, because the two halves of the data have different exposure.
 701
 702- =gitbay-backup.timer=, nightly. The full archive above, last 7 kept.
 703- =gitbay-db-backup.timer=, hourly. =admin backup --db-only=, which
 704  writes the SQLite snapshot alone, last 48 kept. A few MB against the
 705  full archive's hundreds, which is what makes the frequency affordable.
 706
 707The split follows what a loss would actually cost. Repositories are git,
 708so a mirror or any clone is a second copy; the database is the only copy
 709of issues, merge requests, comments and review state. So the recovery
 710point is about an hour for the data that exists nowhere else, and a day
 711for the data that does.
 712
 713Continuous replication (litestream and similar) was considered and not
 714adopted. It would take the database's recovery point to seconds, but the
 715repositories would still be on the nightly archive, so a restore could
 716produce a database referencing commits the repository backup does not
 717have. Consistency between the two halves is worth more here than latency
 718on one of them. Revisit if repository replication becomes continuous
 719too.
 720
 721** Offsite copies
 722
 723bay1 also takes a nightly restic snapshot of =/var/lib/gitbay= and
 724=/var/lib/gitbay-stage= (a database copy and =config.toml=, staged
 725there) to an S3 bucket at Scaleway, with a key that can only add
 726snapshots. Nothing else under =/etc/gitbay= is in it: not the secret
 727key file, not =apns.p8=. The key that can
 728remove them lives on the operator's machine, in
 729=~/.config/gitbay/offsite.env=, and never on bay1: a compromised host
 730cannot destroy its own history. Forgetting, pruning and rewriting all
 731run from there.
 732
 733*** Removing a repository's history from every snapshot
 734
 735A history rewrite plus =admin mr prune= takes commits off the server,
 736but every snapshot taken before it still holds them, and the retention
 737window is the only thing that ages them out. To remove them now,
 738rewrite the snapshots without that repository rather than forgetting
 739the snapshots: everything else in them stays restorable. The next
 740nightly run adds the repository back in its current state.
 741
 742Repositories are stored under the name they had on disk when each
 743snapshot was taken, so a renamed repository needs every name it has
 744carried. Check what an older snapshot holds before choosing the paths:
 745
 746#+begin_src sh
 747set -a; . ~/.config/gitbay/offsite.env; set +a
 748restic $RESTIC_OPTS snapshots
 749restic $RESTIC_OPTS ls <old-snapshot> /var/lib/gitbay/repos/<owner>
 750#+end_src
 751
 752Then dry-run, apply, prune, and confirm nothing matches:
 753
 754#+begin_src sh
 755EXCL="--exclude /var/lib/gitbay/repos/<owner>/<name>.git --exclude /var/lib/gitbay/repos/<owner>/<old-name>.git"
 756restic $RESTIC_OPTS rewrite --dry-run $EXCL     # "would modify N snapshots"
 757restic $RESTIC_OPTS rewrite --forget $EXCL      # new snapshots replace the originals
 758restic $RESTIC_OPTS prune                       # drops the data nothing references
 759restic $RESTIC_OPTS find <name>.git <old-name>.git   # expect no output
 760#+end_src
 761
 762=--forget= is what makes the originals go; without it the rewritten
 763snapshots sit beside them and the data stays referenced. Snapshot IDs
 764change; their times do not. Done for krz/keycask (formerly rust-pass)
 765on 2026-09-18, across 22 snapshots.
 766
 767** Secret key
 768
 769CI secrets, webhook secrets, mirror tokens and APNs device tokens are
 770stored sealed: AES-256-GCM under a key in =server.secret_key_file=,
 771each value prefixed with the id of the key that sealed it
 772(=gbs1:<id>:=). The key file is not in the database, not under
 773=server.root=, and therefore in neither the local archives nor the
 774main restic repository. It must be copied off the host separately;
 775without it a restored database's secrets cannot be opened, and
 776gitbayd refuses to start against them. A separate restic repository
 777for it and =apns.p8= is planned (runbook D of the data-at-rest plan)
 778and not yet in place, so today the only off-host copy is one the
 779operator makes by hand after =init= and after every =rotate=.
 780
 781#+begin_src sh
 782gitbayd admin secrets init     # once; deploy/install.sh does it on first install
 783gitbayd admin secrets check    # open every value, count by key
 784gitbayd admin secrets rotate   # new key, reseal, retire the old one (as root)
 785#+end_src
 786
 787- Missing file: every gitbayd process that opens the database refuses
 788  to run and names the path, including =serve= and, in system mode,
 789  =authorized-keys=. =migrate= does not need it.
 790- Backups: =admin backup= and =admin backup --verify= do not need the
 791  key file; a restore does.
 792- Wrong key: =serve= stops at startup naming the first row that does
 793  not open; =secrets check= does the same without starting anything.
 794- Upgrade: the first start after the upgrade seals every value still
 795  in clear and logs =sealed secret values=.
 796- Rotation: =rotate= adds a key, reseals every value under it in one
 797  transaction, then removes the old keys. Run it as root, since it
 798  replaces the key file in =/etc/gitbay=; the file keeps its owner.
 799  The daemon re-reads the file when it changes, so it needs no
 800  restart. Copy the new file off the host afterwards. =init= and
 801  =rotate= hold an flock on =<key file>.lock= while they run, so a
 802  second run waits for the first.
 803- Push devices are looked up by the SHA-256 of their token
 804  (=push_devices.token_hash=), since two seals of one token differ.
 805
 806** Restore drill
 807
 808A restore onto a clean host, run quarterly (January, April, July,
 809October) and after any change to the backup code
 810(=cmd/gitbayd/backup.go=, =cmd/gitbayd/restoredrill.go=, the offsite
 811job), and recorded below. The disaster it rehearses is losing bay1, so
 812the local archives are gone with it and the sources are the main
 813offsite restic repository (repositories, LFS, the staged database,
 814=config.toml=), the off-host copy of =secret.key= and =apns.p8= (a keys
 815repository once runbook D creates it; until then the operator's
 816hand-made copy), and the operator's password manager (=offsite.env=,
 817the keys repository's password and token once it exists,
 818=backup-identity.txt=). The full steps are runbook C of the
 819data-at-rest plan (=docs/plans/2026-09-27-data-at-rest-and-backup.md=).
 820
 821=gitbayd admin restore-drill= does the archive half. It extracts a
 822full archive into an empty or absent directory, runs every =--verify=
 823check on the extracted copy, and prints what was restored, the newest
 824issue, issue comment, merge request comment and push in the restored
 825database, and the elapsed time. Exit is non-zero if any check fails.
 826
 827#+begin_src sh
 828gitbayd admin restore-drill /var/backups/gitbay/gitbay-20260927-090000.tar.gz --into /srv/drill
 829gitbayd admin restore-drill <archive>.tar.gz.age --identity backup-identity.txt --into /srv/drill
 830#+end_src
 831
 832What to restore, and from where:
 833
 834| Item                          | Source                                                      | Path on the drill host                         |
 835|-------------------------------+-------------------------------------------------------------+------------------------------------------------|
 836| Database                      | staged copy in =/var/lib/gitbay-stage= (restic), or an archive | =<root>/gitbay.db=                          |
 837| Repositories                  | =/var/lib/gitbay/repos= (restic), or an archive              | =<root>/repos=                                 |
 838| LFS objects                   | =/var/lib/gitbay/lfs= (restic), or an archive                | =<root>/lfs= (or =[lfs] root=)                 |
 839| Release assets                | inside each repository (=gitbay-releases/=)                  | with the repositories                          |
 840| Host keys                     | =/var/lib/gitbay/ssh= (restic), or an archive                | =<root>/ssh= (or =[ssh] host_keys=)            |
 841| =config.toml=                 | =/var/lib/gitbay-stage/config.toml= (restic)                 | =/etc/gitbay/config.toml=                      |
 842| =secret.key=, =apns.p8=       | the off-host copy; no archive or main snapshot carries them | =/etc/gitbay/=, mode 0600, owned by =gitbay=   |
 843
 844From the offsite path (restic is not run by any gitbay command):
 845
 846#+begin_src sh
 847restic restore latest --target / --include /var/lib/gitbay --include /var/lib/gitbay-stage
 848cp /var/lib/gitbay-stage/gitbay.db /var/lib/gitbay/gitbay.db
 849gitbayd --config /etc/gitbay/config.toml admin backup --out /tmp/drill.tar.gz
 850gitbayd admin restore-drill /tmp/drill.tar.gz --into /tmp/drill-root
 851#+end_src
 852
 853The second archive is how the restic tree gets the same checks and
 854timestamps; =/tmp/drill-root= is discarded afterwards.
 855
 856What to check, each a column below:
 857
 858- DB integrity, connectivity, release assets, LFS: =restore-drill=
 859  prints =integrity ok=, =connectivity ok on N repositories=, =release
 860  assets ok: N=, =LFS objects ok: N=. Compare N with =gitbayd admin
 861  stats --json= on the source at the snapshot time.
 862- Secrets: =gitbayd --config /etc/gitbay/config.toml admin secrets
 863  check= opens every value.
 864- Host key: =ssh-keyscan -p 22 <drill-host>= matches the source's
 865  fingerprint.
 866- Config: =gitbayd --config /etc/gitbay/config.toml check-config=.
 867- Service: =ssh -p 22 git@<drill-host> whoami= and a =git clone= over
 868  SSH succeed.
 869
 870Time to service runs from the clean host's first root login to the
 871first successful =git clone= over SSH from it. The recovery point is
 872the time of the newest restic snapshot restored; record beside it the
 873newest issue, comment and push =restore-drill= printed, which show how
 874much activity the restore carries.
 875
 876The first drill ran on the operator's laptop rather than a provisioned
 877host, so its time to service has no provisioning in it, and it could
 878not check secrets: no copy of =secret.key= was on the machine, and
 879gitbayd refuses to start while any sealed value does not open. The
 880sealed values were cleared in the drill copy to reach service. The
 881off-host copy of the key is confirmed to exist (#305); the next drill
 882restores it with the snapshot and runs =admin secrets check= on the
 883restored copy.
 884
 885| Date | Host | Snapshot restored (UTC) | Newest issue / comment / push | Time to service | DB integrity | Connectivity | LFS | Release assets | Host key | Secrets | Notes |
 886|------+------+-------------------------+-------------------------------+-----------------+--------------+--------------+-----+----------------+----------+---------+-------|
 887| 2026-09-29 | laptop (macOS), restic from offsite | 2026-09-29 00:19:15 (ccd646cf) | 00:05:17 / 00:09:44 / 00:15:31 | 8m43s (restore 1m49s, checks 33s) | ok | ok, 69/69 | ok, 2 | ok, 529 | matches | not checked (#305) | 4.99 GiB restored; 71 sealed values cleared in the drill copy to start |
 888
 889* Upgrades
 890
 891Replace the binary, restart the unit. Migrations apply automatically and
 892are transactional; hook scripts under =<root>/hooks= are rewritten at
 893startup to point at the current binary path.
 894
 895* CI runner
 896
 897=gitbay-runner= executes builds queued by pushes and merge requests. It
 898polls over SSH with a key of scope =runner=, which reaches only the
 899runner protocol and read-only git (a runner executes arbitrary
 900repository code, so the key it holds must not do more). A runner key
 901claims builds only for the repositories it is attached to, by =repo
 902runner add= from a repository admin or an instance admin; an admin key
 903claims any. Users attach their own runners: see the Users page. For an
 904instance runner, run it as a dedicated unprivileged user on a non-admin
 905account. =admin user create --key= registers a full-scope key, so the
 906runner key is added afterwards through a bootstrap key that is then
 907removed, and attached to each repository it should build:
 908
 909#+begin_src sh
 910useradd --system --create-home --home-dir /var/lib/gitbay-runner ci-runner
 911sudo -u ci-runner ssh-keygen -t ed25519 -N "" -f /var/lib/gitbay-runner/.ssh/id_ed25519
 912ssh-keygen -t ed25519 -N "" -f /tmp/ci-bootstrap
 913gitbayd --config /etc/gitbay/config.toml admin user create ci --key /tmp/ci-bootstrap.pub
 914ssh -i /tmp/ci-bootstrap git@127.0.0.1 keys add --scope runner < /var/lib/gitbay-runner/.ssh/id_ed25519.pub
 915ssh -i /tmp/ci-bootstrap git@127.0.0.1 keys remove "$(ssh-keygen -lf /tmp/ci-bootstrap.pub | awk '{print $2}')"
 916rm /tmp/ci-bootstrap /tmp/ci-bootstrap.pub
 917gitbay-runner -remote git@127.0.0.1 -workdir /var/lib/gitbay-runner/work
 918#+end_src
 919
 920#+begin_src sh
 921gitbay repo runner add krz/site < /var/lib/gitbay-runner/.ssh/id_ed25519.pub
 922#+end_src
 923
 924=-jobs N= runs N builds at once. Claiming is one transaction that
 925selects and updates, and each build works in its own =build-<id>=
 926directory, so workers do not collide; idle polls are staggered across
 927the interval so N of them do not wake together. The drop-in's weights
 928below are per service, not per build, so raising =-jobs= divides them
 929rather than multiplying the host's load.
 930
 931=admin runners= shows which account each runner polls as, and what each
 932may claim. A runner key claims builds only for the repositories it is
 933attached to: with none attached it claims nothing, and =-repos= may only
 934narrow within them. An admin's full-scope key claims any repository —
 935that is what =-repos= was for — and still works for the protocol during
 936a rotation. A merge request head from a fork is built in the target
 937repository as untrusted: the claim carries no secrets, and only a runner
 938started with =-untrusted= takes it. Same-repository heads were built by
 939their branch push and are not built again.
 940
 941=make deploy-runner= also installs
 942=deploy/gitbay-runner.override.conf= as a systemd drop-in: =Nice=10=,
 943=CPUWeight=30=, =IOWeight=30=, so a build never starves the host's sshd,
 944the daemon or the backup timers, and =NoNewPrivileges=,
 945=ProtectSystem=full=, =ProtectKernelTunables=, =ProtectControlGroups=
 946and =RestrictSUIDSGID=, so a step cannot reach outside its workspace
 947and the runner's home. The e2e suite alone starts sixty
 948daemon instances; without the drop-in a deploy's copy over the admin
 949sshd stalled. Both deploy targets copy with =rsync --partial=, which
 950resumes a stalled transfer.
 951
 952Under =-isolation podman=, the default and what bay1 runs, each build
 953is confined to a container (see Container isolation below). Under
 954=-isolation none= steps run directly on the host as the runner's user,
 955so treat that machine as executing whatever your users push, and
 956install the toolchains your builds need on it.
 957
 958A runner claims the oldest pending build among the repositories its key
 959is attached to — for an admin key, the oldest in the instance. =-repos=
 960narrows within that set, which is what makes a runner outside the server
 961practical: one on a machine that should build a single project, or that
 962holds credentials for one deployment, stays on it.
 963
 964Oldest-first is across everything the key may claim, so a repository
 965with a deep queue holds every other repository the same runner serves;
 966bay1 measured a 15-minute average wait on a day of merge request
 967stacks from one repository. A runner attached to one repository cannot
 968be starved. That is the rule, decided in krz/gitbay#207: a runner
 969serving several repositories takes them oldest-first, and an operator
 970who wants one repository never to wait on another runs a second
 971runner attached to it alone. Nothing caps what an account queues,
 972and nothing needs to (krz/gitbay#206): a schedule tick queues nothing
 973while the job's last build is pending or running, so a repository
 974with no runner holds one row per scheduled job rather than one per
 975tick, and a build runs only on a runner its owner attaches, so a busy
 976schedule spends the owner's compute. Pushes are bounded by what an
 977account can push.
 978
 979#+begin_src sh
 980gitbay-runner -remote git@gitbay.org -repos krz/site,krz/docs \
 981  -workdir /var/lib/gitbay-runner/work
 982#+end_src
 983
 984Add =-untrusted= only with =-isolation podman=.
 985
 986gitbay.org's runner is attached to the forge's own repositories and
 987the isolation canary, nothing else, because it shares the host with
 988the forge; its unit names no =-repos=, the attachments are the
 989boundary. Any other repository builds on a runner its owner attaches.
 990
 991=-repos= narrows an admin runner; for a runner key the attachments are
 992the boundary, held by the server, and =-repos= may only name
 993repositories among them. =-untrusted= makes a runner claim merge
 994request heads from forks; the bay1 unit sets it because it isolates in
 995podman. A runner without it builds trusted commits only.
 996
 997=gitbay dashboard= and =ssh git@<host> admin runners= list every key
 998that has polled as a runner: the account, the key's fingerprint, when it
 999last polled, the repositories it may claim — its attachments for a runner
1000key, the =-repos= it asked for or =any= for an admin key — and the build
1001it holds; =admin runners remove <fingerprint>= (=forget= until the next release) drops the row for a key
1002that polled by mistake, the key itself untouched. =admin runners= also
1003heads the list with the queue: builds
1004pending now, and over the last day how many were claimed, how long they
1005waited to be claimed (average and worst), and
1006how many the reaper ended instead of a runner reporting them. A build a runner claimed and never
1007reported is failed by the scheduler's minute tick, whether or not any
1008runner is still alive: within about two minutes of its log stream ending
1009with no outcome reported — the runner reports right after closing the
1010stream, retrying for half a minute if gitbayd is unreachable — or, if no
1011stream was ever seen, at the deadline.
1012
1013Instance admin on the runner account only authorizes the claim/report
1014protocol; it grants no repo access. A build that pushes back — a pages
1015deploy, an archive publish, an automated MR branch — needs an explicit
1016grant on that repo: =repo access grant <owner/name> ci write=. Private
1017repos likewise need at least read for the clone.
1018
1019** Container isolation
1020
1021Builds run in a rootless podman container, one per job, with the
1022workspace bind mounted and nothing else: the clone happens outside with
1023the runner's key, so a step cannot read it. =-isolation none= keeps the
1024old behaviour — steps on the host as the runner's user — for an instance
1025where every repository is trusted. There is no automatic fallback: a
1026runner started with =-isolation podman= that cannot find a working
1027podman exits rather than running a build unsandboxed.
1028
1029gitbay's own jobs name =localhost/gitbay-ci:2=, built from
1030=deploy/Containerfile.ci= on the runner host. A job's image must carry
1031what its steps need: the suite drives real git, git-lfs, gpg and sshd and
1032asserts they exist before running, so the stock runner default would fail
1033it immediately. Build or rebuild it with:
1034
1035#+begin_src sh
1036ssh -p 2222 root@<host> 'cat > /tmp/Containerfile.ci' < deploy/Containerfile.ci
1037ssh -p 2222 root@<host> 'su - ci-runner -s /bin/sh -c \
1038  "podman build -t localhost/gitbay-ci:2 -f /tmp/Containerfile.ci /tmp"'
1039#+end_src
1040
1041The tag is deliberate rather than =:latest=: changing the file means
1042bumping the tag in =.gitbay/ci.yml=, so a running branch's image does not
1043change under it.
1044
1045=-image= names the image a job runs in when it declares none, and is
1046required under =-isolation podman=: there is no built-in default,
1047because an image this host does not have would fail every build. A job
1048overrides it with =image:= in =.gitbay/ci.yml=, validated as a reference
1049so a config file cannot turn it into podman arguments.
1050
1051=-cpus= and =-memory= cap one build (podman's units, e.g. =-cpus 2
1052-memory 4g=); unset means uncapped. The runner applies them itself: it
1053creates a cgroup per build under its own delegated service cgroup,
1054writes the limits there, and starts every podman process for the build
1055inside it, with podman's cgroup handling off. Podman's own =--memory=
1056and =--cpus= never applied under rootless cgroupfs, which is what a
1057system service gets (krz/gitbay#188). The unit therefore needs
1058=Delegate=yes=, which the drop-in sets; without it the runner refuses
1059to start when a limit is set, and logs that builds run unconfined when
1060none is. bay1 runs =-cpus 3 -memory 6g= per build inside =MemoryMax=6G=
1061and =CPUQuota=300%= on the unit, on a 7.7GB four-core host with no
1062swap: the memory cap is what keeps the forge alive when a build
1063allocates without bound, and it sits above the e2e suite's 5GB peak
1064rather than at a fair share. =OOMPolicy=continue= keeps systemd from
1065stopping the runner when a build is OOM-killed.
1066
1067A trusted build's home is its repository's, under
1068=<workdir>/trusted-home/<owner>/<name>=, mounted into its containers as
1069=HOME=: caches persist between trusted builds of one repository and are
1070never read by another's. An untrusted build — a merge request head from
1071a fork — gets =<workdir>/build-<id>-home=, new and empty, removed when
1072the build ends. Homes under =<workdir>/home= are from runners before
1073krz/gitbay#255, which shared them with untrusted builds; nothing reads
1074them any more, and they can be deleted.
1075
1076*Images are provisioned, never pulled by a build.* The runner passes
1077=--pull=never=. Two reasons, and the second is the better one: the
1078service runs with =RestrictSUIDSGID=yes= so podman cannot unpack a layer
1079holding a setuid file, which is nearly every distribution image; and on
1080an instance where anyone can push a =ci.yml=, =image:= would otherwise
1081mean "fetch and run anything from the internet". An operator pulls or
1082builds what is allowed and a build picks among those. A job naming an
1083image the host does not have fails with a message saying so.
1084
1085#+begin_src sh
1086su - ci-runner -s /bin/sh -c "podman pull docker.io/library/alpine:3.20"
1087su - ci-runner -s /bin/sh -c "podman images"
1088#+end_src
1089
1090Prepare a host before pointing an isolating runner at it:
1091
1092#+begin_src sh
1093ssh -p 2222 root@<host> 'sh -s' < deploy/runner-podman-setup.sh
1094make deploy-runner
1095#+end_src
1096
1097The script installs podman, delegates a subuid/subgid range to
1098=ci-runner=, checks that user namespaces are enabled rather than
1099assuming, enables lingering, and verifies rootless podman actually runs
1100as that user. It is idempotent.
1101
1102It also installs nftables. =make deploy-runner= ships
1103=deploy/gitbay-runner-egress.nft= to =/etc/gitbay-runner/egress.nft=
1104with =gitbay-runner-egress.service=, which loads it and which the
1105runner's unit requires; it checks the file with =nft -c=, reloads the
1106unit, and runs =deploy/runner-egress-check.sh= as =ci-runner= before
1107restarting the runner: =127.0.0.1:22= and the public 22 must answer,
11082222 must not. The table limits the runner's user to =127.0.0.1:22=,
1109DNS on loopback, and 22, 80 and 443 on the host's public address; the
1110Threat-Model page says why.
1111
1112That table cannot tell a build from the runner, since both run as
1113=ci-runner=. =deploy/gitbay-runner-builds.nft=, shipped as
1114=/etc/gitbay-runner/builds.nft=, matches by cgroup instead: the runner
1115starts each build under =builds/trusted= or =builds/untrusted= in its
1116service cgroup, and the table closes the host's loopback to every
1117build, limits an untrusted build to TCP 80 and 443 and DNS, and closes
1118private ranges to both (the CI page has the table). nftables resolves a
1119cgroup path to its id when the table loads, and the service cgroup is
1120new on every start, so the drop-in's =ExecStartPre= creates the two
1121cgroups, hands them to =ci-runner= and loads the table before the
1122runner starts; a table that does not load stops the start. =make
1123deploy-runner= checks the file's syntax before the restart and that the
1124table is loaded after it. If =/etc/resolv.conf= names a nameserver in a
1125private range, allow it in the file first or builds resolve nothing.
1126
1127A restart of =nftables.service= flushes both tables;
1128=systemctl reload gitbay-runner-egress= restores both.
1129
1130The egress unit's stop and the rollback below use =nft destroy=,
1131which needs nftables 1.0.8 or later; check =nft --version= on a new
1132host.
1133
1134Checking the tables on a running host, during a build (the flood test
1135below waits a minute before its first probe, for this):
1136
1137#+begin_src sh
1138nft list table inet gitbay_builds          # counters on the reject rules
1139for p in $(pgrep -u ci-runner pasta); do cat /proc/$p/cgroup; done
1140# 0::/system.slice/gitbay-runner.service/builds/trusted/build-<id>
1141#+end_src
1142
1143A pasta process anywhere else — the runner's own =runner= cgroup, a
1144user slice — means the builds table does not see that build's traffic
1145and only the first table applies. Run
1146=deploy/runner-auth-flood-test.sh= on the scratch repository (below),
1147once as a push and once with =--untrusted=. It fails if the runner was
1148locked out or if the build log lacks the lines only a working table
1149produces. The authoritative proof that pasta's sockets are in the
1150build's cgroup is the untrusted run: =169.254.1.2:22= and
1151=github.com:22= refused, all twelve logins refused, and the counters on
1152the =untrusted= chain's rejects rising. The first table lets
1153=ci-runner= reach both of those addresses.
1154
1155To take the builds table out, on the host:
1156
1157#+begin_src sh
1158sed -i '/^ExecStartPre=+.*builds/d' /etc/systemd/system/gitbay-runner.service.d/override.conf
1159rm /etc/gitbay-runner/builds.nft
1160systemctl daemon-reload
1161nft destroy table inet gitbay_builds
1162#+end_src
1163
1164The runner needs no restart. It still places builds under
1165=builds/trusted= and =builds/untrusted=, but with the file gone neither
1166a runner start nor =systemctl reload gitbay-runner-egress= loads the
1167table again, and builds keep the first table and =--no-map-gw=. A
1168runner that takes =-untrusted= or polls over loopback refuses to start
1169without build cgroups at all, since the table would match nothing. The
1170next =make deploy-runner= installs the file and the lines again.
1171
1172The drop-in sets =NoNewPrivileges=no=, without which rootless podman
1173cannot call =newuidmap= and the runner refuses to start. That is a
1174considered trade, explained in the file and in the Threat-Model; if you
1175run with =-isolation none=, set it back to =yes=.
1176
1177*Restarting the runner is safe.* On SIGTERM it stops claiming, finishes
1178the build in flight, reports it, and exits; the drop-in's
1179=TimeoutStopSec=50min= covers the longest build, and its =KillMode=mixed=
1180is what makes the signal reach the runner alone — under systemd's default
1181the build's container and the log session are signalled with it, and the
1182runner drains a build that is already dead. So =make deploy-runner=
1183waits for a running build rather than orphaning it, and a build's result
1184is retried for half a minute if gitbayd is restarting at that moment. A
1185second SIGTERM ends the runner at once, abandoning the build to the
1186reaper. The suite checks all three: =TestRunnerDrainsOnSIGTERM= signals
1187the process, =TestRunnerDropInLetsTheDrainHappen= reads the drop-in's
1188=KillMode= and =TimeoutStopSec=, and =TestRunnerDrainUnderSystemd= runs
1189the runner as a transient user unit under =systemd-run= and stops it
1190under both kill modes. That last one needs a systemd user manager, so it
1191skips in the container CI runs in; run it on a Linux host with
1192=go test ./e2e -run TestRunnerDrainUnderSystemd -v=.
1193
1194*Validate podman mode on a scratch repository before pointing the runner
1195at real ones.* Every deploy that switched the whole instance to
1196containers and failed took CI down with it. Instead: create a throwaway
1197repository the runner account can read (public, or granted read — a
1198private one is "not found" to the runner and the build stays pending),
1199give it one job that names the CI image, attach the runner's key to it,
1200and deploy the runner with =-repos= naming only that repository. The
1201production unit, with its real hardening, then claims nothing else;
1202other repositories' builds queue until =-repos= is removed again, which
1203is a pause, not an outage.
1204
1205#+begin_src sh
1206# on a machine with an admin gitbay identity (root on the host has none),
1207# with the runner's public key copied from the host:
1208gitbay repo create cmc/runner-scratch   # then push a .gitbay/ci.yml naming the image
1209scp -P 2222 root@<host>:/var/lib/gitbay-runner/.ssh/id_ed25519.pub runner.pub
1210gitbay repo runner add cmc/runner-scratch < runner.pub
1211# on the host:
1212sed -i 's#^ExecStart=/usr/local/bin/gitbay-runner #&-repos cmc/runner-scratch #' /etc/systemd/system/gitbay-runner.service.d/override.conf
1213systemctl daemon-reload && systemctl restart gitbay-runner
1214# back on the admin machine:
1215gitbay build log cmc/runner-scratch 1   # green: remove -repos, redeploy, delete the scratch repository
1216#+end_src
1217
1218*Do not deploy an isolating runner to a host that has not been
1219prepared.* The runner is specified to refuse to start without a working
1220podman rather than fall back to running builds unsandboxed — a fallback
1221that silently drops isolation is worse than a stopped runner, because
1222nothing surfaces it. On an unprepared host that refusal stops every
1223build on the instance.
1224
1225The service drop-in carries =Delegate=yes= for rootless cgroup
1226management and =ReadWritePaths= for podman's store under
1227=/var/lib/gitbay-runner=, which =ProtectSystem=full= would otherwise
1228make read-only. Those paths are prefixed =-= so they are ignored when
1229absent: the drop-in installs on unprepared hosts too, and a unit that
1230refused to start would stop every build.
1231=gitbay-runner-prune.timer= prunes unused images weekly, as the runner's
1232user: rootless storage belongs to that user, and root's prune would not
1233see it. An unpruned image store on a 40GB host is a slow outage.
1234
1235* LFS storage
1236
1237Objects live content-addressed under =[lfs] root= (default
1238=<server.root>/lfs=); =[lfs] max_object_bytes= caps a single object
1239(512MB default). Storage sits behind a small interface — an
1240S3-compatible backend is a drop-in with the server proxying, and
1241presigned URLs a later optimization. LFS objects do not travel with
1242push mirrors (mirrors move git refs only), and gc does not yet collect
1243orphaned objects.
1244
1245* Pages
1246
1247=[pages] domain = "example.site"= serves public repos' =pages= branches
1248on =<owner>.<domain>=. DNS needs a wildcard record =*.<domain>= to the
1249server; ACME issues per-subdomain certificates on demand (only for
1250owners that exist). The domain must not be the site host or a parent of
1251it — pages content runs its own scripts and must stay off the forge's
1252origin.
1253
1254Users with repo admin claim custom domains with =repo domain add=.
1255Claims activate only after a DNS TXT challenge proves control of the
1256domain (=repo domain verify=, audit-logged); pending claims serve
1257nothing, get no certificates, and expire after 7 days. ACME issues
1258certificates only for verified hosts, so stray DNS pointed at the
1259server gets nothing.
1260
1261* Security
1262
1263The [[Threat-Model]] file is the reference for what the forge
1264trusts and refuses to do. Operational checklist:
1265
1266- *Software checks.* =deploy/audit.sh= runs =go vet=, =govulncheck=
1267  (the module list is deliberately short — review it on each release),
1268  and a short fuzz pass over every attacker-facing parser (pkt-line,
1269  commit, SSHSIG armor, OpenPGP key, SSH tokenizer). Run it before
1270  tagging a release. CI's own =vuln= job runs =govulncheck= nightly
1271  against main rather than per push, because =@latest= scans today's
1272  advisory database and an advisory lands without anyone pushing;
1273  =build trigger krz/gitbay vuln= runs it on demand.
1274- *Web responses* carry a scripts-forbidden CSP, =X-Frame-Options:
1275  DENY=, =nosniff=, =no-referrer=, and HSTS when TLS is on — no
1276  configuration needed.
1277- *Host sandboxing.* The systemd unit in =deploy/cloud-init.yaml= runs
1278  gitbayd unprivileged with =ProtectSystem=strict=, =PrivateDevices=,
1279  =LockPersonality=, =MemoryDenyWriteExecute=,
1280  =SystemCallFilter=@system-service=, and =RestrictAddressFamilies= to
1281  INET/INET6/UNIX. It keeps =CAP_NET_BIND_SERVICE= only, to bind 22/80/443.
1282- *OS patches* apply via =unattended-upgrades= (security origins,
1283  auto-reboot 04:30 if required).
1284- *Admin sshd (2222)* is throttled by =MaxStartups=/=MaxAuthTries= and
1285  watched by =fail2ban=; gitbayd's own port 22 is throttled by
1286  =limits.ssh_auth_rate= (auth failures per IP per minute), and every
1287  account's writes by =limits.write_rate=.
1288- *Monitoring.* =gitbay-monitor.timer= writes a reading hourly to
1289journald and, when =/etc/gitbay/monitor.url= exists, posts it to that
1290webhook: disk, service, the daemon's own =/healthz= answer, certificate
1291expiry, and the age of the newest full backup and database snapshot.
1292It exits non-zero on an alert so the unit shows in =systemctl
1293--failed=: a stopped service, =/healthz= not answering =ok=, disk ≥ 85%,
1294a certificate under 21 days, a full backup over 25 hours old, or a
1295database snapshot over 2 hours old.
1296
1297=GET /healthz= is unauthenticated and cache-free: whether the database
1298answers and which commit serves, 503 when it does not.
1299- *Database.* =gitbay.db= and its WAL live under =/var/lib/gitbay= (mode
1300  0750, owned by =gitbay=). The nightly archive plus provider snapshots
1301  are the recovery path; for tighter RPO, add continuous replication
1302  (litestream) against the same file — it coexists with the WAL.
1303
1304* Odds and ends
1305
1306- deleting a fork marks MRs sourced from it =source_gone=; their diffs
1307  remain viewable and mergeable because the target repo owns the
1308  objects.
1309- =refs/merge-requests/*= is server-owned and unpushable by clients;
1310  only =admin mr prune= removes one (see Maintenance).
1311- audit-relevant activity (issue/MR lifecycle, imports, pushes) lands in
1312  the =events= table, which also feeds webhooks.
1313- the daemon idles under 10MB RSS; the smallest VPS tier is adequate.