No description
  • Go 75.8%
  • TypeScript 19.7%
  • CSS 3.4%
  • Go Template 0.6%
  • Dockerfile 0.2%
  • Other 0.3%
Find a file
renovate_bot bad40d2c91
All checks were successful
ci / frontend-test (push) Successful in 37s
ci / build-1 (push) Successful in 3m28s
ci / frontend-docker (push) Successful in 0s
ci / backend-test (push) Successful in 6m5s
ci / build (push) Successful in 2m48s
ci / backend-docker (push) Successful in 0s
ci / build-2 (push) Has been skipped
ci / chart (push) Successful in 0s
Update https://code.forgejo.org/forgejo/upload-artifact action to v5
2026-11-18 08:40:31 +00:00
.forgejo/workflows Update https://code.forgejo.org/forgejo/upload-artifact action to v5 2026-11-18 08:40:31 +00:00
backend fix suboptimal build for cross compile 2026-11-18 00:59:07 +00:00
deploy/helm/auth-server add nginxrun emptydir 2026-11-08 15:47:22 +01:00
frontend Update cgr.dev/chainguard/nginx Docker digest to 9708b6c 2026-11-17 23:47:52 +00:00
.dockerignore Add Go module, ignore rules and backend image 2026-11-07 12:51:35 +01:00
.gitignore Add Go module, ignore rules and backend image 2026-11-07 12:51:35 +01:00
README.md CI: port GitLab pipeline to Forgejo Actions 2026-11-18 01:44:30 +01:00
renovate.json add renovate config 2026-11-07 13:00:30 +01:00

Auth Server

A small OIDC provider with Traefik forward auth and a user account UI. Go backend, React frontend, one Helm chart.

  • Backend: Go, Gin, GORM, godotenv, go-libs (config and logging), gin-logrus. SQLite (default), MariaDB, PostgreSQL. No cgo.
  • Frontend: React, Vite, TypeScript. Light and dark theme follow the system setting.
  • Deploy: two images (backend, frontend) and one Helm chart. The ingress sends /api, /oauth2, /.well-known and /auth to the backend, everything else to the UI.

Status

Area State
OIDC code flow with PKCE, token, userinfo, discovery, JWKS done
OIDC RP-initiated logout at /oauth2/logout (id_token_hint may be expired, post_logout_redirect_uri must be a registered redirect URI, state), advertised as end_session_endpoint done, unit tested, not tried with a real relying party
Optional per UI client: add an unknown redirect URI on first sign-in (confidential clients only; not for Kubernetes or CLIENTS_FILE clients; stored after the sign-in and group check, audited as redirect_learned) done, unit tested, not checked in a browser
OIDC redirect URIs: http(s) or a custom app scheme such as app.immich:///oauth-callback; script and data schemes refused; authorization still needs an exact match with a registered URI done, unit tested
SAML identity provider (metadata, SSO with Redirect and POST binding, signed assertions, groups) done
Traefik ForwardAuth (/auth/forward, optional ?policy=) done
Local users, bcrypt passwords (8 to 72 characters, one rule for UI, admin, reset and ADMIN_PASSWORD), sessions done
LDAP login next to local users, several servers in priority order, group sync (periodic, at login, manual) done, tested with fake directories only
TOTP 2FA, replay protected done
Names per user (given and family name): from LDAP givenName and sn, or set by an admin; sent as name, given_name, family_name in ID token and userinfo, and as SAML common name done, unit tested and typechecked; LDAP attributes not tested against a real server, users get names at the next sync
Passkeys as second factor and as passwordless sign-in, also for LDAP users done, tested with a software authenticator, not yet with real hardware
Group policies for OIDC apps, SAML apps and forward auth done
Group management in the admin UI: create, rename (follows apps, policies and members), delete (refused while in use), add and remove members; users may only join registered groups done, tested through the API and typechecked; not checked in a browser
Auth history, allowed apps, password change, security settings in the UI done
Auth history and admin events show the app name (OIDC client or SAML app) next to its ID done, unit tested and typechecked, not checked in a browser
Designed error pages for OIDC, SAML and forward-auth failures (unknown app, unregistered redirect, access denied, bad SAML request, 404, expired) done, wording fixed in the UI; the server only sends a code, through a short-lived server-side reference
Browser title per page, favicon, touch icons and web manifest done
Responsive UI: top bar on desktop, bottom tab bar on phones, tables become cards, dialogs become bottom sheets, automatic dark mode done, checked with screenshots at 390 px and 1280 px in headless Chromium; not tried on real phones or other browsers
Admin UI: users, OIDC apps, SAML apps (add, edit, delete, IdP details and metadata download), forward auth policies, LDAP servers (add, test, sync), events done, checked by typecheck and build only, not in a browser
Kubernetes CRDs OIDCClient, SAMLProvider, ForwardAuth with controller done, tested with a fake client, not on a real cluster
Kubernetes CRDs Group (registers a group) and GroupAssignment (gives users groups, declared per user name; removing it takes the groups back). CRD groups are read-only in the admin UI, and a group still used by an app, policy, member or assignment is never pruned done, tested with a fake client, not on a real cluster
Secret per OIDCClient in its namespace, Traefik Middleware per ForwardAuth done, same limits
Swagger UI at /swagger/index.html done
Security headers: Content-Security-Policy and Permissions-Policy on backend (looser CSP for Swagger) and UI nginx done, backend unit tested, nginx not checked in a browser
Login rate limiting, shared by all replicas done, in Redis or in the SQL database
Redis for sign-in steps, auth codes, rate limits and job leases (optional, SQL fallback) done, tested against an in-process Redis, not a real server
Multiple backend replicas (PostgreSQL or MariaDB) done, tested with two servers on one database; SQLite is single replica only
Helm: DB from config.db.* with the password in a secret, each secret value inline or external, CI sets image repo and tag done, checked with helm lint and helm template only, not deployed
Database migrations with gormigrate in a dedicated Helm hook Job; pods only wait and check done, tested with the real binary on SQLite (also adopting a database from before migrations), not on PostgreSQL or MariaDB, the Job not run on a cluster
Tests, Forgejo pipeline, Helm chart, two images done. The chart uses the commit SHA as image tag (empty image.tag means appVersion) and CI checks it. CRD schemas are checked by a test, since helm lint misses bad keys; CRDs were never applied to a real API server by me
Recovery codes for 2FA (10 one-time codes, shown once, regenerate any time) done
Admin reset of a user's 2FA done
Password reset by email (30 minute single-use link, needs SMTP) done, tested against a fake SMTP server and a fake mailer, not a real mail server
LDAP against a real server not tested
LDAP servers as Kubernetes resources not done (settings live in the admin UI)

