- TypeScript 97.4%
- JavaScript 1.8%
- Dockerfile 0.8%
| Filnamn | Senaste incheckningsmeddelande | Senaste incheckningsdatum |
|---|---|---|
|
|
||
| .forgejo/workflows | ||
| .vscode | ||
| src | ||
| .env.example | ||
| .gitignore | ||
| .markdownlint-cli2.jsonc | ||
| .prettierignore | ||
| .prettierrc.json | ||
| Containerfile | ||
| eslint.config.mjs | ||
| lefthook.json | ||
| LICENSE | ||
| package.json | ||
| pnpm-lock.yaml | ||
| pnpm-workspace.yaml | ||
| README.md | ||
| renovate.json | ||
| tsconfig.build.json | ||
| tsconfig.json | ||
| vitest.config.ts | ||
bitborg-auth-reconciler
A one-way Keycloak → Forgejo entitlement reconciler for bitborg.
It reads Keycloak tier groups and entitlement roles, the entitlement source of truth
(ADR 0044),
and projects it onto Forgejo via the admin API: a shared LFS/storage quota group, the per-user
org-create flag, the per-repo Actions toggle, and the Renovate collaborator step (live in production, off unless RENOVATE_ENABLED=true).
Extracted from bitborg-infra's templated bash script into a standalone, unit-tested TypeScript project per ADR 0035, following the ADR 0033 runner-controller pattern: released as semver-tagged OCI images to the Forgejo registry and consumed by bitborg-infra as a pinned, Renovate-updated image. Keycloak stays the source of truth; this is a pure one-way projector.
- Public, AGPL-3.0.
- Stack: TypeScript (strict) on Node 24, pnpm v11 (Volta-pinned), Vitest, ESLint, Prettier.
Safety guarantees (the properties that matter most)
These are enforced at the boundary and covered by unit tests — they are not assumed:
- Fail-closed on a Keycloak read failure. If the token, any read group, role, role mapping or any page of a list can't be fetched, the run aborts having mutated nothing. A transient Keycloak error must never strip everyone's entitlements. Keycloak is read before any Forgejo write, so the abort is total.
- Refuses an all-empty tier read. If every tier group reads as empty while Forgejo has non-exempt users, the run aborts: that is a partial read, not a real state.
- Dry-run by default. No Forgejo mutation happens unless
RECONCILE_APPLY=true. Unset or any other value = dry-run (the run still reads and logs every proposed action). - Idempotent writes. A
409("already a member") on a quota-group add is treated as success; removals ignore404. Each run reads the quota group members and each repo'shas_actionsfirst and sends only the writes that differ, so a second run over an unchanged world sends no quota-group orhas_actionswrites.allow_create_organizationis not readable through the admin API, so it is still written once per account. A failed member read aborts the run before any account write. - Fail loud on config. Any missing or malformed required environment variable aborts the run with a clear message and a non-zero exit — it never silently no-ops.
- Best-effort Actions enforcement. The per-repo
has_actionstoggle needs token scopes the shared admin token may lack; a failure there warns and flags a degraded metric but never aborts the run and takes the critical quota/org enforcement down with it (#183). - Best-effort identity projection, reported under its own name. A refused
full_name/email write or rename warns and degrades the identity gauge — never the Actions one (#22). The two fail for unrelated reasons (a short token scope vs. a value the git host won't accept), so they never share a signal. - One refused account write does not stop the run. A refused quota-group add or removal, or org-create
write warns, counts and raises its own gauge, then the run moves to the next account. A refused
add skips that account's removals, so it never ends up in no group. A
404skips the account (deleted mid-run). Status0(Forgejo unreachable) still aborts (#83).
What it projects (the rules)
Per user (in precedence order):
- Exempt first-party users (
USER_EXEMPT) → the unlimited quota group. tier_basicortier_pro→ the sharedpaidquota group (LFS included — onesize:allrule over repos + LFS + packages; #184).tier_participant→ the zero-quotaparticipantgroup (ADR 0029).- No tier signal at all → fail-closed to
participant, with a warning (#125 H1).
Plus, per user: allow_create_organization from the ent_orgs role; the per-repo Actions toggle, on for every user
with a hosting quota (exempt, tier_basic, tier_pro) and for holders of the ent_runners_shared role
(ADR 0018); and, when enabled, the Renovate bot as a Write collaborator up
to a Free/Pro cap from the ent_renovate role (ADR 0024).
Tiers are flat Keycloak groups. Entitlements are realm roles. A user holds a role directly or
through a role mapping on a group they are in, so the reconciler reads the role's users, the
groups it is mapped onto, and the members of those groups and of their subgroups (ADR 0044).
Mapped groups are read by id, so a renamed group, a subgroup or a duplicate name all resolve. An
unknown id aborts the run with no changes. Tier groups are still found by exact top-level name. Composite roles are not expanded.
Tier and entitlement members join to Forgejo accounts by Keycloak user id, which equals the Forgejo
login_name, so a refused rename does not cost a user their entitlements (#81). A local account
(empty login_name) gets none of them. It can only be exempt, matched by login, case-insensitively.
Per org: exempt (first-party) orgs → unlimited group + Actions on; tenant orgs → the flat capped
group + Actions only when at least one org member is a paid user (tier_basic or tier_pro) or an exempt first-party user (#121, #37).
If the member list cannot be read, the org's Actions are left unchanged and the Actions gauge degrades.
Quota groups are modelled as exactly one size:all rule and any stray base/lfs rule is
detached — the workaround for Forgejo's most-permissive-quota-merge (a size:all cap combined
with the legacy base rule would be defeated by the merge). Legacy pre-#184 tier groups are
purged after users are moved off them.
Keycloak permissions the client needs
The KEYCLOAK_CLIENT_ID service account is read-only and holds no view-users or manage-users.
Those two realm roles bypass the scoped admin permissions. It gets exactly these grants (set in
bitborg-infra, opentofu/keycloak/service-accounts.tofu):
| Grant | Endpoints that need it |
|---|---|
realm-management role view-realm |
GET /roles/{role}/users, GET /roles/{role}/groups |
Users permission, scope view |
GET /users (identity projection) |
Groups permission, scope view |
GET /groups (tier group by name), GET /groups/{id}/children |
Groups permission, scope view-members |
GET /groups/{id}/members |
Plus the client-credentials token request. Every call is a GET.
The client must never call per-user endpoints such as GET /users/{id} or
GET /users/{id}/groups. They return 403 for this account, and the fakes in the tests accept any
path. src/keycloak-http.test.ts records every path each HttpKeycloakClient method requests and
fails on one that is not on its allowlist. Extend the allowlist and this section together.
Without the users view permission Keycloak can strip attributes from the user list. The identity
projection would then see no values, propose nothing and stay green. The run logs a warning when
GET /users returns users and none has an e-mail.
After any change to these grants, do a dry-run (RECONCILE_APPLY unset) against the live realm. Check
that a known drift (a changed display name or e-mail) is proposed in the log.
Configuration contract (cross-repo)
Every input crosses the bitborg-infra → reconciler boundary as an environment variable
(supplied by the infra EnvironmentFile + vault). See .env.example for the
canonical list with example values. Summary:
| Variable | Required | Shape / notes |
|---|---|---|
RECONCILE_APPLY |
no (default false) |
true to apply; anything else = dry-run |
FORGEJO_URL, KEYCLOAK_URL |
yes | https://… base URLs. KEYCLOAK_URL must reach /admin/* |
KEYCLOAK_REALM |
yes | realm name (bitborg) |
KEYCLOAK_CLIENT_ID |
yes | read-only service-account client (bitborg-reconciler) |
KEYCLOAK_CLIENT_SECRET |
yes (secret) | that client's secret (client_credentials grant) |
FORGEJO_TOKEN |
yes (secret) | scoped admin: write:admin + read:user + write:repository |
RESOLVE_IP |
no | pin hosts to the local Caddy (ADR 0017); unset = DNS |
PAID_GROUP, PARTICIPANT_GROUP, ORG_GROUP, ORG_UNLIMITED_GROUP |
yes | Forgejo quota group names |
PAID_LIMIT, ORG_LIMIT |
yes | integer bytes; -1 = unlimited, 0 = block |
LEGACY_QUOTA_GROUPS |
no (default none) | comma/space separated |
KEYCLOAK_GROUP_TIER_BASIC, …_TIER_PRO, …_PARTICIPANT |
yes | Keycloak group names |
KEYCLOAK_ROLE_ORGS, KEYCLOAK_ROLE_RUNNERS |
yes | Keycloak realm role names |
USER_EXEMPT, ORG_EXEMPT |
no (default none) | comma/space separated |
RENOVATE_ENABLED |
no (default false) |
when true, the four below become required |
RENOVATE_BOT, KEYCLOAK_ROLE_RENOVATE, RENOVATE_CAP_FREE, RENOVATE_CAP_PRO |
only if renovate on | bot handle, role, integer caps |
TEXTFILE_DIR |
no | node_exporter textfile dir for last-run metrics |
Semver / breaking-change policy for the contract: the env-var names and shapes above ARE the
public API of this repo. A change that renames, removes, or changes the required-ness/shape of a
variable is a MAJOR version bump (it requires a coordinated change to bitborg-infra's
EnvironmentFile). Adding a new optional variable with a safe default is a minor bump.
Metrics (node_exporter textfile collector)
When TEXTFILE_DIR is set, every run rewrites reconciler.prom atomically with these gauges —
all unlabelled, all "as of the last run". Alert rules in bitborg-infra key off these names, so
renaming one is a coordinated change (same rule as the env-var contract above).
| Metric | Meaning |
|---|---|
bitborg_reconciler_last_run_status |
Exit status of the last run (0 = ok). |
bitborg_reconciler_last_run_timestamp_seconds |
Unix time of the last run — the deadman/ReconcilerStale input. |
bitborg_reconciler_actions_enforcement_degraded |
1 = per-repo Actions (CI) enforcement was skipped/refused. Cause: admin token scope. |
bitborg_reconciler_identity_fields_corrected |
full_name/email values written this run (ADR 0038). |
bitborg_reconciler_identity_renames_applied |
Accounts renamed this run to follow a Keycloak rename (ADR 0038). |
bitborg_reconciler_identity_projection_degraded |
1 = Forgejo refused an identity write. Cause: a value Keycloak accepts and Forgejo doesn't. |
bitborg_reconciler_identity_failures |
Identity writes refused this run, per refused call. |
bitborg_reconciler_user_writes_degraded |
1 = Forgejo refused a quota-group add or org-create write for an account (#83). |
bitborg_reconciler_user_write_failures |
Those refused writes this run, per refused call. A 404 (account deleted mid-run) is not counted. |
On an aborted run only the status (set to 1) and the timestamp change. Every other gauge keeps the value from the last completed run, so an outage does not clear an alert that was firing (#85).
The last two identity gauges exist because they used to be reported as the Actions gauge, whose alert text sends
the operator after a token scope that was never the problem (#22). An identity failure is
permanent until the value is fixed — the projection recomputes the same diff every run — so
treat a non-zero …_identity_failures as "go and fix a value", not "wait for it to clear".
Local development
pnpm install
pnpm test # vitest (unit tests — fake Keycloak/Forgejo clients)
pnpm typecheck # tsc --noEmit (strict)
pnpm lint # eslint + prettier --check
pnpm build # tsc -> dist/
node dist/main.js # one pass, using the current environment (see .env.example)
The projection logic is pure and tested against in-memory fakes of the Keycloak/Forgejo clients — no network is touched by the test suite.
Deployment (stays in bitborg-infra)
The reconciler runs as a rootless Podman Quadlet oneshot container driven by a systemd
timer on the services host (every 5 min, Persistent=true) — one container run per pass, not a
daemon. bitborg-infra owns: the timer, the Quadlet unit (only its Image= changes), the
EnvironmentFile with the Keycloak client secret and the Forgejo token, all host-specific config, and both vault
secrets. This repo owns only the image and its behaviour.
Releases are cut by tagging vX.Y.Z, which builds and pushes
git.bitborg.se/bitborg/bitborg-auth-reconciler:vX.Y.Z + :sha-XXXX and creates a Forgejo
Release. There is no :latest tag and no AutoUpdate=registry: this image mutates real
production entitlements, so a human tags releases and Renovate opens the pinned-bump PR
(ADR 0033 / ADR 0035).
Release order: merge the version bump, verify main and package.json, then tag. A tag pushed before the bump merges builds the wrong commit.