Infrastruktur för Bitborg. https://git.bitborg.se/
  • Jinja 42.8%
  • Python 34.6%
  • HCL 10.4%
  • Shell 10.1%
  • CSS 0.8%
  • Övrigt 1.3%
Hitta en fil
Kodförråd filer (senaste incheckning först)
Filnamn Senaste incheckningsmeddelande Senaste incheckningsdatum
Johannes Axner 1b1b7bee72
Alla kontroller lyckades
ci / ci (push) Successful in 23m22s
feat(keycloak): own realm state passphrase and scheduled realm drift check (#932)
This PR carries the whole #576 stack. #934 merged into #933's branch and #933 into this one, so the
three changes land together:

1. The realm state gets its own passphrase.
2. The shared passphrase is dropped from the realm root (#933).
3. A scheduled realm drift check with alerts (#934).

Both realm workspaces (staging, prod) were re-encrypted from this branch's first two commits, which
still had the fallback, before merge. Both now read `key_provider.pbkdf2.realm`. The vault keys are
in #935.

## Own passphrase for the realm state

Each environment's realm state (`opentofu/keycloak`) is encrypted with its own
`vault_keycloak_opentofu_state_passphrase` instead of the main root's passphrase. The drift check
needs the realm state on the services host, and the host must never hold the main root's key.

- `encryption.tofu`: only the `pbkdf2.realm` key and `aes_gcm.realm` method, for state and plans.
- `variables.tofu`: `realm_state_passphrase` (sensitive, at least 16 characters).
  `state_encryption_passphrase` is gone from the realm root.
- `scripts/keycloak-tofu-env.py`: exports `TF_VAR_realm_state_passphrase` from the environment's own
  vault and reads no other vault. The self-test checks that it never exports the main root's
  passphrase.
- `vault.example.yml` and the runbook ("Keycloak realm", "Realm state passphrase") document the key.

The main root keeps `vault_opentofu_state_encryption_passphrase` unchanged.

Proof on a throwaway root with the fallback config, then the final config: the fallback read the old
state (`No changes`, exit 0), `apply -refresh-only` rewrote it to `key_provider.pbkdf2.realm`, and
the final config read it with only the realm passphrase. The old config could no longer read it.

## Realm drift check

A timer on the prod services host runs `tofu plan -detailed-exitcode` for `opentofu/keycloak` every
6 hours and writes the exit code to the textfile collector. Three alerts read it:

| Alert                           | Fires when                                       | Severity |
| ------------------------------- | ------------------------------------------------ | -------- |
| `KeycloakRealmDrift`            | the plan is not empty (exit 2)                   | warning  |
| `KeycloakRealmDriftCheckFailed` | the plan did not complete                        | warning  |
| `KeycloakRealmDriftCheckStale`  | no completed plan for 14 hours, or none recorded | warning  |

The plan covers everything the root declares. A changed flow, execution, required action, client,
scope or permission raises `KeycloakRealmDrift`, and so does a merged realm change that was never
applied.

- **Runs on the services host** as `bitborg-id`, in the OpenTofu container
  (`ghcr.io/opentofu/opentofu`, through the registry mirror). The admin API listens only on that
  host's loopback.
- **Authenticates as `opentofu`.** A read-only client cannot plan this root: the provider refreshes
  every `keycloak_openid_client` with `GET /clients/<id>/client-secret`, which needs manage rights.
  `bitborg-id` owns Keycloak's database, which already holds every client secret, so the job gives
  no account anything it lacked.
- **Inputs:** `--tags keycloak` copies the `.tofu` files, lock file, `env/prod.tfvars` and the
  encrypted workspace state from the checkout that runs Ansible, and templates the `TF_VAR_*` inputs
  into a 0600 env file. The self-test fails if the role's inputs differ from the script's or include
  the main root's passphrase.
- **Prod only.** The monitoring VM does not scrape staging. The role skips the check while the realm
  passphrase or the `opentofu` secret is unset.
- **Traceability.** The role records the applying checkout's `HEAD` on the host, and each run's
  journal line names it. The role warns when that checkout is not at `origin/main`.
- **Failures.** With no state copy, the run reports status 1. A failed run retries after 5 minutes,
  at most twice an hour.

Rejected: CI (needs the admin secret and an SSH path into prod), the monitoring VM (a second host
with the admin secret), a read-only client (cannot refresh clients), `plan -refresh-only` (misses
merged changes never applied).

Proof against a local Keycloak 26.8.2: clean realm gives status 0; an OTP execution set to
`DISABLED` gives status 2; Keycloak stopped gives status 1 and keeps the last success timestamp.

## Operator steps after merge

1. In a fresh shell, per environment with its tunnel open:
   `eval "$(./scripts/keycloak-tofu-env.py <env>)"`, then `tofu plan -detailed-exitcode` must
   exit 0.
2. Run the registry mirror once so `bitborg/opentofu:1.13.9` exists in the registry.
3. From the main checkout, run `--tags keycloak` on prod.
4. Start `bitborg-keycloak-realm-drift.service` as `bitborg-id`. Expect status 0.
5. Apply the monitoring role so the rules load.
6. Prove it: change a client description in the admin console, start the check, expect status 2.
   Apply the realm to undo it, then run `--tags keycloak` again.

After every realm apply, run `--tags keycloak` from the same checkout, or the check plans stale
state and fires.

## Checks

`tofu fmt -check`, `tofu validate`, `keycloak-tofu-env.py --self-test`, ruff, shellcheck,
`test-alert-rules.py`, `check-alert-rules.py`, `check-metric-names.py`,
`check-renovate-annotations.py`, `lint-rendered-templates.py`, `check-podman-run-log-driver.py`,
`ansible-lint`, `site.yml --syntax-check`, prettier, markdownlint.

Closes #576

Reviewed-on: #932
2026-11-30 21:10:52 +00:00
.forgejo/workflows fix(caddy): raise the memory cap and challenge cookieless crawlers (#870) 2026-11-08 12:14:07 +00:00
.vscode fix(renovate): disable major updates (#142) 2026-07-19 12:36:13 +00:00
ansible feat(keycloak): own realm state passphrase and scheduled realm drift check (#932) 2026-11-30 21:10:52 +00:00
assets chore: remove kanidm (#743) 2026-10-14 11:42:55 +00:00
cost feat(ops): 2fa review, safer teardown, off-site state copy, cost refresh (#830) 2026-10-19 22:53:55 +00:00
docs feat(keycloak): own realm state passphrase and scheduled realm drift check (#932) 2026-11-30 21:10:52 +00:00
local docs(runbook): rewrite live sections with the bitborg names (#754) 2026-10-15 10:26:10 +00:00
opentofu feat(keycloak): own realm state passphrase and scheduled realm drift check (#932) 2026-11-30 21:10:52 +00:00
scripts feat(keycloak): own realm state passphrase and scheduled realm drift check (#932) 2026-11-30 21:10:52 +00:00
.editorconfig chore: initial commit 2026-06-10 21:00:18 +02:00
.gitignore chore: git ignore logs (#781) 2026-10-18 11:35:25 +00:00
.markdownlint-cli2.jsonc docs(runbook): drill backs a public tested-restore claim (#69) 2026-07-12 13:16:12 +00:00
.prettierignore fix: add node_modules to git ignore (#231) 2026-07-28 07:34:34 +00:00
CONTRIBUTING.md docs: point stale gitborg links at the canonical bitborg host (#405) 2026-08-09 20:31:18 +00:00
lefthook.json ci: lint the rendered role templates (#777) 2026-10-18 11:41:43 +00:00
package.json chore(deps): update pnpm to v11.29.0 (#926) 2026-11-30 01:00:54 +00:00
pnpm-lock.yaml chore(deps): lock file maintenance (#918) 2026-11-30 00:57:30 +00:00
pnpm-workspace.yaml chore(renovate): three night runs, automerge for dev tooling, explicit pnpm gate (#894) 2026-11-16 10:19:24 +00:00
README.md chore(renovate): three night runs, automerge for dev tooling, explicit pnpm gate (#894) 2026-11-16 10:19:24 +00:00
renovate.json fix(renovate): split terraform lock maintenance onto its own branch (#906) 2026-11-26 18:57:34 +00:00
ruff.toml feat(ci): export job logs to loki, clean up pr artifacts (#831) 2026-10-19 22:54:05 +00:00

bitborg-infra

Infrastructure-as-code and decision record for bitborg, a self-hosted git hosting service built on Forgejo and running on Bahnhof Cloud (Swedish, GDPR-focused).

This repository is intended to eventually be hosted on bitborg itself — the service hosts its own infrastructure code.

Guiding principles

bitborg is built, in priority order, to be:

  1. Owned, operated and hosted in Sweden — Swedish-owned, Swedish-operated, on Swedish soil. Users' code never passes through US-owned or US-operated infrastructure (beyond reach of the US CLOUD Act).
  2. Respectful of user integrity — GDPR and other EU/EEA data-protection law today, and built to adapt to future regulation.
  3. Free and open source — a fully FOSS stack, preferring the freer alternative (copyleft, community/non-profit governance) when options are comparable.
  4. Secure with users' data — minimal attack surface, least privilege, secrets never in plaintext, encrypted backups and tested restores.

These take precedence over convenience and govern every decision in this repo. See principles.md (bitborg-docs) for what each means concretely and how the stack embodies them.

What this is

A single instance on Bahnhof's OpenStack VPC runs Forgejo + PostgreSQL + Keycloak (identity provider, "Bitborg-id") + the public portal (bitborg-web) as rootless Podman containers managed by Quadlet (systemd), fronted by Caddy for automatic TLS across four hosts. The instance is provisioned with OpenTofu and configured with Ansible; a final health-check role gates every apply, probing the core services before the run is considered done. Keycloak is the identity provider (OIDC) and source of truth for tier entitlements; a reconciler systemd timer applies those entitlements to Forgejo (LFS quota, org-create, and CI/Actions access). CI/CD (Forgejo Actions) is on for every user with a hosting quota and for orgs with a paid or first-party member, and uses ephemeral single-use OpenStack VMs — one VM per job, booted and reaped by a runner-controller role on the services host (ADR 0021). There is no standing runner VM. bitborg-web deploys through that pipeline — a merge to its protected main triggers an ephemeral ci runner that builds an image, pushes it to the Forgejo registry, and the services host pulls it via podman auto-update (CI never touches prod; ADR 0019). Backups run on systemd timers as age-encrypted archives on a dedicated Cinder volume (/srv/bitborg-backup; ADR 0022), with off-site upload enabled to Glesys Object Storage (Swedish, Falkenberg) as primary and Hetzner Object Storage (hel1, EU) as secondary redundancy (ADR 0011), and a weekly backup-drill role restores the latest off-site archive onto a throwaway VM to prove the backup actually recovers. Dependency updates are automated by self-hosted Renovate (nightly timer; ADR 0023), with a registry-retention role pruning old CI images out of the Forgejo registry and a token-audit role tracking service-account token age. Web logins are SSO-only through Keycloak ("Sign in with Bitborg-id"; ADR 0044). Observability — metrics, logs, Grafana dashboards, alerting (ntfy + email), and cookieless GoatCounter analytics — runs on a separate, opt-in monitoring VM that the services host only pushes to, with mutual down-detection between the two (ADR 0020).

flowchart LR
    Internet([Internet])
    Admin([Admin])

    Internet -->|"bitborg.se :443"| Caddy
    Internet -->|"www :443"| Caddy
    Internet -->|"git :443"| Caddy
    Internet -->|"id :443"| Caddy
    Internet -->|":22 git SSH"| Forgejo["Forgejo<br/>:3000 + SSH"]
    Admin -->|":2222"| SSHD["admin sshd"]
    Caddy -->|"apex → 308 www"| Caddy
    Caddy -->|www| Web["bitborg-web<br/>Astro"]
    Caddy -->|git| Forgejo
    Caddy -->|"id"| Keycloak["Keycloak (Bitborg-id)<br/>OIDC IdP"]
    Web --> Forgejo
    Forgejo -.->|"OIDC login"| Keycloak
    Web --> Postgres[("PostgreSQL")]
    Forgejo --> Postgres
    Reconciler["reconciler<br/>(systemd timer)"]
    Reconciler -.->|"read entitlements"| Keycloak
    Reconciler -.->|"apply quota / org-create / Actions"| Forgejo
    Forgejo -.-> Timers["systemd timers"]
    Timers --> Local["age-encrypted backups<br/>(dedicated volume /srv/bitborg-backup)"]
    Local -->|"off-site (enabled)"| S3[("Glesys S3 (primary)<br/>+ Hetzner S3 (secondary)<br/>hel1 · interim EU")]
    Forgejo -.->|"OIDC (Bitborg-id)"| Keycloak
    Renovate["renovate<br/>(nightly timer, ADR 0023)"]
    Renovate -.->|"open update PRs"| Forgejo
    RunCtl["runner-controller<br/>(ADR 0021, on services host)"]
    EphVM[/"ephemeral runner VM<br/>(single-use, label: ci)"\]
    RunCtl -.->|"boot / reap"| EphVM
    EphVM -.->|"Actions, git :443"| Caddy
    Agents["monitoring-agent<br/>(push)"] -.->|"metrics + logs + cross-probe"| Mon["Monitoring VM<br/>(opt-in, ADR 0020)<br/>VictoriaMetrics · Loki · Grafana<br/>alerts → ntfy/email · GoatCounter"]
    Internet -->|"grafana/stats/ntfy :443"| Mon
    Mon -.->|"OIDC (Bitborg-id)"| Keycloak

The end-to-end flows — SSO login (Forgejo + Grafana via "Bitborg-id"), Keycloak realm provisioning, reconciliation, CI/CD deploy, backups, and observability/alerting — are diagrammed in architecture.md (bitborg-docs).

Layout

Path Purpose
principles.md (bitborg-docs) Guiding principles that govern every decision
architecture.md (bitborg-docs) Component overview and how they fit together
docs/runbook.md Operations: deploy, upgrade, restore, rotate secrets
docs/roadmap.md Not-yet-built growth: HA, payments go-live
decisions/ (bitborg-docs) Architecture Decision Records (ADRs)
ansible/ All host provisioning and service configuration
opentofu/ OpenTofu config to provision the host on OpenStack
cost/ Bahnhof unit prices + gathered usage samples
scripts/ Cost audit/30-day projection and complete teardown
local/ Podman preview of Forgejo config/branding (no cloud)

Git hooks

lefthook runs two hooks. pre-commit formats and fixes staged files. pre-push runs the same static checks CI runs, so a lint failure is caught before it costs a CI round trip:

pre-push job CI equivalent
format (prettier) pnpm format:check
lint markdown pnpm mdlint
lint python (ruff) ./scripts/ruff.sh
shellcheck ./scripts/shellcheck.sh
rendered role templates ./scripts/lint-rendered-templates.py
renovate annotations are live ./scripts/check-renovate-annotations.py
handler names are unique ./scripts/check-handlers-unique.py
metric names are consistent ./scripts/check-metric-names.py
runner-controller logic tests test_controller_logic.py
sign-in watcher match test test_forgejo_signin_watch.sh
caddy access-log redaction test_access_log_redaction.sh
opentofu fmt tofu fmt -check -recursive
opentofu validate tofu validate (root module)
opentofu validate (keycloak) tofu validate (opentofu/keycloak)
ansible-lint ansible-lint (same throwaway vault password as CI)
secret scan (gitleaks) gitleaks git --redact --no-banner .

Every job carries skip_empty: false, and that is load-bearing. Lefthook decides which files a push touches by diffing against the branch's remote counterpart. A brand-new branch has none, so the file list is empty and every job is skipped with "no matching push files" — which is exactly the case a feature branch is in the first time it is pushed. Measured: without it, a push carrying a deliberate ruff E501 violation sailed straight through. With it, the same push is rejected.

Three deliberate differences, all worth knowing:

  • The smoke tests are NOT in the hook. pnpm smoke:containers and pnpm smoke:textfile do real podman run calls with image pulls. On every push that is slow enough that people would start skipping the hook, which costs more than it saves. CI still gates them, so a smoke failure is caught there rather than here. Run them by hand when touching *.container.j2 hardening.
  • The alert-rule check is NOT in the hook either. ./scripts/check-alert-rules.py parses the rendered vmalert rules with vmalert itself, which means a container run and an image pull, so it belongs with the smoke tests rather than in a per-push hook. Run it by hand when touching alert-rules.yml.j2 or the thresholds in the monitoring role's defaults. Its --self-test proves it can still fail.
  • A missing tool warns, it does not fail. If tofu, ansible-lint or gitleaks is not installed the job prints a loud warning and passes, because blocking a push on a tool you have not installed is worse than the round trip. The warning says plainly that CI will still run the check.

Bypass with LEFTHOOK=0 git push when you genuinely need to. CI is the real gate either way.

Quickstart

Prerequisites: a Bahnhof OpenStack project with clouds.yaml configured, OpenTofu and Ansible installed locally, and the ansible-vault password for the encrypted secrets. The image is Debian 13 (trixie)+ (needs Podman ≥ 4.4 for Quadlet) — already the default in the OpenTofu config.

# 1. Provision the instance on Bahnhof OpenStack
cd opentofu
cp terraform.tfvars.example terraform.tfvars        # set ssh_public_key
tofu init && tofu apply                             # outputs the floating IP

# 2. Configure it (copy the floating IP into the inventory first)
cd ../ansible
ansible-galaxy install -r requirements.yml          # install collections
# set the floating IP in inventory/hosts.yml and your domain in group_vars/all/vars.yml
ansible-playbook site.yml                           # SSH port is auto-detected (see runbook §Initial deploy)

Then complete Forgejo first-run (create admin, lock down registration) per docs/runbook.md.

To preview configuration and branding changes locally — no cloud resources or vault needed: cd local && make up (see local/README.md).

Decisions at a glance

Area Choice
Hosting Bahnhof OpenStack VPC (OpenTofu)
Container runtime Podman + Quadlet (systemd)
Config management Ansible
Database PostgreSQL (container)
Reverse proxy / TLS Caddy (automatic HTTPS, Let's Encrypt)
Identity / SSO Keycloak "Bitborg-id" (OIDC) on id; group→role mapping (ADR 0044)
Public portal bitborg-web (Astro) on www; open sign-up (ADR 0029)
CI/CD Forgejo Actions; ephemeral single-use VMs per job (label ci); runner-controller on services host; tiered, reconciler-gated (ADR 0021)
Deploy (bitborg-web) Ephemeral ci runner builds image → Forgejo registry → host pulls via auto-update (ADR 0019/0021)
Observability Separate, opt-in VM: VictoriaMetrics + Loki + Grafana + alerts (ntfy/email); push-only agents; cookieless GoatCounter analytics (ADR 0020)
Backups age-encrypted archives on a dedicated Cinder volume (/srv/bitborg-backup); off-site to Glesys S3 (Falkenberg, primary) and Hetzner S3 (hel1, secondary, interim EU) (ADR 0022)
Dependency updates Self-hosted Renovate (nightly timer); pinned images mirrored into the Forgejo registry (ADR 0023)
Service accounts Scoped Forgejo service accounts for reconciler/renovate/CI/bot (ADR 0024)
Email Sweego (EU); transactional + verification

See docs/decisions/ for the full reasoning behind each.