Local development

cd backend
ISSUER=http://localhost:8080 ADMIN_PASSWORD=dev-admin-password go run ./cmd/server   # API on :8080
cd frontend && npm ci && npm run dev                                                # UI on :5173, proxies to :8080

Tests: cd backend && go test ./... and cd frontend && npm test.

Configuration

Environment variables. The server reads a .env file if present.

Variable Default Purpose
ISSUER – (required) Public base URL. Becomes the OIDC iss claim
LISTEN_ADDR :8080 HTTP listen address
DB_DRIVER sqlite sqlite, mariadb or postgres
DB_DSN data/auth.db SQLite file path, or the driver DSN for a server database
SIGNING_KEY_PATH – PKCS#8 RSA key (PEM). Without it a new key is made at each start
CLIENTS_FILE – JSON list of OIDC clients, upserted at start-up (see below)
ADMIN_USERNAME / ADMIN_PASSWORD admin / – First user, created when missing, in group admins
SESSION_TTL 12h Browser session lifetime
COOKIE_SECURE true Secure flag on the session cookie
TRUSTED_PROXIES – CIDRs of the ingress, whose X-Forwarded-For is used for the auth history
ALLOWED_RETURN_DOMAINS – Domains a login may redirect to, besides the issuer host
LOGIN_RATE_PER_MINUTE 10 Login attempts per user name, and three times that per IP
WEBAUTHN_RP_NAME Auth Server Name the browser shows for passkeys
SMTP_HOST, SMTP_FROM – Turn on password reset by email. More: SMTP_PORT (587), SMTP_USERNAME, SMTP_PASSWORD, SMTP_SECURITY (starttls, tls, none)
REDIS_URL – redis://:password@host:6379/0 (rediss:// for TLS). Or REDIS_ADDR and REDIS_PASSWORD
KUBE_ENABLED false Run the CRD controller. KUBE_SERVICE_URL and KUBE_RESYNC tune it
LOG_LEVEL INFO ERROR, WARN, INFO or DEBUG (go-libs)

CLIENTS_FILE example. The secret is read from the env var named in client_secret_env and stored as a bcrypt hash. Leave client_secret_env out for a public client, which then must use PKCE.

[
  {
    "client_id": "grafana",
    "name": "Grafana",
    "client_secret_env": "GRAFANA_OIDC_SECRET",
    "redirect_uris": ["https://grafana.example.com/login/generic_oauth"],
    "allowed_groups": ["admins"]
  }
]

Traefik forward auth

The chart creates a Middleware (traefik.io/v1alpha1) named auth-forward in the release namespace. Apps use it with:

traefik.ingress.kubernetes.io/router.middlewares: <namespace>-auth-forward@kubernetescrd

Unauthenticated requests get a 302 to the login page with the original URL. Authenticated requests pass with the headers X-Auth-User and X-Auth-Groups. Traefik overwrites client-sent copies of these headers.

Kubernetes resources

With kube.enabled (default in the chart) the backend reconciles these resources every 15 s. Rows and objects it creates are read-only in the admin UI. It never changes a Secret or Middleware it did not create.

apiVersion: auth.jonasled.dev/v1alpha1
kind: OIDCClient           # creates Secret grafana-oidc in this namespace: client_id, client_secret, endpoints
metadata: { name: grafana, namespace: apps }
spec:
  redirectUris: [https://grafana.example.com/login/generic_oauth]
  allowedGroups: [admins]
---
apiVersion: auth.jonasled.dev/v1alpha1
kind: ForwardAuth          # creates Traefik Middleware whoami in this namespace, limited to the groups
metadata: { name: whoami, namespace: apps }
spec:
  allowedGroups: [staff]

Anyone who can create these resources can register apps, so limit that with RBAC.

Database migrations

The schema is managed with gormigrate (GORM), as its own step:

auth-server migrate        # apply the migrations that have not run yet
auth-server wait-schema    # wait until every migration of this version is applied (WAIT_SCHEMA_TIMEOUT, default 10m)

Applied migrations are recorded in the migrations table. The server does not migrate when it starts: it checks that every migration it knows is recorded and refuses to start otherwise. A database that is ahead (migrated by a newer version) is accepted, so rolling the application back keeps working. With MariaDB or PostgreSQL the chart runs auth-server migrate in a Helm hook Job (pre-upgrade, and post-install on the first install). New pods have an init container that waits for it, so pods never migrate, never race, and a failed migration stops the rollout. migrations.job.enabled=false turns the Job off; run auth-server migrate before each upgrade. SQLite is migrated by its single pod at start (MIGRATE_ON_START=true), because a Job could not share its volume. PostgreSQL and SQLite roll a failed migration back; MariaDB cannot roll back DDL.

A new database gets the whole current schema in one step. A database from before migrations existed is adopted by the same step, without losing data. To change the schema, edit the model, append a migration with a new timestamp ID to migrations() in backend/internal/database/migrate.go (never edit an old one, and do not use the live models inside it), and update modelsFingerprint in migrate_test.go. That test fails whenever a model changes, as the reminder.

Signing key

One RSA key (PKCS#8 PEM) signs OIDC tokens and SAML assertions. The server also derives the keys that seal TOTP secrets and LDAP bind passwords from it, and the SAML certificate comes from it. Create it once and keep a backup:

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out signing.pem
kubectl -n auth-server create secret generic auth-signing --from-file=signing.pem=signing.pem
# Helm: --set signingKey.existingSecret=auth-signing      Local: SIGNING_KEY_PATH=./signing.pem

Without a key a new one is made at every start, which breaks tokens, authenticator apps and saved LDAP passwords after a restart, and does not work with several replicas. If you replace the key, users must set up their authenticator apps again and LDAP bind passwords must be entered again.

Running several replicas

Use PostgreSQL or MariaDB and a shared signing key (signingKey.existingSecret); the chart refuses anything else. All state is in the database: sessions, auth codes, second-factor steps, passkey ceremonies. Any replica can serve any step of a flow, and single-use items (auth codes, TOTP steps, challenges) are consumed with atomic statements. Periodic jobs (LDAP sync, the Kubernetes controller) run on one replica at a time through a lease row, and another replica takes over about a minute after the holder dies. The schema is migrated once by a Job, not by the pods (see below). The chart adds a PodDisruptionBudget and spreads pods over nodes. Rate limit counters, sign-in steps, auth codes and job leases are kept in Redis when REDIS_URL (or REDIS_ADDR and REDIS_PASSWORD) is set, else in the SQL database. Use Redis in production: the SQL fallback writes on every login attempt.

helm install auth deploy/helm/auth-server --set backend.replicaCount=3 --set config.dbDriver=postgres \
  --set persistence.enabled=false --set signingKey.existingSecret=auth-signing \
  --set config.db.host=db.internal --set secrets.values.DB_PASSWORD.secretName=auth-db --set secrets.values.DB_PASSWORD.key=password \
  --set redis.internal.enabled=true --set secrets.values.REDIS_PASSWORD.secretName=auth-redis --set secrets.values.REDIS_PASSWORD.key=password

Helm

helm install auth deploy/helm/auth-server --set host=auth.example.com \
  --set signingKey.existingSecret=auth-signing --set secrets.values.ADMIN_PASSWORD.secretName=auth-admin \
  --set secrets.values.ADMIN_PASSWORD.key=password

Each entry under secrets.values is either an inline string (local tests only) or {secretName, key} pointing at a key of a Secret you provide. The DSN is built by the chart from config.db.* plus secrets.values.DB_PASSWORD. The signing key secret holds signing.pem. Without it, tokens stop working at every restart. Several backend replicas need a server database and the signing key secret; the chart refuses other combinations.

Pipeline

.forgejo/workflows/ci.yml: backend (modules from https://goproxy.jonasled.dev) gofmt, vet, swagger docs check and tests; frontend typecheck, tests and build; both images; Helm lint, render and push of the chart to the project's OCI registry (images and chart through the reusable workflows in infra/ci-snippets).