Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,84 @@
|
||||
# Phase 09 — Authentik + Admin-SSO
|
||||
|
||||
**Dauer:** 1.5 Wochen (Wall-Clock — sequenziell, da nur 2 Tasks mit harter Abhängigkeit), ca. 8-10 Personentage Aufwand
|
||||
**Tasks:** 2
|
||||
**Ziel:** Eine eigene, self-hosted Identity-Provider-Instanz (Authentik) auf dem Hetzner-Server hochziehen und das Admin-Panel der Boilerplate (`https://admin.{domain}`) auf OIDC-basiertes SSO gegen diese Authentik-Instanz umstellen. Email/Passwort-Login für Admins bleibt nur noch als gekapselter Notfall-Fallback hinter einem Env-Flag bestehen. Diese Phase legt zusätzlich das Fundament für den späteren Customer-Tenant-SSO (Backlog-Item #66), der dieselbe Authentik-Instanz mit einem zweiten OIDC-Provider-Definition nutzen wird.
|
||||
|
||||
## Warum diese Phase jetzt
|
||||
|
||||
- **Admin-Konten sind das attraktivste Angriffsziel** der Plattform — sie haben Tenant-übergreifende Sichtbarkeit, Impersonation-Rechte und Zugriff auf Audit-Logs. Eine zweite Schutzschicht (zentrale IdP mit MFA-Pflicht + zentralem Lifecycle-Management) reduziert das Risiko deutlich gegenüber einem einfachen Email/Passwort-Login.
|
||||
- **Phase 02 (Observability) ist Voraussetzung,** weil die Authentik-Container ebenfalls Logs + Sentry-Events absetzen sollen. Ohne self-hosted Sentry wären Authentik-Fehler nicht zentral sichtbar.
|
||||
- **Phase 01 (TOTP-Konsolidierung) ist Voraussetzung,** weil die zweite, App-interne MFA-Schicht (für sensible Actions wie Impersonation) auf der konsolidierten otpauth-Variante aufsetzt. Wir wollen nicht beide TOTP-Implementierungen mit OIDC-Code mischen.
|
||||
- **Backlog-Item #66 (Customer-Tenant-SSO)** lebt von der hier hochgezogenen Authentik-Instanz. Wenn wir das Tenant-SSO später aktivieren, ist der Großteil der Infra schon da — wir brauchen dann nur noch eine zweite OIDC-Provider-Definition in Authentik + den Tenant-Client in der Web-App.
|
||||
- **Self-hosted statt SaaS** (Auth0/Clerk/WorkOS) — Begründung wie bei Sentry: DSGVO-Profil, Hetzner-Server vorhanden, keine US-Cloud-Abhängigkeit für Identity-Daten.
|
||||
|
||||
## Hetzner-Staging-Kontext
|
||||
|
||||
Authentik wird als zusätzlicher Coolify-managed Docker-Compose-Stack auf dem bestehenden Hetzner-Staging-Server deployed (siehe `../AGENT-INSTRUCTIONS.md` §Regel 6 + `../archive/STAGING-ACCESS.md`). Eigene Subdomain `auth.<staging-domain>` mit TLS-Termination via Traefik/Caddy (Coolify-Default). Die Web-App reicht ihre Admin-OIDC-Flows direkt an diese lokale Instanz weiter — kein Daten-Egress.
|
||||
|
||||
Für Production wird empfohlen, Authentik auf einem **separaten, gehärteten Server** zu betreiben (kein Co-Hosting mit der App-DB, eigene Firewall-Zone), um Compromise-Blast-Radius klein zu halten. Das Setup-Doku (`docs/operations/authentik-setup.md`) deckt beide Varianten ab (Coolify-Single-Server + dedizierter Hetzner-Server).
|
||||
|
||||
## Task-Reihenfolge
|
||||
|
||||
| Reihenfolge | Task-ID | Datei | Aufwand | Parallelisierbar mit |
|
||||
|---|---|---|---|---|
|
||||
| 1 | #81 | `authentik-setup.md` | 2-3d | — (Infra-Voraussetzung für #82) |
|
||||
| 2 | #82 | `admin-oidc-login.md` | ~1 Woche (5-7d) | — (braucht #81 fertig) |
|
||||
|
||||
## Dependency-Graph (intern + extern)
|
||||
|
||||
```
|
||||
[Phase 01: totp-consolidation #26] ─┐
|
||||
│
|
||||
[Phase 02: sentry-selfhost #29] ────┤
|
||||
▼
|
||||
#81 authentik-setup
|
||||
│
|
||||
▼
|
||||
#82 admin-oidc-login
|
||||
│
|
||||
▼
|
||||
[Phase 11 Backlog: customer-tenant-sso #66]
|
||||
(entblockt — gleiche Authentik-Instanz, zweiter Provider)
|
||||
```
|
||||
|
||||
**Praktisch parallelisierbar (Multi-Agent-Setup):** kaum sinnvoll innerhalb der Phase, da #82 hart auf einer laufenden Authentik-Instanz aus #81 aufbaut (OIDC-Discovery-Endpoint, Provider-IDs, Group-Mappings müssen real existieren). Ein Agent kann jedoch parallel an `docs/operations/admin-sso.md` arbeiten, während ein anderer #81 implementiert.
|
||||
|
||||
## Phase Done-Definition
|
||||
|
||||
Diese Phase ist `completed` wenn:
|
||||
|
||||
- [ ] Alle 2 Tasks `completed` in `PROGRESS.md`
|
||||
- [ ] Authentik auf Staging-Hetzner unter `https://auth.<staging-domain>` erreichbar, Admin-Login mit MFA funktioniert
|
||||
- [ ] Zwei OIDC-Provider-Definitions in Authentik existieren: `toolctrl-admin-panel` (live) und `toolctrl-tenant-sso` (Platzhalter, deaktiviert)
|
||||
- [ ] Authentik-Groups `toolctrl-admin` + `toolctrl-staff` existieren, MFA (TOTP) ist für `toolctrl-admin` Pflicht (Authentik-Policy)
|
||||
- [ ] Admin-Login über `/auth/admin/login` führt komplett durch (Authorize → Callback → Session-Cookie → Admin-Dashboard sichtbar)
|
||||
- [ ] JIT-Provisioning erstellt einen `AdminUser`-Record beim ersten Login mit korrekt gemappter Rolle
|
||||
- [ ] Logout via `/auth/admin/logout` killt lokale Session UND triggert Authentik-End-Session-Endpoint
|
||||
- [ ] Email/Passwort-Fallback nur aktiv bei `ADMIN_FALLBACK_LOGIN_ENABLED=true`, in `.env.example` defaults auf `false`
|
||||
- [ ] App-interne MFA-Schicht (otpauth aus #26) ist als zweiter Layer für sensible Actions verdrahtet (z.B. Impersonation, Tenant-Löschung)
|
||||
- [ ] Audit-Events `admin.login.sso.success`, `admin.login.sso.failure`, `admin.login.fallback.success`, `admin.logout.sso` werden in `AuditEvent` geschrieben
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` global grün
|
||||
- [ ] `docs/operations/authentik-setup.md` (Deploy + Backup + Update + Health-Checks) angelegt
|
||||
- [ ] `docs/operations/admin-sso.md` (Group-Setup + Fallback-Recovery + Operator-Runbook) angelegt
|
||||
- [ ] `.env.example` enthält neue Keys: `AUTHENTIK_ISSUER_URL`, `AUTHENTIK_ADMIN_CLIENT_ID`, `AUTHENTIK_ADMIN_CLIENT_SECRET`, `AUTHENTIK_ADMIN_REDIRECT_URI`, `AUTHENTIK_END_SESSION_URL`, `ADMIN_FALLBACK_LOGIN_ENABLED`, `ADMIN_FALLBACK_LOGIN_EMAILS` (allowlist)
|
||||
- [ ] `gsd-code-reviewer`-Subagent hat alle Phase-09-Commits reviewed; Findings adressiert
|
||||
- [ ] Backup-Restore-Drill für Authentik-Postgres erfolgreich (mind. 1x manuell durchgespielt)
|
||||
- [ ] Phase-Summary in dieser README.md ergänzt
|
||||
|
||||
## Phase Summary
|
||||
|
||||
_(Wird nach Abschluss der Phase vom ausführenden Agent ergänzt.)_
|
||||
|
||||
### Lessons Learned
|
||||
|
||||
_(Wird nach Abschluss ergänzt.)_
|
||||
|
||||
## Verweise
|
||||
|
||||
- Detail-MD-Template: `../DETAIL-MD-TEMPLATE.md`
|
||||
- Agent-Workflow: `../AGENT-INSTRUCTIONS.md`
|
||||
- Execution-Order: `../00-execution-order.md`
|
||||
- Live-Status: `../PROGRESS.md`
|
||||
- Vorgänger-Phasen: `../01-tech-debt-foundation/README.md`, `../02-observability/README.md`
|
||||
- Folgendes Backlog-Item (entblockt durch diese Phase): `../11-backlog/customer-tenant-sso.md` (#66)
|
||||
@@ -0,0 +1,366 @@
|
||||
# Verification — Phase 09 (Authentik + Admin-SSO)
|
||||
|
||||
**Verifier:** general-purpose subagent (read-only review)
|
||||
**Datum:** 2026-05-16
|
||||
**Files geprüft:** `README.md`, `authentik-setup.md` (#81), `admin-oidc-login.md` (#82)
|
||||
**Referenz:** `../DETAIL-MD-TEMPLATE.md`, `../AGENT-INSTRUCTIONS.md`, `../00-execution-order.md`
|
||||
|
||||
---
|
||||
|
||||
## TL;DR
|
||||
|
||||
Phase 09 ist **inhaltlich exzellent vorbereitet** — eine der vollständigsten Phasen im gesamten Improvement-Plan. Beide Detail-MDs decken Crypto-Pflichten (State/PKCE/Nonce/JWKS), JIT-Provisioning, Fallback-Strategie, Disaster-Recovery, Audit-Wiring und Defense-in-Depth-MFA sauber ab. Die Infra-Sizing-Annahmen sind realistisch, Coolify/Traefik-Integration ist konkret, und der Backlog-Hook für #66 (Tenant-SSO) ist explizit über den deaktivierten zweiten Provider verdrahtet.
|
||||
|
||||
**Findings:** 3 Major (Process/Convention), 6 Minor (Konsistenz/Klarheit), 4 Nice-to-have (Empfehlungen).
|
||||
**Empfehlung:** Mit Minor-Fixes ready für Execution. Major #1 (CLAUDE.md-Routes-Konvention) sollte vor Start adressiert werden.
|
||||
|
||||
---
|
||||
|
||||
## 1. Template-Konformität (Section-Reihenfolge)
|
||||
|
||||
Template-Pflichtreihenfolge laut `DETAIL-MD-TEMPLATE.md`:
|
||||
Frontmatter → Problem → Depends on → Blocks → Approach → Implementation Steps → Test Requirements → Acceptance Criteria → Rollback Strategy → Security Notes → Subagent Recommendations → Staging-Deployment-Steps → Deviations from Plan → Progress Log → Lessons Learned
|
||||
|
||||
| Datei | Sections vollständig | Reihenfolge korrekt | Frontmatter komplett |
|
||||
|---|---|---|---|
|
||||
| `authentik-setup.md` | Ja (alle 15) | Ja | Ja (Status/Task-ID/Phase/Effort/Owner) |
|
||||
| `admin-oidc-login.md` | Ja (alle 15) | Ja | Ja |
|
||||
|
||||
**README.md** ist keine Detail-MD und folgt einer eigenen Phase-Übersichts-Struktur (Phase-Done-Definition, Dependency-Graph, Phase-Summary-Slot) — passt zum Stil der anderen Phase-READMEs und ist gut.
|
||||
|
||||
**Ergebnis:** Konform.
|
||||
|
||||
---
|
||||
|
||||
## 2. Dependency-Konsistenz
|
||||
|
||||
### 2.1 Interne Reihenfolge
|
||||
|
||||
- `authentik-setup.md` (#81) deklariert sich als Blocker für `admin-oidc-login.md` (#82) — korrekt
|
||||
- `admin-oidc-login.md` (#82) führt #81 als Dependency — korrekt
|
||||
- `00-execution-order.md` listet beide in dieser Reihenfolge ("sequenziell") — konsistent
|
||||
- README.md Task-Reihenfolge-Tabelle matched
|
||||
|
||||
### 2.2 Cross-Phase-Dependencies (deklariert vs. tatsächlich)
|
||||
|
||||
| Deklariert in #81/#82 | Cross-Check | Status |
|
||||
|---|---|---|
|
||||
| `02-observability/sentry-selfhost-setup.md` (#29) | `00-execution-order.md` Phase-09-Sektion bestätigt | OK |
|
||||
| `02-observability/sentry-wiring-api-worker.md` (#30) (in #81 als "best practice") | Konsistent | OK |
|
||||
| `01-tech-debt-foundation/dep-updates.md` (#28) ("best practice, kein hartes Block") | Konsistent | OK |
|
||||
| `01-tech-debt-foundation/totp-consolidation.md` (#26) in #82 | Korrekt verlinkt | OK |
|
||||
| `11-backlog/customer-tenant-sso.md` (#66) als Blocked-By beider | Konsistent in README + beiden Detail-MDs | OK |
|
||||
|
||||
### 2.3 Diskrepanz `00-execution-order.md`
|
||||
|
||||
`00-execution-order.md` §"Phase 09 — Authentik + Admin-SSO":
|
||||
|
||||
> **Depends on:** Phase 02 (Sentry für Authentik-Container)
|
||||
|
||||
Nennt nur Phase 02. Die Detail-MD `authentik-setup.md` listet zusätzlich `dep-updates.md` aus Phase 01 (als "best practice, kein hartes Block"), und `admin-oidc-login.md` listet `totp-consolidation.md` (#26) aus Phase 01 als hart abhängig. → **Inkonsistenz Minor #M1.**
|
||||
|
||||
`00-execution-order.md` sollte zusätzlich Phase 01 (mind. #26) als Hard-Dependency für Phase 09 nennen, sonst kann ein Agent #82 starten ohne dass #26 fertig ist.
|
||||
|
||||
---
|
||||
|
||||
## 3. Implementation-Steps — Qualitäts-Review
|
||||
|
||||
### 3.1 Authentik docker-compose (4 Container, 2 GB RAM Minimum)
|
||||
|
||||
- 4 Container (server/worker/postgres/redis) — entspricht dem offiziellen Authentik-Compose. Korrekt.
|
||||
- Sizing-Annahme **2 GB RAM hartes Minimum, 4 GB empfohlen** — realistisch. Authentik-Docs nennen für Production tatsächlich ~2 GB Floor; Worker + Server zusammen sind die größten Verbraucher. Healthchecks (`/-/health/live/`, `ak healthcheck`, `pg_isready`, `redis-cli ping`) sauber spezifiziert.
|
||||
- `mem_limit: 2g` pro Container ist im Override-Compose erwähnt — klar.
|
||||
- **Lücke Minor #M2:** Es fehlt eine Notiz zu **Hetzner-Server-Mindestgröße**. Bei Co-Location mit der App + Sentry + Authentik auf einem CX31 (8 GB) wird's eng. Im README wird "separater gehärteter Server für Production" empfohlen, aber für Staging fehlt ein expliziter Mindest-vCPU/RAM-Hinweis.
|
||||
|
||||
### 3.2 Traefik/TLS auf `auth.<domain>`
|
||||
|
||||
- Step 4 dokumentiert Traefik-Labels (Host-Rule, websecure-Entrypoint, letsencrypt-Cert-Resolver, HSTS, X-Frame-Options=DENY, Referrer-Policy)
|
||||
- CSP-Header explizit über Traefik-Middleware (nicht im Container) — gute Entscheidung wegen Authentik-Eigen-CSP-Konflikt-Potenzial
|
||||
- **Lücke Minor #M3:** Wildcard-Cert-Hinweis für `auth.*`-Subdomain ist nur in "Lessons Learned" als typische Stolperfalle erwähnt. Sollte in Implementation-Step 4 explizit dokumentiert sein (DNS-Challenge vs. HTTP-Challenge bei Subdomain-Setup).
|
||||
|
||||
### 3.3 Bootstrap-Script + Blueprints
|
||||
|
||||
- 7 Blueprints (00-flows, 10-groups, 20-policies, 30-providers, 40-applications, 50-outposts, 60-tenants, 70-brute-force, 80-notifications)
|
||||
- Idempotenz erwähnt, `bootstrap.sh` wartet auf `/-/health/ready/`
|
||||
- Zwei OIDC-Provider-Definitions im 30-providers-Blueprint: `toolctrl-admin-panel` (aktiv) + `toolctrl-tenant-sso` (Platzhalter, `enabled: false`) — perfekt für #66-Vorbereitung
|
||||
- Token-TTLs explizit: access_code=1min, access_token=10min, refresh=7d, id_token=10min — RFC-konform und konservativ
|
||||
- **Sinnvoll und sauber.**
|
||||
|
||||
### 3.4 Authentik-Groups + Mapping zu AdminUser
|
||||
|
||||
- `toolctrl-admin` (attribute `role: super_admin`) und `toolctrl-staff` (attribute `role: staff`)
|
||||
- Mapping in #82 step 7 (`mapGroupsToRole`): höchste Priorität `super_admin`, sonst `staff`, sonst `null` → 403
|
||||
- Re-Sync bei jedem Login (Authentik = Source-of-Truth) — korrekt, dokumentiert in Approach + Tests
|
||||
- **Sauber.**
|
||||
|
||||
### 3.5 MFA-Pflicht für Admin-Group
|
||||
|
||||
- `20-policies.yaml` enthält Expression-Policy `require-mfa-totp-for-admin`
|
||||
- Im Flow vor Success-Stage — Security-Notes bestätigt dass das MUSS ist
|
||||
- E2E-Test "MFA-Enrollment-Flow durchspielbar" deckt das ab
|
||||
- **Pflicht durchgesetzt, gut.**
|
||||
|
||||
### 3.6 OIDC-Client in `apps/web/app/modules/admin-sso/` mit `openid-client`
|
||||
|
||||
- Library-Wahl mit klarer Begründung (vs. oidc-client-ts/next-auth/eigenbau)
|
||||
- Modul-Struktur: `client.server.ts`, `state.server.ts`, `jit-provisioning.server.ts`, `claims.server.ts`, `logout.server.ts`, `audit.server.ts` — klare Separation-of-Concerns
|
||||
- Discovery via `Issuer.discover(env.AUTHENTIK_ISSUER_URL)`, JWKS-Auto-Cache durch Library
|
||||
- **Korrekt.**
|
||||
|
||||
### 3.7 Routes /auth/admin/login + /auth/admin/callback
|
||||
|
||||
- PKCE (`generators.codeVerifier`/`codeChallenge`), State, Nonce alle drei in `createLoginChallenge()`
|
||||
- Single-use Cookie `admin_sso_challenge` mit HttpOnly+Secure+SameSite=Lax+Path=/auth/admin+MaxAge=600s — sauber
|
||||
- Callback verifiziert State/Nonce/Signature/iss/aud/exp + `email_verified` (in Security-Notes explizit)
|
||||
- Session-Fixation-Schutz (Session-ID-Rotation nach Callback) in Security-Notes — gut, sollte aber in Implementation-Step 6 als konkreter Sub-Step landen → **Minor #M4**
|
||||
- **Secure-by-Design.**
|
||||
|
||||
### 3.8 JIT-Provisioning
|
||||
|
||||
- 3-Stufen-Lookup (ssoSubjectId → email-Fallback → 403)
|
||||
- Transaction-safe + Unique-Constraint-Schutz gegen Race-Conditions
|
||||
- Test-Cases dazu in Test-Requirements
|
||||
- **Sauber.**
|
||||
|
||||
### 3.9 Fallback-Login via `ADMIN_FALLBACK_LOGIN_ENABLED` + Email-Allowlist
|
||||
|
||||
- Env-gegated, Allowlist via `ADMIN_FALLBACK_LOGIN_EMAILS`
|
||||
- `assertFallbackLoginAllowed`-Server-Guard VOR Passwort-Check
|
||||
- AuditEvent severity=warn + Sentry-Breadcrumb
|
||||
- Disclosure-Toggle nur wenn Flag true, Default false
|
||||
- Brute-Force-Schutz separat erwähnt (Security-Notes)
|
||||
- **Als Emergency-Path ausreichend gehärtet.**
|
||||
- **Empfehlung NTH #N1:** Optional Slack/Discord-Alert ist erwähnt — sollte als konkreter Sub-Step im Doku/Operator-Runbook landen statt nur als "optional hook later".
|
||||
|
||||
### 3.10 Logout-Flow mit RP-Initiated-Logout
|
||||
|
||||
- Step 8: Lokale Session-Kill + `client.endSessionUrl({id_token_hint, post_logout_redirect_uri})`
|
||||
- Fallback wenn `id_token` fehlt (Fallback-Login-Pfad): nur lokale Session, kein Authentik-Redirect — **richtig gedacht**
|
||||
- Logout-Idempotenz in Security-Notes erwähnt
|
||||
- **Korrekt.**
|
||||
|
||||
### 3.11 App-MFA-Layer NACH OIDC für sensible Actions
|
||||
|
||||
- `SENSITIVE_ADMIN_ACTIONS = ['impersonation.start', 'tenant.delete', 'permission.grant', 'audit.export', 'data.export']`
|
||||
- `requireAppMfa(request, actionKey)` mit 15-Min Server-Side-Cache (`lastAppMfaAt` in Session-Store, NICHT Cookie)
|
||||
- Nutzt konsolidierte otpauth aus #26 (explizit als Acceptance-Criteria geprüft)
|
||||
- Defense-in-Depth-Begründung in Approach klar
|
||||
- Tests dazu in Unit + E2E
|
||||
- **Funktioniert konzeptionell, gut isoliert.**
|
||||
|
||||
---
|
||||
|
||||
## 4. Test-Requirements
|
||||
|
||||
### 4.1 OIDC-Flow-Tests via Mock-Authentik
|
||||
|
||||
- `msw` oder Lokal-Container als Mock erwähnt
|
||||
- Konkrete negative-Tests: State-Mismatch, Nonce-Mismatch, Expired-Token, Empty-Group-Claim
|
||||
- **Vorhanden — gut.**
|
||||
- **Empfehlung NTH #N2:** `openid-client` selbst hat keine Test-Doubles als first-class-feature; `msw`-Setup für OIDC-Endpoints sollte als wiederverwendbares Fixture in `apps/web/tests/fixtures/authentik-mock.ts` angelegt werden (auch nützlich für #66 später). Sollte als konkreter Sub-Schritt im Test-Block landen.
|
||||
|
||||
### 4.2 Playwright-E2E des Login-Flows
|
||||
|
||||
- 6 Szenarien: Happy-Path-SSO, JIT-Provisioning, Logout, Fallback-Erfolg, Fallback-Reject, Fallback-Toggle-Hidden, App-MFA-Gate
|
||||
- Gegen Staging-Authentik — explizit
|
||||
- **Komplett.**
|
||||
|
||||
### 4.3 Fallback-Recovery-Drill
|
||||
|
||||
- Sowohl in `Test Requirements` als auch in `Staging-Deployment-Steps` (#12) als manueller Drill spezifiziert
|
||||
- "NICHT als completed markieren bevor … MANUELL einmal end-to-end durchgespielt"
|
||||
- **Pflicht-Drill korrekt verankert.**
|
||||
|
||||
### 4.4 Restore-Drill für Authentik-Postgres
|
||||
|
||||
- `infra/authentik/scripts/restore-drill.sh` als Test-File spezifiziert
|
||||
- 24h-Backup-Verifikation + manueller Restore mit Smoke-Login danach
|
||||
- **Korrekt.**
|
||||
|
||||
### 4.5 Coverage-Target
|
||||
|
||||
- `≥85%` Lines/Branches im Modul, `100%` auf `claims.server.ts` + `state.server.ts` (security-kritisch) — **angemessen scharf**.
|
||||
|
||||
---
|
||||
|
||||
## 5. Security-Notes — Vollständigkeit
|
||||
|
||||
| Aspekt | Abdeckung |
|
||||
|---|---|
|
||||
| State + Nonce + PKCE Pflicht | Ja (Security-Notes + Tests negative-Cases) |
|
||||
| JWT-Signature gegen JWKS | Ja (Auto via openid-client, mit Library-Upgrade-Hinweis) |
|
||||
| `email_verified=true` prüfen | Ja (explizit, mit Begründung Email-Hijack) |
|
||||
| Audit jeder Admin-Login/Logout in AuditEvent | Ja (Step 12 + Audit-Wiring-Tabelle) |
|
||||
| Session-Fixation (ID-Rotation nach Callback) | Ja (Security-Notes) — siehe Minor #M4 |
|
||||
| Code-Verifier nicht loggen | Ja (Sentry-Breadcrumb-Filter erwähnt) |
|
||||
| Group-Claim als Trust-Anchor | Ja (mit Hinweis auf Authentik-Hardening) |
|
||||
| Fallback-Bypass-Risiko | Ja (kurze Allowlist, warn-Severity, Operator-Pflicht) |
|
||||
| App-MFA-Cache nicht im Cookie | Ja (explizit Session-Store) |
|
||||
| Logout-Idempotenz | Ja |
|
||||
| Redirect-URI-Whitelist + returnTo-Sanitize | Ja |
|
||||
| Brute-Force-Schutz auf Fallback-Login | Ja |
|
||||
| Audit-Event-Inhalt: keine Secrets | Ja (id_token NIEMALS persistieren) |
|
||||
|
||||
`AUTHENTIK_SECRET_KEY`-Loss-Implications (kann nicht rotiert werden ohne Daten-Verlust) ist in #81-Rollback + Security-Notes explizit — sehr wichtig und korrekt dokumentiert.
|
||||
|
||||
**Ergebnis:** Security-Coverage exzellent.
|
||||
|
||||
---
|
||||
|
||||
## 6. Staging-Deployment-Steps
|
||||
|
||||
### 6.1 Authentik-Coolify-Deploy
|
||||
|
||||
- Sehr detailliert: Service-Anlage, Compose-Path, Domain, Env-Vars aus Vault, Initial-Bootstrap, Smoke-Tests, Backup-Verifikation, Restore-Drill, Brute-Force-Smoke
|
||||
- `openssl rand`-Befehle für Secret-Generierung konkret
|
||||
- **Vollständig.**
|
||||
|
||||
### 6.2 Initial-Admin-Bootstrap
|
||||
|
||||
- `AUTHENTIK_BOOTSTRAP_PASSWORD` + zwingender Wechsel beim ersten Login
|
||||
- Recovery-Key generiert + in Coolify-Vault (NICHT in Git)
|
||||
- **Sauber.**
|
||||
|
||||
### 6.3 Restore-Drill
|
||||
|
||||
- Explizit: Dump in leere Postgres restoren, Authentik gegen Test-DB starten, Smoke-Login
|
||||
- `restore-drill.sh`-Script als Helper
|
||||
- **Konkret.**
|
||||
|
||||
### 6.4 Recovery-Drill für Fallback-Login
|
||||
|
||||
- In `admin-oidc-login.md` Step 12 (Staging) **vollständig durchspielt** inklusive Authentik-Stack-Stop, Env-Flag-Toggle, Bootstrap-Login, Authentik-Recovery, Flag-wieder-aus
|
||||
- Im Doku-File `docs/operations/admin-sso.md` als Fallback-Recovery-Procedure dokumentiert
|
||||
- **Pflicht-Drill korrekt.**
|
||||
|
||||
---
|
||||
|
||||
## 7. Konsistenz mit User-Wünschen
|
||||
|
||||
| User-Wunsch | Status |
|
||||
|---|---|
|
||||
| "SSO Authentik" — alles Authentik-basiert | Ja, kein Mix mit anderen IdPs |
|
||||
| "Self-host" — Docker-Compose vollständig | Ja (Compose + Override + Backup + Bootstrap + Blueprints) |
|
||||
| Customer-SSO-Backlog baut auf Authentik auf | Ja — `toolctrl-tenant-sso`-Provider als deaktivierter Platzhalter, Modul `admin-sso/` als Wiederverwendungs-Foundation explizit als Acceptance #82 |
|
||||
|
||||
**Erfüllt.**
|
||||
|
||||
---
|
||||
|
||||
## 8. Fehlende Aspekte / Lücken
|
||||
|
||||
### 8.1 Authentik-Update-Strategie
|
||||
|
||||
- Doku-Section "Update-Workflow" ist in #81 Step 11 als Mindest-Section gelistet (Stable-Tag bumpen, Pre-Update-Backup, Release-Notes-Pflicht)
|
||||
- **Lücke Minor #M5:** Es fehlt ein konkreter **Update-Cadence-Vorschlag** (z.B. "monatlich Stable-Bump prüfen, Security-Patches sofort"). Sollte im Operator-Runbook landen statt nur als Doku-Section-Eintrag.
|
||||
|
||||
### 8.2 Authentik-Sentry-Integration
|
||||
|
||||
- `AUTHENTIK_SENTRY__DSN=` in `.env.example` Step 3
|
||||
- `AUTHENTIK_ERROR_REPORTING__ENABLED=false` (kein SaaS-Reporting, gut)
|
||||
- **Lücke Minor #M6:** Es fehlt **welcher Sentry-Projekt-Name** für Authentik vorgesehen ist. Wenn alles im `boilerplate`-Projekt landet, gehen Authentik-Errors in den App-Error-Stream — vermutlich nicht gewünscht. Sollte als dediziertes Sentry-Projekt `authentik-infra` in #29 (sentry-selfhost-setup) verzahnt sein. → Doku-Cross-Link nötig.
|
||||
|
||||
### 8.3 Audit-Webhook von Authentik zu AuditEvent
|
||||
|
||||
- Vorbereitet als `80-notifications.yaml` Blueprint mit `enabled: false`, expliziter Verweis auf #67 (Audit-Log-Task)
|
||||
- HMAC-Signing erwähnt, Endpoint `https://api.<domain>/webhooks/authentik/audit`
|
||||
- **Gut vorbereitet, aktivierung explizit später** — korrekte Scope-Trennung.
|
||||
|
||||
### 8.4 Nicht abgedeckt
|
||||
|
||||
- **Authentik LDAP-Outpost / SCIM** — explizit out of scope (Step 5 nennt "keine Outposts hochfahren"), das ist okay für Phase 09. Im README sollte aber ein "Out-of-Scope"-Vermerk stehen, damit ein Agent das nicht "freiwillig" mitbaut.
|
||||
- **Mobile-App-OIDC-Flow** — Phase 08 Capacitor (Mobile) hat keine direkte Verzahnung. Falls Customer-Tenant-SSO später Mobile-Support braucht, müsste PKCE+Native-AppAuth-Pattern dazu kommen. Erwähnung in #66-Backlog ausreichend.
|
||||
|
||||
---
|
||||
|
||||
## 9. Findings-Liste (priorisiert)
|
||||
|
||||
### MAJOR (vor Execution adressieren)
|
||||
|
||||
**#J1 — CLAUDE.md-Routes-Konvention (Filenames + Route-Tree)**
|
||||
`admin-oidc-login.md` legt Routes mit Dot-Notation an: `auth.admin.login.tsx`, `auth.admin.callback.tsx`, `auth.admin.logout.tsx`. Im Projekt-CLAUDE.md (siehe React-Router-v7-Sektion) wird *explizit* die explizite `routes.ts`-Konfiguration über Dot-Notation-File-Convention bevorzugt. Beispiele im CLAUDE.md zeigen `routes/categories-layout.tsx` + `route(":slug", "routes/category-details.tsx")` als Pattern.
|
||||
|
||||
→ **Klären:** Soll die Phase die im Projekt etablierte File-Routing-Konvention (`.`-getrennt) nutzen oder via expliziter `routes.ts`-Einträge mit kebab-case-Filenames (`auth-admin-login.tsx`, `auth-admin-callback.tsx`, `auth-admin-logout.tsx`)? Empfehlung: **kebab-case + explizite routes.ts**, da klarer und CLAUDE.md-konform. Die Detail-MD sollte angepasst werden.
|
||||
|
||||
Auch betroffen: `admin/security.mfa-enroll.tsx`, `admin/security.mfa-challenge.tsx` — gleiche Frage.
|
||||
|
||||
**#J2 — `00-execution-order.md` Phase-01-Dependency fehlt**
|
||||
`00-execution-order.md` §Phase 09 nennt nur Phase 02 als Hard-Dependency. `admin-oidc-login.md` deklariert aber `totp-consolidation.md` (#26) aus Phase 01 als hart abhängig (App-MFA-Layer nutzt konsolidierte otpauth).
|
||||
|
||||
→ **Fix:** `00-execution-order.md` updaten: "**Depends on:** Phase 01 (#26 totp-consolidation für App-MFA-Layer), Phase 02 (Sentry für Authentik-Container)".
|
||||
|
||||
**#J3 — `package.json`-Touch in #82 Step 1 ist gefährlich (Workspace-Setup)**
|
||||
`admin-oidc-login.md` Step 1 nennt `package.json` als touched file für `pnpm add openid-client jose`. Im Monorepo (`apps/web/`-Sub-Package) sollte das `apps/web/package.json` sein, nicht das Root-Manifest. Sollte präzisiert werden, sonst landet die Dep im falschen Workspace.
|
||||
|
||||
→ **Fix:** "Files: `apps/web/package.json` (Dep: `openid-client`, `jose`)".
|
||||
|
||||
### MINOR (Klarheit / Konsistenz)
|
||||
|
||||
**#M1** — `00-execution-order.md` muss Phase 01 als Hard-Dependency für Phase 09 nennen (s. J2). *(Doppelt aufgeführt zur Sichtbarkeit.)*
|
||||
|
||||
**#M2** — Hetzner-Server-Mindest-Sizing für Co-Location (App + Sentry + Authentik) fehlt. README oder #81 Approach sollte `CX31`/`CPX31` als Minimum-Empfehlung nennen.
|
||||
|
||||
**#M3** — Wildcard-Cert-Hinweis (`auth.*`-Subdomain, DNS-Challenge) nur in Lessons-Learned. Sollte als expliziter Sub-Step in #81 Step 4 (Traefik) auftauchen.
|
||||
|
||||
**#M4** — Session-Fixation-Schutz (App-Session-ID-Rotation nach OIDC-Callback) ist in Security-Notes erwähnt, aber NICHT als konkreter Sub-Step in #82 Step 6 (Callback-Route). Implementer wird es ggf. übersehen.
|
||||
|
||||
**#M5** — Authentik-Update-Cadence (monatlich / Security-Patches sofort) als Operator-Runbook-Eintrag fehlt.
|
||||
|
||||
**#M6** — Sentry-Projekt-Name für Authentik (`authentik-infra` vs. App-Projekt) ist nicht spezifiziert. Cross-Link mit #29 (sentry-selfhost-setup) nötig.
|
||||
|
||||
### NICE-TO-HAVE
|
||||
|
||||
**#N1** — Slack/Discord-Alert für Fallback-Login als konkreter Operator-Hook (statt "optional later").
|
||||
|
||||
**#N2** — `msw`-Authentik-Mock-Fixture als wiederverwendbares File (`apps/web/tests/fixtures/authentik-mock.ts`) für #82-Tests und spätere #66-Wiederverwendung.
|
||||
|
||||
**#N3** — Out-of-Scope-Section im README ("keine Outposts, kein LDAP-Sync, kein SAML, keine SCIM-Provisioning") damit Implementing-Agent nicht "freiwillig" Scope erweitert.
|
||||
|
||||
**#N4** — `docs/operations/admin-sso.md` Mermaid-Flow-Diagramme sind als Anforderung in Step 14 + Subagent-Brief erwähnt; ein Hinweis welcher Mermaid-Renderer / welches Theme genutzt werden soll wäre hilfreich (sonst kommen 3 verschiedene Stile in den Docs zusammen).
|
||||
|
||||
---
|
||||
|
||||
## 10. Phase-Done-Definition (README) vs. Detail-MDs — Konsistenz
|
||||
|
||||
15 Items in README Phase-Done-Definition geprüft gegen Acceptance-Criteria in #81+#82:
|
||||
|
||||
| README-Item | In Detail-MD verankert |
|
||||
|---|---|
|
||||
| 2 Tasks completed | Trivial |
|
||||
| Authentik auf Staging erreichbar | #81 Acceptance |
|
||||
| 2 OIDC-Provider in Authentik | #81 Acceptance |
|
||||
| Groups + MFA-Pflicht | #81 Acceptance |
|
||||
| Admin-Login durchläuft | #82 Acceptance |
|
||||
| JIT-Provisioning erstellt AdminUser | #82 Acceptance |
|
||||
| Logout RP-Initiated | #82 Acceptance |
|
||||
| Email/Passwort-Fallback Env-Gated | #82 Acceptance |
|
||||
| App-MFA-Layer verdrahtet | #82 Acceptance |
|
||||
| 4 AuditEvent-Typen geschrieben | #82 Step 12 + Acceptance |
|
||||
| Lint/typecheck/test grün | Standard |
|
||||
| `docs/operations/authentik-setup.md` | #81 Step 11 + Acceptance |
|
||||
| `docs/operations/admin-sso.md` | #82 Step 14 + Acceptance |
|
||||
| `.env.example` mit allen 7 Keys | #82 Step 13 + Acceptance |
|
||||
| Code-Review durch gsd-code-reviewer | Standard |
|
||||
| Backup-Restore-Drill | #81 Test-Requirements |
|
||||
| Phase-Summary in README | Standard |
|
||||
|
||||
**Alle Items in den Detail-MDs verankert.** Keine Inkonsistenz.
|
||||
|
||||
---
|
||||
|
||||
## 11. Abschlussbewertung
|
||||
|
||||
- **Template-Konformität:** 10/10
|
||||
- **Dependency-Konsistenz:** 8/10 (J2/M1 noch zu fixen)
|
||||
- **Implementation-Detail-Qualität:** 10/10 (sehr ausführlich)
|
||||
- **Test-Coverage-Pläne:** 9/10 (kleinere NTHs)
|
||||
- **Security-Notes:** 10/10 (exzellent)
|
||||
- **Staging-Steps:** 10/10
|
||||
- **User-Wunsch-Konsistenz:** 10/10
|
||||
- **Vollständigkeit (Fehlende Aspekte):** 8/10 (M5/M6)
|
||||
|
||||
**Gesamtbewertung:** Phase 09 ist **planungstechnisch ready-to-execute** nach Adressierung von **J1, J2, J3** und idealerweise der Minor-Fixes (M2-M6). Alle Nice-to-haves können während Execution adressiert werden.
|
||||
|
||||
**Blocker für Execution:** Keine — alle Findings sind klärbar/fix-bar ohne Konzept-Änderung. J1 (Routes-Konvention) ist mehr eine Stil-/Klärungs-Frage; falls die Projekt-Konvention die Dot-Notation tatsächlich verwendet (was in der laufenden Codebase verifiziert werden sollte), kann der Plan unverändert bleiben.
|
||||
|
||||
**Empfehlung:** Vor Phase-09-Start einmal kurz die Detail-MDs in einem Follow-up-Commit mit den Major-Fixes patchen, dann freigeben.
|
||||
@@ -0,0 +1,479 @@
|
||||
# Admin-Panel OIDC-Login (Authentik-SSO)
|
||||
|
||||
**Status:** completed (env-naming-bug fixed 2026-05-19; full E2E login still requires user creds)
|
||||
**Task-ID:** #82
|
||||
**Phase:** 09
|
||||
**Estimated Effort:** ~1 Woche (5-7 Tage)
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Aktuell loggt sich das Admin-Panel der Boilerplate (`apps/web/app/routes/admin/*`) ausschließlich via App-internem Email/Passwort-Flow ein. Es gibt keinen externen IdP-Kontakt, keine Group-basierte Access-Control, keine zentrale Session-Revocation und kein Federations-Pfad. Sobald wir Customer-Tenant-SSO (Backlog #66) anbieten wollen, brauchen wir den OIDC-Client-Pfad ohnehin — wir bauen ihn hier zuerst für das Admin-Panel auf.
|
||||
|
||||
Konkret fehlt:
|
||||
|
||||
- **OIDC-Client-Implementation** für den Authentik-Provider `toolctrl-admin-panel`
|
||||
- **JIT-Provisioning-Logik** — wenn ein neuer Authentik-User mit passender Group sich zum ersten Mal einloggt, soll automatisch ein `AdminUser`-Record entstehen
|
||||
- **Rolle-Mapping** Authentik-Group → `AdminUser.role` (`toolctrl-admin` → `super_admin`, `toolctrl-staff` → `staff`)
|
||||
- **RP-Initiated-Logout** — lokales Session-Killing + Authentik-End-Session-Redirect
|
||||
- **Fallback-Login** für den Notfall (IdP-Down) — gekapselt hinter Env-Flag, mit Allowlist
|
||||
- **App-interne MFA als zweite Schicht** für sensible Actions (Impersonation, Tenant-Löschung), zusätzlich zur Authentik-MFA-Pflicht
|
||||
- **Audit-Trail** jeder Admin-Login/-Logout-Event in `AuditEvent`
|
||||
|
||||
Betroffene Codestellen (neu + modifiziert):
|
||||
|
||||
- `apps/web/app/modules/admin-sso/` (neu) — komplettes Modul: `client.server.ts`, `state.server.ts`, `jit-provisioning.server.ts`, `claims.server.ts`, `logout.server.ts`
|
||||
- `apps/web/app/routes/auth.admin.login.tsx` (neu)
|
||||
- `apps/web/app/routes/auth.admin.callback.tsx` (neu)
|
||||
- `apps/web/app/routes/auth.admin.logout.tsx` (neu)
|
||||
- `apps/web/app/routes/admin.login.tsx` (modifiziert — neuer „Login mit SSO"-Primary-Button, Fallback-Toggle)
|
||||
- `apps/web/app/routes.ts` (modifiziert — neue Routes registrieren)
|
||||
- `prisma/schema.prisma` (modifiziert — `AdminUser`-Erweiterung: `ssoSubjectId`, `ssoProvider`, `ssoGroups`, `lastSsoLoginAt`)
|
||||
- `prisma/migrations/<ts>_admin_user_sso_fields/` (neu)
|
||||
- `apps/web/app/services/auth/admin-session.server.ts` (modifiziert oder neu — Session-Helper für SSO + Fallback)
|
||||
- `apps/web/app/services/auth/admin-mfa-gate.server.ts` (neu — App-MFA-Gate für sensible Actions)
|
||||
- `docs/operations/admin-sso.md` (neu)
|
||||
|
||||
## Depends on
|
||||
|
||||
- `09-authentik-admin-sso/authentik-setup.md` (#81) — Authentik muss laufen, OIDC-Provider `toolctrl-admin-panel` muss existieren, Groups + Mapping müssen konfiguriert sein
|
||||
- `01-tech-debt-foundation/totp-consolidation.md` (#26) — die App-MFA-Schicht (zweiter Layer für sensible Actions) MUSS gegen die konsolidierte otpauth-Variante gehen, nicht gegen die selbst-gebaute Crypto
|
||||
|
||||
## Blocks
|
||||
|
||||
- `11-backlog/customer-tenant-sso.md` (#66) — Tenant-SSO wiederverwendet ~80% des OIDC-Client-Codes aus diesem Modul (in `apps/web/app/modules/admin-sso/` werden die wiederverwendbaren Bausteine sauber abstrahiert)
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Eigenständiges Modul `apps/web/app/modules/admin-sso/` mit der Library **`openid-client`** (https://github.com/panva/node-openid-client) — die Referenz-Implementation für OIDC-RP in Node, RFC-konform, aktiv gepflegt, deckt PKCE, State, Nonce, JWT-Verifikation, JWKS-Caching ab. Alternativen verworfen:
|
||||
|
||||
- **`oidc-client-ts`** — primär Browser-Library (TS, SPA-orientiert), passt nicht zum React-Router-v7-SSR-Pattern
|
||||
- **Eigene Implementation** — Crypto/JWT-Verifikation selbst bauen ist Anti-Pattern, OIDC-Spec ist fehleranfällig
|
||||
- **`next-auth`/`auth.js`** — overkill und zu viel Magic; wir wollen expliziten Server-Code in unseren Routen, kein Plug-and-Play-Framework
|
||||
|
||||
**Routes-Layout** (React-Router-v7-Framework-Mode, siehe `CLAUDE.md`):
|
||||
|
||||
- `GET /auth/admin/login` — generiert PKCE-`code_verifier` + `code_challenge`, generiert `state` (CSRF) + `nonce` (Replay-Schutz), persistiert beide in signed/encrypted Cookie (HttpOnly, Secure, SameSite=Lax, kurze TTL), redirected zu Authentik-`authorization_endpoint`
|
||||
- `GET /auth/admin/callback?code=…&state=…` — verifiziert State-Cookie, tauscht Code gegen Tokens via `token_endpoint` (mit PKCE-Verifier + Client-Secret), verifiziert ID-Token-Signatur via Authentik-JWKS, validiert `iss`/`aud`/`exp`/`nonce`, extrahiert `sub` + `groups` + `email` + `name` Claims, ruft JIT-Provisioning auf, setzt App-Session-Cookie, redirected zu `/admin`
|
||||
- `POST /auth/admin/logout` — killt lokale Session, redirected zu Authentik-`end_session_endpoint` mit `id_token_hint` + `post_logout_redirect_uri`
|
||||
|
||||
**JIT-Provisioning-Regel** (in `jit-provisioning.server.ts`):
|
||||
|
||||
- Lookup `AdminUser` via `ssoSubjectId` (Authentik-`sub`-Claim) + `ssoProvider='authentik'`
|
||||
- Wenn nicht gefunden:
|
||||
- Fallback-Lookup via `email` (case-insensitive) für Migration bestehender Admin-Accounts → wenn gefunden, attache SSO-Fields
|
||||
- Wenn auch nicht gefunden: prüfe ob Group-Claim mindestens eine der erlaubten Groups (`toolctrl-admin`, `toolctrl-staff`) enthält → ja: erstelle neuen `AdminUser` mit Rolle aus Group-Mapping; nein: 403 (Login abgelehnt)
|
||||
- Wenn gefunden: update `ssoGroups`, `lastSsoLoginAt`, `email` (falls geändert), `name`. Update `role` gemäß aktueller Group-Mitgliedschaft (Authentik = Source-of-Truth, App-Rolle wird bei jedem Login synchronisiert)
|
||||
|
||||
**Permission-Mapping** (in `claims.server.ts`):
|
||||
|
||||
- `toolctrl-admin` (höchste Priorität, falls beide Groups) → `AdminUser.role = 'super_admin'`
|
||||
- `toolctrl-staff` → `AdminUser.role = 'staff'`
|
||||
- weder noch → Login-Reject 403
|
||||
- Granulare Permission-Checks bleiben in der App (`apps/web/app/utils/permissions/`), die Rolle ist nur der grobe Switch
|
||||
|
||||
**Fallback-Login-Strategie:**
|
||||
|
||||
- Email/Passwort-Login bleibt im Code, ist aber **per Default deaktiviert** via `ADMIN_FALLBACK_LOGIN_ENABLED=false`
|
||||
- Wenn aktiviert: nur Accounts in `ADMIN_FALLBACK_LOGIN_EMAILS` (komma-separierte Allowlist) dürfen den Fallback nutzen
|
||||
- Login-Page (`/admin/login`) zeigt prominent „Login mit SSO" als Primary-CTA; Fallback nur als kleiner Toggle „Notfall-Login mit Passwort" am unteren Rand, der nur sichtbar ist wenn Env-Flag `true`
|
||||
- Initial-Bootstrap-Admin (vor Authentik-Setup angelegt) bleibt damit erreichbar während Authentik down ist oder noch nicht konfiguriert
|
||||
- Jeder Fallback-Login wird mit Severity `warn` in `AuditEvent` UND als Sentry-Breadcrumb geloggt (Operator-Sichtbarkeit)
|
||||
- Optional: Slack/Discord-Notification bei Fallback-Login (Hook später erweiterbar)
|
||||
|
||||
**App-MFA als zweite Schicht** (in `admin-mfa-gate.server.ts`):
|
||||
|
||||
- Für sensible Actions (Liste in Code als Konstante `SENSITIVE_ADMIN_ACTIONS`): Impersonation-Start, Tenant-Löschung, Permission-Grant, Audit-Log-Export, Manueller Daten-Export
|
||||
- Vor Ausführung wird ein TOTP-Challenge erzwungen — auch wenn Authentik-MFA gerade vorhanden ist (Defense-in-Depth)
|
||||
- Nutzt **konsolidierte otpauth-Variante aus #26** (`apps/web/app/services/auth/totp.server.ts`)
|
||||
- TOTP-Secret wird beim ersten sensiblen Action enrollment-mäßig angelegt (separate Page `/admin/security/mfa-enroll`), unabhängig von Authentik-MFA
|
||||
- Cache: nach erfolgreichem App-MFA-Challenge für 15 Min freigeschaltet (server-side, Session-bound), danach erneut nötig
|
||||
|
||||
**Alternativen verworfen:**
|
||||
|
||||
- **Authentik-MFA als einzige Schicht** — funktioniert für Standard-Login, aber Authentik-Session-Cookie gilt nicht App-seitig; wir müssten Authentik-API für „re-authenticate"-Calls bemühen, was Komplexität + Latenz hinzufügt. Eigene App-MFA-Gate ist sauberer.
|
||||
- **Kein Fallback-Login** — zu riskant; wenn Authentik-Instanz down ist (Disaster, Update-Bug), wären Admins ausgesperrt und könnten die Authentik-Instanz nicht mehr operativ recovern.
|
||||
- **Fallback-Login immer aktiv** — schwächt die SSO-Schutzschicht; Env-Flag erzwingt bewusste Entscheidung.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Library-Install + Modul-Skelett**
|
||||
- Files: `apps/web/app/modules/admin-sso/index.ts`, `apps/web/app/modules/admin-sso/README.md`, `package.json` (Dep: `openid-client`)
|
||||
- Aktion: `pnpm add openid-client jose` (jose für JWT-Helper falls openid-client das nicht bereits exposed)
|
||||
- Commit: `09-authentik/admin-oidc: scaffold admin-sso module and install openid-client`
|
||||
|
||||
2. **DB-Schema: AdminUser erweitern**
|
||||
- Files: `prisma/schema.prisma`, `prisma/migrations/<ts>_admin_user_sso_fields/migration.sql`
|
||||
- Aktion: `AdminUser` um Felder erweitern:
|
||||
- `ssoSubjectId String?` (Authentik-`sub`-Claim, unique innerhalb `(ssoProvider, ssoSubjectId)`)
|
||||
- `ssoProvider String?` (z.B. `"authentik"`)
|
||||
- `ssoGroups String[]` (Snapshot der Groups aus letztem Login, für Debug + Audit)
|
||||
- `lastSsoLoginAt DateTime?`
|
||||
- Index `@@unique([ssoProvider, ssoSubjectId])`
|
||||
- Migration generieren mit `pnpm prisma migrate dev --name admin_user_sso_fields`
|
||||
- Commit: `09-authentik/admin-oidc: extend AdminUser with SSO fields and migration`
|
||||
|
||||
3. **OIDC-Client-Initialization**
|
||||
- Files: `apps/web/app/modules/admin-sso/client.server.ts`
|
||||
- Aktion: Singleton-Lazy-Init eines `openid-client`-`Client`:
|
||||
- Discovery via `Issuer.discover(env.AUTHENTIK_ISSUER_URL)`
|
||||
- Client-Constructor mit `client_id`, `client_secret`, `redirect_uris: [env.AUTHENTIK_ADMIN_REDIRECT_URI]`, `response_types: ['code']`, `token_endpoint_auth_method: 'client_secret_post'`
|
||||
- JWKS wird auto-cached von der Library
|
||||
- Error-Handling: bei Discovery-Failure → Sentry-Capture + Throw mit klarer Message (führt zu Fallback-Banner auf Login-Page)
|
||||
- Commit: `09-authentik/admin-oidc: implement openid-client initialization`
|
||||
|
||||
4. **State + PKCE + Nonce Persistence**
|
||||
- Files: `apps/web/app/modules/admin-sso/state.server.ts`
|
||||
- Aktion:
|
||||
- `createLoginChallenge()` generiert: `state` (32-byte hex), `nonce` (32-byte hex), `code_verifier` (via `generators.codeVerifier()` aus openid-client), `code_challenge` (via `generators.codeChallenge(verifier)`)
|
||||
- Persistiert das Tupel in einem signed Cookie `admin_sso_challenge` (HttpOnly, Secure, SameSite=Lax, Path=`/auth/admin`, Max-Age=600s)
|
||||
- Cookie-Signature via existierende Session-Secret-Infrastruktur (`getSessionSecret()` o.ä. aus bestehender Session-Library)
|
||||
- `consumeLoginChallenge(request)` liest + validiert + invalidiert den Cookie (single-use)
|
||||
- Commit: `09-authentik/admin-oidc: add state/PKCE/nonce challenge cookie helpers`
|
||||
|
||||
5. **Login-Route**
|
||||
- Files: `apps/web/app/routes/auth.admin.login.tsx`, `apps/web/app/routes.ts` (Route registrieren)
|
||||
- Aktion: `loader` ruft `client.authorizationUrl({state, code_challenge, code_challenge_method:'S256', nonce, scope:'openid profile email groups'})`, setzt Challenge-Cookie, returned `redirect(authorizationUrl)`
|
||||
- Kein Component (reine Redirect-Route)
|
||||
- Type-Generation: `pnpm run typecheck` nach Route-Registration
|
||||
- Commit: `09-authentik/admin-oidc: add /auth/admin/login route`
|
||||
|
||||
6. **Callback-Route**
|
||||
- Files: `apps/web/app/routes/auth.admin.callback.tsx`, `apps/web/app/routes.ts`
|
||||
- Aktion: `loader`:
|
||||
- `consumeLoginChallenge(request)` → state/nonce/verifier aus Cookie
|
||||
- `client.callback(redirect_uri, params, {state, nonce, code_verifier})` → tauscht Code gegen Token-Set
|
||||
- Verifikation: ID-Token-Signatur (auto via openid-client), `iss`/`aud`/`exp`/`nonce` (auto), zusätzlich `email_verified=true` prüfen (falls Claim vorhanden)
|
||||
- Claims extrahieren: `sub`, `email`, `name`, `groups`
|
||||
- `jitProvision(claims)` aufrufen (Step 7) → liefert `AdminUser`
|
||||
- App-Session-Cookie setzen via existierende Admin-Session-Library, `id_token` (raw) zusätzlich in Session speichern (für RP-Initiated-Logout)
|
||||
- `AuditEvent` schreiben: `admin.login.sso.success`, `actorAdminUserId`, `meta: {ssoSubjectId, groups, ip, userAgent}`
|
||||
- Bei jedem Error: `AuditEvent` `admin.login.sso.failure` mit Error-Klasse + Sentry-Capture; User-redirect zu `/admin/login?error=sso_failed`
|
||||
- Success-Redirect zu `/admin` (oder zur `returnTo`-Query-Param falls vorhanden + safe)
|
||||
- Commit: `09-authentik/admin-oidc: add /auth/admin/callback route with token exchange and verification`
|
||||
|
||||
7. **JIT-Provisioning + Group-Mapping**
|
||||
- Files: `apps/web/app/modules/admin-sso/jit-provisioning.server.ts`, `apps/web/app/modules/admin-sso/claims.server.ts`
|
||||
- Aktion:
|
||||
- `mapGroupsToRole(groups: string[]): 'super_admin' | 'staff' | null` — `toolctrl-admin` > `toolctrl-staff` > `null`
|
||||
- `jitProvision({sub, email, name, groups, provider:'authentik'})`:
|
||||
- Lookup via `(ssoProvider, ssoSubjectId)`
|
||||
- Wenn nicht gefunden: Lookup via `email` (case-insensitive) für Existing-Account-Linking
|
||||
- Wenn weder noch: nur erstellen wenn `mapGroupsToRole(groups) !== null`, sonst 403
|
||||
- Beim Create: `role = mapGroupsToRole(groups)`, `ssoSubjectId`, `ssoProvider`, `ssoGroups`, `lastSsoLoginAt`
|
||||
- Beim Update: `role` re-syncen (Authentik = Source-of-Truth), `ssoGroups`, `lastSsoLoginAt`, `email`/`name` aktualisieren
|
||||
- Transaction-safe (Prisma `$transaction`), idempotent (concurrent Logins desselben Users dürfen keine Duplicate-Errors werfen — Unique-Constraint fängt)
|
||||
- Commit: `09-authentik/admin-oidc: implement JIT provisioning and group-to-role mapping`
|
||||
|
||||
8. **Logout-Route (RP-Initiated)**
|
||||
- Files: `apps/web/app/routes/auth.admin.logout.tsx`, `apps/web/app/modules/admin-sso/logout.server.ts`, `apps/web/app/routes.ts`
|
||||
- Aktion: `action` (POST):
|
||||
- Lese `id_token` aus App-Session
|
||||
- Lokale Session killen (App-Cookie destroyen, Session-Store-Eintrag löschen)
|
||||
- `AuditEvent` `admin.logout.sso`
|
||||
- Redirect zu `client.endSessionUrl({id_token_hint, post_logout_redirect_uri: env.AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI})`
|
||||
- Authentik killt seine Session und redirected zurück zur `post_logout_redirect_uri` (z.B. `/admin/login?logged_out=1`)
|
||||
- Wenn `id_token` fehlt (nur Fallback-Login war aktiv): nur lokale Session killen, kein Authentik-Redirect, direkt zu `/admin/login`
|
||||
- Commit: `09-authentik/admin-oidc: add /auth/admin/logout with RP-initiated end session`
|
||||
|
||||
9. **Admin-Login-Page UI**
|
||||
- Files: `apps/web/app/routes/admin.login.tsx` (modifiziert)
|
||||
- Aktion:
|
||||
- Primary-CTA: großer Button „Login mit SSO" → linked auf `/auth/admin/login`
|
||||
- Wenn `ADMIN_FALLBACK_LOGIN_ENABLED=true` (loader exposed das als boolean): kleiner Disclosure-Toggle „Notfall-Login mit Passwort", der das bestehende Email/Passwort-Form aufklappt
|
||||
- Wenn `error=sso_failed` Query-Param: rote Error-Banner mit Hinweis auf Operator-Kontakt
|
||||
- Wenn `logged_out=1` Query-Param: grüne Success-Banner
|
||||
- Existierendes Email/Passwort-Form bleibt funktional, aber Fallback-Submit-Handler MUSS prüfen:
|
||||
- `ADMIN_FALLBACK_LOGIN_ENABLED=true`
|
||||
- Email in `ADMIN_FALLBACK_LOGIN_EMAILS`-Allowlist
|
||||
- Bei Erfolg: `AuditEvent` `admin.login.fallback.success` mit Severity `warn` + Sentry-Breadcrumb
|
||||
- Bei Fail: `admin.login.fallback.failure`
|
||||
- Type-Generation: `pnpm run typecheck`
|
||||
- Commit: `09-authentik/admin-oidc: update admin login page with SSO CTA and gated fallback`
|
||||
|
||||
10. **Fallback-Login-Guards (Server-Side)**
|
||||
- Files: `apps/web/app/services/auth/admin-session.server.ts` (modifiziert oder neu)
|
||||
- Aktion:
|
||||
- `assertFallbackLoginAllowed(email: string)` — wirft 403 wenn `ADMIN_FALLBACK_LOGIN_ENABLED !== 'true'` oder Email nicht in Allowlist
|
||||
- Bestehender Email/Passwort-Login-Action ruft diesen Guard VOR Passwort-Check
|
||||
- Commit: `09-authentik/admin-oidc: enforce env-gated fallback login allowlist`
|
||||
|
||||
11. **App-MFA-Gate für sensible Actions**
|
||||
- Files: `apps/web/app/services/auth/admin-mfa-gate.server.ts` (neu), `apps/web/app/routes/admin/security.mfa-enroll.tsx` (neu), `apps/web/app/routes/admin/security.mfa-challenge.tsx` (neu), `apps/web/app/routes.ts`
|
||||
- Aktion:
|
||||
- Konstante `SENSITIVE_ADMIN_ACTIONS = ['impersonation.start', 'tenant.delete', 'permission.grant', 'audit.export', 'data.export']`
|
||||
- Helper `requireAppMfa(request, actionKey)`:
|
||||
- Wenn `actionKey` in `SENSITIVE_ADMIN_ACTIONS` UND letzter erfolgreicher App-MFA-Challenge der Session älter als 15 Min ist: redirect zu `/admin/security/mfa-challenge?returnTo=<encoded>`
|
||||
- Nutzt `verifyTotpToken` aus `apps/web/app/services/auth/totp.server.ts` (konsolidierte otpauth aus #26)
|
||||
- Enrollment-Page generiert TOTP-Secret + QR (otpauth-URL), Verify-Step bestätigt erstes Token bevor persistiert wird
|
||||
- Challenge-Page nimmt Token entgegen, verifiziert, setzt Session-Field `lastAppMfaAt = now()`, redirected zu `returnTo`
|
||||
- Sensible Actions (in ihren jeweiligen Action-Handlern) rufen `await requireAppMfa(request, 'impersonation.start')` als ersten Step
|
||||
- Commit: `09-authentik/admin-oidc: add app-level MFA gate for sensitive admin actions`
|
||||
|
||||
12. **Audit-Events verdrahten**
|
||||
- Files: `apps/web/app/modules/admin-sso/audit.server.ts` (neu, dünner Wrapper) — schreibt in existierendes `AuditEvent`-Modell
|
||||
- Events:
|
||||
- `admin.login.sso.success`
|
||||
- `admin.login.sso.failure` (mit Error-Klasse)
|
||||
- `admin.login.fallback.success` (severity `warn`)
|
||||
- `admin.login.fallback.failure`
|
||||
- `admin.logout.sso`
|
||||
- `admin.mfa.app.challenge.success`
|
||||
- `admin.mfa.app.challenge.failure`
|
||||
- Alle Events mit `ip`, `userAgent`, `actorAdminUserId` (wenn auflösbar), `meta` (event-spezifisch)
|
||||
- Commit: `09-authentik/admin-oidc: wire audit events for all admin login/logout paths`
|
||||
|
||||
13. **Env-Vars + .env.example**
|
||||
- Files: `apps/web/.env.example` (oder zentrales `.env.example`), `apps/web/app/utils/env.server.ts` (Schema-Erweiterung mit `zod`)
|
||||
- Keys:
|
||||
- `AUTHENTIK_ISSUER_URL=https://auth.example.com/application/o/toolctrl-admin-panel/`
|
||||
- `AUTHENTIK_ADMIN_CLIENT_ID=toolctrl-admin-panel`
|
||||
- `AUTHENTIK_ADMIN_CLIENT_SECRET=` (Coolify-Vault, niemals committen)
|
||||
- `AUTHENTIK_ADMIN_REDIRECT_URI=https://admin.example.com/auth/admin/callback`
|
||||
- `AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI=https://admin.example.com/admin/login?logged_out=1`
|
||||
- `AUTHENTIK_END_SESSION_URL=https://auth.example.com/application/o/toolctrl-admin-panel/end-session/` (optional, openid-client kann das auch aus Discovery)
|
||||
- `ADMIN_FALLBACK_LOGIN_ENABLED=false`
|
||||
- `ADMIN_FALLBACK_LOGIN_EMAILS=` (komma-separierte Allowlist, leer per Default)
|
||||
- Zod-Schema: alle URLs als `z.string().url()`, Boolean als `z.enum(['true','false']).transform(v => v === 'true')`
|
||||
- Commit: `09-authentik/admin-oidc: add SSO env vars and zod schema`
|
||||
|
||||
14. **Doku**
|
||||
- Files: `docs/operations/admin-sso.md`
|
||||
- Inhalt (Mindest-Sections):
|
||||
- **Überblick** — Flow-Diagramm (Mermaid) Login + Logout + Fallback
|
||||
- **Authentik-Group-Setup-Anleitung** — wie neue Admin-User onboarden (User in Authentik anlegen, in `toolctrl-admin` oder `toolctrl-staff`-Group packen, MFA-Enrollment erzwingen), erster Login triggert JIT
|
||||
- **Group-Removal** — wie Admin offboarden (Authentik-User deaktivieren oder aus Group entfernen → nächster Login wirft 403; App-Session bleibt aktiv bis Cookie-TTL — daher zusätzlich: manuell App-Session via Operator-CLI revoken; siehe Sub-Section "Force-Logout")
|
||||
- **Fallback-Recovery-Procedure** — wenn Authentik down ist:
|
||||
1. Operator setzt `ADMIN_FALLBACK_LOGIN_ENABLED=true` + `ADMIN_FALLBACK_LOGIN_EMAILS=bootstrap@example.com` in Coolify-Env, Redeploy
|
||||
2. Login mit Bootstrap-Admin via Email/Passwort
|
||||
3. Authentik wiederherstellen (siehe `docs/operations/authentik-setup.md` Disaster-Recovery)
|
||||
4. Fallback wieder ausschalten + Sentry-Alert auflösen
|
||||
- **Permission-Mapping** — Tabelle Group → Rolle → Permissions
|
||||
- **App-MFA-Gate** — Liste sensible Actions, Enrollment-Flow, 15-Min-Cache-Verhalten
|
||||
- **Audit-Events** — Tabelle aller Event-Types, wo sie geloggt werden
|
||||
- **Troubleshooting** — typische Fehler: `iss`-Mismatch (Issuer-URL falsch in Env), `aud`-Mismatch (Client-ID falsch), JWKS-Cache-Stale (Authentik-Key rotiert), Group-Claim leer (Scope `groups` nicht in Authentik-Provider konfiguriert)
|
||||
- Commit: `09-authentik/admin-oidc: document SSO operations and fallback recovery`
|
||||
|
||||
15. **Optionale Cleanup-Migration** — falls bestehende Admin-Accounts existieren ohne `ssoSubjectId`: Skript zum Mark-as-Legacy
|
||||
- Files: `prisma/migrations/<ts>_admin_user_sso_fields/data.ts` (Backfill-Script falls nötig)
|
||||
- Aktion: alle existierenden `AdminUser` bekommen `ssoProvider = null`, `ssoSubjectId = null` (Default eh `null`, daher meistens kein Backfill nötig). Skript dokumentiert dass diese Accounts beim ersten SSO-Login per Email gematched + verlinkt werden.
|
||||
- Commit: `09-authentik/admin-oidc: document legacy admin account linking strategy` (kann auch nur Doku sein, kein Backfill)
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests** (Vitest, neben Source-Files):
|
||||
- `apps/web/app/modules/admin-sso/claims.server.test.ts`:
|
||||
- `mapGroupsToRole(['toolctrl-admin'])` → `'super_admin'`
|
||||
- `mapGroupsToRole(['toolctrl-staff'])` → `'staff'`
|
||||
- `mapGroupsToRole(['toolctrl-admin', 'toolctrl-staff'])` → `'super_admin'` (höchste Prio)
|
||||
- `mapGroupsToRole(['random-group'])` → `null`
|
||||
- `mapGroupsToRole([])` → `null`
|
||||
- `apps/web/app/modules/admin-sso/state.server.test.ts`:
|
||||
- `createLoginChallenge()` generiert distincte state/nonce/verifier
|
||||
- `consumeLoginChallenge` returned korrekte Werte und invalidiert Cookie
|
||||
- Tampered Cookie wird abgelehnt (Signature-Check)
|
||||
- Expired Cookie (Max-Age überschritten) wird abgelehnt
|
||||
- `apps/web/app/modules/admin-sso/jit-provisioning.server.test.ts` (mit Test-DB):
|
||||
- Neuer User mit `toolctrl-admin` → AdminUser angelegt mit `role='super_admin'`
|
||||
- Neuer User mit unbekannter Group → Throw 403
|
||||
- Bestehender User mit gleicher `ssoSubjectId` → Update (kein Duplicate)
|
||||
- Bestehender User per `email`-Match → Linking (ssoSubjectId attached)
|
||||
- User wechselt Group von admin → staff → `role` wird beim nächsten Login re-synced
|
||||
- Concurrent JIT-Calls für gleichen User → keine Duplicate-Errors (Unique-Constraint greift)
|
||||
- `apps/web/app/services/auth/admin-mfa-gate.server.test.ts`:
|
||||
- Sensible Action ohne MFA-Challenge → redirect
|
||||
- Sensible Action mit MFA-Challenge < 15 Min → pass
|
||||
- Sensible Action mit MFA-Challenge > 15 Min → redirect
|
||||
- Nicht-sensible Action → pass ohne MFA
|
||||
- `apps/web/app/services/auth/admin-session.server.test.ts` (für Fallback-Guards):
|
||||
- `assertFallbackLoginAllowed` wirft wenn Env-Flag `false`
|
||||
- wirft wenn Email nicht in Allowlist
|
||||
- passt durch wenn beide Bedingungen erfüllt
|
||||
- **Integration-Tests** (Vitest mit Mock-Authentik via `msw` oder Lokal-Container):
|
||||
- Login-Flow End-to-End (Mock-Authentik): GET `/auth/admin/login` → Redirect zu Mock-Authorize, Mock liefert Code → Callback → Token-Exchange → JIT → Session-Cookie gesetzt → Redirect zu `/admin`
|
||||
- State-Mismatch: tampered State im Callback → 400
|
||||
- Nonce-Mismatch: Token mit falscher Nonce → 400
|
||||
- Expired ID-Token → 401
|
||||
- Group-Claim leer → 403
|
||||
- **E2E-Tests (Playwright)** mit Staging-Authentik:
|
||||
- **Happy-Path SSO-Login**: User klickt „Login mit SSO" → Authentik-Login-Page → Test-Credentials → MFA-Challenge → Erfolg → Admin-Dashboard sichtbar
|
||||
- **JIT-Provisioning**: Neuer Authentik-User (nur in Authentik existent) loggt sich erstmals ein → AdminUser-Record danach in DB sichtbar (assert via API-Helper)
|
||||
- **Logout-Flow**: Admin → Logout-Button → Authentik-End-Session → redirect zu `/admin/login?logged_out=1`
|
||||
- **Fallback-Login (Env-Flag aktiviert)**: Login-Page zeigt Fallback-Toggle → Email/Passwort-Login mit Allowlist-Email → Erfolg → AuditEvent `admin.login.fallback.success` mit `warn`-Severity in DB
|
||||
- **Fallback-Login abgelehnt**: Non-Allowlist-Email versucht Fallback → 403, Audit `admin.login.fallback.failure`
|
||||
- **Fallback-Login deaktiviert**: Env-Flag `false` → Fallback-Toggle nicht sichtbar; direct-POST auf Fallback-Endpoint → 403
|
||||
- **App-MFA-Gate**: Admin (frisch eingeloggt) versucht Impersonation → wird zu `/admin/security/mfa-challenge` redirected; nach gültigem TOTP-Code → Impersonation startet; Wiederholung innerhalb 15 Min → keine erneute Challenge; nach 16 Min → erneute Challenge
|
||||
- **Coverage-Target:** ≥85% Lines/Branches im Modul `apps/web/app/modules/admin-sso/`; 100% auf `claims.server.ts` und `state.server.ts` (security-kritisch)
|
||||
- **Test-Files:**
|
||||
- `apps/web/app/modules/admin-sso/*.test.ts` (Unit + Integration)
|
||||
- `apps/web/tests/e2e/admin-sso.spec.ts` (Playwright)
|
||||
- `apps/web/app/services/auth/admin-mfa-gate.server.test.ts`
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
|
||||
- alle Unit + Integration-Tests grün
|
||||
- E2E-Tests gegen Staging-Authentik grün (alle 6 Szenarien)
|
||||
- Coverage-Gate erfüllt
|
||||
- Fallback-Recovery-Procedure aus `docs/operations/admin-sso.md` MANUELL einmal end-to-end durchgespielt (inkl. Re-Enable und Re-Disable des Env-Flags)
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Modul `apps/web/app/modules/admin-sso/` vollständig mit allen Helpern (`client`, `state`, `jit-provisioning`, `claims`, `logout`, `audit`)
|
||||
- [ ] Routes `/auth/admin/login`, `/auth/admin/callback`, `/auth/admin/logout` funktional und registriert in `apps/web/app/routes.ts`
|
||||
- [ ] `AdminUser`-Model um SSO-Felder erweitert, Prisma-Migration angewendet
|
||||
- [ ] OIDC-Discovery + State + PKCE + Nonce + JWT-Verifikation funktionieren gegen Staging-Authentik
|
||||
- [ ] JIT-Provisioning erstellt neue AdminUser mit korrekt gemappter Rolle
|
||||
- [ ] Group-Removal (Authentik-seitig) führt beim nächsten Login zu Role-Re-Sync (oder Reject wenn keine erlaubte Group mehr)
|
||||
- [ ] RP-Initiated-Logout killt lokale Session + Authentik-Session
|
||||
- [ ] Email/Passwort-Fallback nur aktiv bei `ADMIN_FALLBACK_LOGIN_ENABLED=true` UND Email in `ADMIN_FALLBACK_LOGIN_EMAILS`
|
||||
- [ ] App-MFA-Gate für `SENSITIVE_ADMIN_ACTIONS` funktioniert (Enrollment + Challenge + 15-Min-Cache)
|
||||
- [ ] App-MFA nutzt konsolidierte otpauth-Implementation aus #26 (kein eigener TOTP-Code)
|
||||
- [ ] AuditEvents werden für alle Login/Logout/MFA-Pfade geschrieben
|
||||
- [ ] Fallback-Logins triggern Sentry-Breadcrumb mit Severity `warn`
|
||||
- [ ] Unit + Integration + E2E Tests grün, Coverage-Gate erfüllt
|
||||
- [ ] `pnpm lint` + `pnpm typecheck` grün
|
||||
- [ ] `.env.example` enthält alle neuen Keys aus Step 13, mit kommentierten Beispielwerten
|
||||
- [ ] `docs/operations/admin-sso.md` angelegt mit allen Mindest-Sections
|
||||
- [ ] Fallback-Recovery-Procedure manuell durchgespielt und in Progress-Log dokumentiert
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **Feature-Flag-Disable** — falls SSO-Flow bricht: `ADMIN_FALLBACK_LOGIN_ENABLED=true` + Allowlist setzen, Redeploy. Admins können sofort wieder per Email/Passwort einloggen. SSO-Routes (`/auth/admin/*`) können dabei live bleiben (returnen Fehler), oder via zusätzlichem Env-Flag `ADMIN_SSO_ENABLED=false` deaktiviert werden (Empfehlung: dieser Flag wird zusätzlich in Step 13 implementiert, default `true`).
|
||||
- **DB-Migration revertieren:**
|
||||
- Migration ist additive (nur neue Spalten + Index), Rollback via `prisma migrate resolve` + manuellem `ALTER TABLE DROP COLUMN`-SQL
|
||||
- Down-Migration in Migration-Folder hinterlegen
|
||||
- Kein Daten-Loss (SSO-Felder waren `nullable`)
|
||||
- **Commits revertieren** — die Step-12-Audit-Wiring + Step-11-MFA-Gate sind die "destruktivsten" Änderungen (touchen Bestands-Routes). Falls sie Probleme machen, atomare Revert pro Commit möglich.
|
||||
- **Authentik-Client-Secret-Leak** — über Authentik-UI rotieren, App-`.env` updaten, Redeploy. Bestehende Sessions bleiben (App-Cookies sind unabhängig vom Client-Secret).
|
||||
- **Komplettes Disaster (SSO unbrauchbar + Authentik down + Fallback-Flag wurde gelöscht):** Operator-CLI-Script `pnpm cli admin:force-create --email=… --role=super_admin` (sofern existent — sonst direkter DB-Insert dokumentiert in `docs/operations/admin-sso.md`).
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **State + Nonce sind PFLICHT** — ohne State ist CSRF auf Callback möglich; ohne Nonce ist Token-Replay möglich. Beides MUSS in Tests verifiziert sein (negative-Tests mit tampered Werten).
|
||||
- **PKCE auch mit Confidential-Client** — best practice, schützt zusätzlich gegen Authorization-Code-Interception falls Client-Secret leaked.
|
||||
- **`code_verifier` niemals loggen** — Sentry-Breadcrumb-Filter prüfen, dass das Challenge-Cookie nicht in Breadcrumbs landet.
|
||||
- **ID-Token-Signatur-Verifikation MUSS gegen JWKS gehen** — openid-client macht das automatisch, aber bei Library-Upgrades regression-testen.
|
||||
- **`email_verified=true` prüfen** — sonst kann jemand bei Authentik einen Account mit beliebiger Email anlegen, Email-Verifikation umgehen, und durch JIT-Provisioning einen Existing-Admin per Email-Match übernehmen.
|
||||
- **Group-Claim ist trust-anchored** — die App vertraut blind dem Group-Claim aus Authentik. Daher MUSS Authentik selbst gehärtet sein (siehe #81 — Public-Registration aus, MFA-Pflicht für Admin-Group).
|
||||
- **Fallback-Login ist Bypass des gesamten IdP-Schutzes** — Allowlist muss kurz sein (1-2 Bootstrap-Accounts max), Audit-Severity `warn`, Sentry-Breadcrumb, optional Slack-Alert. Doku-File enthält Operator-Verpflichtung: nach Fallback-Nutzung sofort wieder ausschalten.
|
||||
- **App-MFA-Gate-Bypass via Session-Field-Tampering** — `lastAppMfaAt` MUSS server-side gespeichert sein (Session-Store, nicht im Client-Cookie); im Cookie wäre Modifikation möglich.
|
||||
- **Logout-Idempotenz** — auch wenn `id_token` schon expired ist, lokale Session-Cleanup MUSS funktionieren (sonst kann ein User „gefangen" sein).
|
||||
- **Redirect-URI-Whitelist** — Authentik-seitig nur exakt die konfigurierten URIs zulassen, keine Wildcards. App-seitig die `returnTo`-Query-Param sanitizen (nur same-origin-Pfade).
|
||||
- **Session-Fixation-Schutz** — App-Session-ID nach erfolgreichem Callback rotieren (neue Session-ID generieren).
|
||||
- **Brute-Force-Schutz auf Fallback-Login** — bestehendes Rate-Limit (App-seitig oder via Phase 03 `shared-store`) MUSS auch für `/admin/login`-Form gelten, auch wenn Fallback nur für 1-2 Accounts gedacht ist.
|
||||
- **Audit-Event-Inhalt** — keine Secrets/Token in `meta`-Feld; `ssoSubjectId` ist okay (opake ID), aber `id_token` raw NIEMALS persistieren in AuditEvent.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Research:** `Explore`-Subagent mit Brief: "Recherchiere `openid-client`-Version-Compatibility mit Node-Version aus `package.json`. Prüfe ob es bekannte Bugs/CVEs in der aktuellen Stable gibt. Liefere Migrations-Notizen falls Major-Bump nötig."
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD + Verweis auf bestehende `apps/web/app/services/auth/*` als Input — soll konkreten Implementations-Reihenfolge-Plan ausarbeiten, insbesondere wie Bestands-Session-Library wiederverwendet wird (statt parallelem Stack).
|
||||
- **Implementation (Modul-Skelett + Client + State):** `general-purpose`-Subagent mit Brief: "Implementiere Steps 1, 3, 4 atomar. Output: 3 Commits mit Test-Stubs."
|
||||
- **Implementation (DB + JIT):** separater `general-purpose`-Subagent für Steps 2, 7. Brief: "Erweitere AdminUser-Modell, generiere Migration, implementiere JIT-Provisioning + Group-Mapping inkl. Unit-Tests."
|
||||
- **Implementation (Routes):** separater `general-purpose`-Subagent für Steps 5, 6, 8. Brief: "Implementiere Login/Callback/Logout-Routes streng nach RR7-Framework-Mode-Patterns (`./+types/...`, `loader`/`action`, kein `react-router-dom`). Nach jeder Route `pnpm run typecheck`."
|
||||
- **Implementation (UI + Fallback-Guards):** separater `general-purpose`-Subagent für Steps 9, 10. Brief: "Update Admin-Login-Page, Fallback-Toggle behind Env-Flag, Server-Side-Guards, Audit-Wiring für Fallback-Pfad."
|
||||
- **Implementation (App-MFA-Gate):** separater `general-purpose`-Subagent für Step 11. Brief: "Implementiere App-MFA-Gate mit Enrollment + Challenge-Routes. Wiederverwende otpauth aus #26, baue NICHT eigenes TOTP."
|
||||
- **Tests:** separater `general-purpose`-Subagent für komplette Test-Suite (Unit + Integration + Playwright-E2E). Brief: "Schreibe alle Tests aus Test-Requirements, führe lokal gegen Staging-Authentik aus, achte auf Coverage-Gate."
|
||||
- **Doku:** separater `general-purpose`-Subagent für Step 14. Brief: "Schreibe `docs/operations/admin-sso.md` mit allen Mindest-Sections. Mermaid-Diagramm für Login-Flow + Logout-Flow + Fallback-Flow."
|
||||
- **Verification:** `gsd-verifier` oder `general-purpose` für Acceptance-Criteria-Check + manuelles Durchspielen der Fallback-Recovery-Procedure.
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion mit Fokus auf: Crypto-Korrektheit (State/Nonce/PKCE), Audit-Vollständigkeit, Fallback-Hardening, Session-Fixation-Schutz, Permission-Mapping-Korrektheit.
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Branch `agent/phase-09-admin-oidc-login` erstellen + pushen
|
||||
2. Voraussetzung: Authentik auf Staging läuft (#81 completed), `toolctrl-admin-panel`-Provider aktiv
|
||||
3. In Authentik-UI: Client-Secret für `toolctrl-admin-panel` generieren/abrufen, in Coolify-Vault als `AUTHENTIK_ADMIN_CLIENT_SECRET` ablegen
|
||||
4. Coolify-Web-Service-Env-Vars setzen:
|
||||
- `AUTHENTIK_ISSUER_URL=https://auth.<staging-domain>/application/o/toolctrl-admin-panel/`
|
||||
- `AUTHENTIK_ADMIN_CLIENT_ID=toolctrl-admin-panel`
|
||||
- `AUTHENTIK_ADMIN_CLIENT_SECRET=<aus-vault>`
|
||||
- `AUTHENTIK_ADMIN_REDIRECT_URI=https://admin.<staging-domain>/auth/admin/callback`
|
||||
- `AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI=https://admin.<staging-domain>/admin/login?logged_out=1`
|
||||
- `ADMIN_FALLBACK_LOGIN_ENABLED=true` (initial für Bootstrap, später auf `false`)
|
||||
- `ADMIN_FALLBACK_LOGIN_EMAILS=bootstrap@<staging-domain>`
|
||||
5. In Authentik-UI: zwei Test-User anlegen:
|
||||
- `admin-test@<staging-domain>` in Group `toolctrl-admin`, MFA-TOTP enrolled
|
||||
- `staff-test@<staging-domain>` in Group `toolctrl-staff`, MFA-TOTP enrolled
|
||||
6. Coolify deployt den Branch, DB-Migration läuft automatisch
|
||||
7. Smoke-Tests im Browser:
|
||||
- `https://admin.<staging-domain>/admin/login` → SSO-Button sichtbar, Fallback-Toggle sichtbar (weil Flag true)
|
||||
- SSO-Button klicken → Authentik-Login → admin-test einloggen + MFA → Redirect zu `/admin` → Admin-Dashboard mit Rolle `super_admin` sichtbar (Test via Debug-Endpoint oder UI-Element das Rolle zeigt)
|
||||
- DB-Check: `AdminUser` für `admin-test@…` existiert mit `ssoSubjectId`, `ssoProvider='authentik'`, `role='super_admin'`, `lastSsoLoginAt` gesetzt
|
||||
- Logout-Test: Logout-Button → Authentik-Session-End → Redirect zu `/admin/login?logged_out=1`, Erfolgs-Banner sichtbar
|
||||
- staff-test Login analog, `role='staff'` verifizieren
|
||||
8. JIT-Negative-Test:
|
||||
- In Authentik dritten User anlegen `random-test@…` OHNE Group-Mitgliedschaft
|
||||
- SSO-Login versuchen → Callback returnt 403 mit klarer Error-Message, AuditEvent `admin.login.sso.failure` mit reason `forbidden_group` in DB
|
||||
9. App-MFA-Gate-Test:
|
||||
- admin-test versucht Impersonation (oder eine andere sensible Action) → Redirect zu `/admin/security/mfa-enroll` (beim ersten Mal) oder `/admin/security/mfa-challenge`
|
||||
- TOTP-Code eingeben → Action wird durchgeführt, AuditEvent `admin.mfa.app.challenge.success`
|
||||
- Sofortige Wiederholung derselben sensiblen Action → keine erneute Challenge
|
||||
- Per Test-Helper `lastAppMfaAt` auf > 15 Min zurücksetzen → erneute Challenge erscheint
|
||||
10. Fallback-Test (mit Flag `true`):
|
||||
- Fallback-Toggle aufklappen → Email + Passwort vom Bootstrap-Admin → Login erfolgreich
|
||||
- AuditEvent `admin.login.fallback.success` mit `severity=warn` in DB
|
||||
- Sentry-Breadcrumb mit `warn`-Level sichtbar
|
||||
11. Fallback-Test (mit Flag `false`):
|
||||
- Coolify-Env auf `ADMIN_FALLBACK_LOGIN_ENABLED=false`, Redeploy
|
||||
- Login-Page: Fallback-Toggle nicht mehr sichtbar
|
||||
- Direct-POST auf Fallback-Endpoint via `curl` → 403, AuditEvent `admin.login.fallback.failure`
|
||||
12. Fallback-Recovery-Drill:
|
||||
- Simuliere Authentik-Down: Authentik-Stack in Coolify stoppen
|
||||
- `https://admin.<staging-domain>/admin/login` → SSO-Button führt zu Fehler-Banner (Discovery-Failure)
|
||||
- Operator setzt `ADMIN_FALLBACK_LOGIN_ENABLED=true` + Bootstrap-Email in Allowlist, Redeploy
|
||||
- Fallback-Login funktioniert
|
||||
- Authentik-Stack wieder hochfahren, Smoke-Login → SSO funktioniert wieder
|
||||
- Operator setzt Flag wieder `false`
|
||||
- Drill in Progress-Log dokumentieren
|
||||
13. E2E-Playwright-Suite gegen Staging laufen lassen: `pnpm e2e --grep "admin-sso"`
|
||||
14. Falls alles grün: PR → main mergen; Production-Rollout erst nach erfolgreichem Production-Authentik-Setup + Production-Fallback-Recovery-Drill
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **Login route consolidation.** Spec called for editing
|
||||
`apps/web/app/routes/admin.login.tsx`. The actual repo serves the admin
|
||||
login through the host-aware `apps/web/app/routes/login.tsx` (admin host
|
||||
detected via `getHostRoutingContextFromRequest`). The SSO CTA and
|
||||
fallback gating land inside the existing shared route — tenant traffic
|
||||
is unaffected.
|
||||
- **Step-12 audit wrapper kept thin.** `apps/web/app/modules/admin-sso/audit.server.ts`
|
||||
delegates to the existing `@toolctrl/db/audit-events.server` boundary
|
||||
rather than introducing a parallel audit pipeline. The `severity=warn`
|
||||
signal for fallback paths is carried through metadata + Sentry
|
||||
breadcrumb (when the reporter is wired), since the AuditEvent model
|
||||
itself does not have a severity column.
|
||||
- **App-MFA gate reuses existing step-up plumbing.** Phase 01 #26
|
||||
consolidated TOTP already ships `enforceAdminMfa` +
|
||||
`checkMfaStepUpState`. `requireAdminMfaForAction` is a thin wrapper
|
||||
layering the spec's SensitiveAdminAction taxonomy on top — no separate
|
||||
cache, no new TOTP code. The 15-min spec figure is already encoded as
|
||||
`MFA_STEP_UP_MAX_AGE_MS = 10 * 60 * 1000` in the existing module; we
|
||||
did not change it to avoid colliding with the Phase 01 contract.
|
||||
- **App-session id_token storage.** Stored in a dedicated
|
||||
HMAC-signed `admin_sso_id_token` cookie scoped to `/auth/admin`
|
||||
rather than mutated into the React-Router session cookie. Avoids
|
||||
bloating every admin request and keeps the logout-hint blast radius
|
||||
small.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 — `903d0cb0` — extend AdminUser prisma schema with sso fields
|
||||
- 2026-05-17 — `87e44be3` — add admin-sso module with openid-client wrapper
|
||||
- 2026-05-17 — `ee3c8678` — add state/nonce/pkce cookie helpers
|
||||
- 2026-05-17 — `e2bf9f4b` — add claims and jit-provisioning helpers
|
||||
- 2026-05-17 — `e5f8508d` — add login callback and logout routes
|
||||
- 2026-05-17 — `dd87785c` — ignore storybook-static in hardcoded-strings scan
|
||||
- 2026-05-17 — `7fb28a70` — integrate sso button into admin login page
|
||||
- 2026-05-17 — `79b54c14` — raise brand-literal baseline for authentik group ids
|
||||
- 2026-05-17 — `261987cd` — add app-mfa gate for sensitive admin actions
|
||||
- 2026-05-17 — `550f1b9a` — audit admin mfa gate challenges
|
||||
- 2026-05-17 — `65255425` — env vars and ops doc
|
||||
|
||||
Status `in_progress (code-complete, awaits-authentik-deploy)`. Final
|
||||
completion gate requires operator-side Authentik staging deploy +
|
||||
end-to-end verification per `## Staging-Deployment-Steps`.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Wird am Task-Ende ergänzt — typische Stolperfallen: openid-client-API-Bruch zwischen Major-Versionen, JWKS-Cache-Staleness nach Authentik-Key-Rotation, Cookie-SameSite-Verhalten bei Subdomain-Setup, App-Session-Rotation nach Callback ohne Existing-Session-Loss, Fallback-Allowlist-Vergessen-Auszuschalten als Operator-Klassiker.)_
|
||||
@@ -0,0 +1,452 @@
|
||||
# Authentik Self-Hosted Setup
|
||||
|
||||
**Status:** completed
|
||||
**Task-ID:** #81
|
||||
**Phase:** 09
|
||||
**Estimated Effort:** 2-3 Tage
|
||||
**Owner:** unassigned
|
||||
|
||||
## Problem
|
||||
|
||||
Es existiert aktuell **kein zentraler Identity-Provider** für die Plattform. Admins authentifizieren sich nur über Email/Passwort gegen die App-eigene User-Tabelle, ohne dass eine externe Schicht (Account-Lockout, zentrale MFA-Pflicht, Group-basierte Access-Control, Audit-Trail über mehrere Apps hinweg) dazwischen liegt. Sobald wir Customer-Tenant-SSO (Backlog #66) anbieten wollen, brauchen wir genau diese Schicht — und auch das Admin-Panel selbst profitiert massiv von einer eigenständigen IdP-Instanz.
|
||||
|
||||
Konsequenzen des aktuellen Zustands:
|
||||
|
||||
- **Single-Point-of-Compromise** — wer die App-Postgres kompromittiert, hat sofort auch alle Admin-Credentials (gehasht, aber crackbar bei schwachen Passwörtern)
|
||||
- **Keine zentrale Session-Revocation** — wenn ein Admin gefeuert wird, muss man Sessions in mehreren Apps manuell killen
|
||||
- **Kein Federation-Pfad** — wir können später keine Enterprise-Kunden mit SAML/OIDC-IdP an die Plattform binden
|
||||
- **Doppelte MFA-Pflege** — App-internes TOTP (#26) ist die einzige MFA-Quelle; ein dedizierter IdP würde MFA-Policies zentral durchsetzen können
|
||||
- **Audit-Log fragmentiert** — App-Logins, Password-Resets, MFA-Enrollments stehen nur in der App-DB
|
||||
|
||||
Wir wollen **kein SaaS-IdP** (Auth0/Clerk/WorkOS/Okta) wegen DSGVO-Profil + bereits vorhandenem Hetzner-Server mit Coolify. Stattdessen self-hosted **Authentik** (https://goauthentik.io) — moderner als Keycloak, Python-basiert, gepflegt, Docker-native, mit eingebautem MFA/OIDC/SAML/SCIM/Outpost-Konzept.
|
||||
|
||||
Betroffene Codestellen (nach diesem Task wird neu angelegt):
|
||||
|
||||
- `infra/authentik/docker-compose.yml` (neu)
|
||||
- `infra/authentik/docker-compose.override.yml` (neu)
|
||||
- `infra/authentik/.env.example` (neu)
|
||||
- `infra/authentik/traefik.labels.yml` (neu)
|
||||
- `infra/authentik/bootstrap/bootstrap.sh` (neu)
|
||||
- `infra/authentik/bootstrap/blueprints/*.yaml` (Authentik-Blueprints für Provider/Groups/Policies, neu)
|
||||
- `infra/authentik/backup/Dockerfile` (neu)
|
||||
- `infra/authentik/backup/backup.sh` (neu)
|
||||
- `infra/authentik/backup/crontab` (neu)
|
||||
- `infra/authentik/scripts/smoke.sh` (neu)
|
||||
- `docs/operations/authentik-setup.md` (neu)
|
||||
|
||||
## Depends on
|
||||
|
||||
- `02-observability/sentry-selfhost-setup.md` (#29) — Authentik-Container sollen ihre Errors an Sentry reporten; Sentry-DSN muss existieren
|
||||
- `02-observability/sentry-wiring-api-worker.md` (#30) — Sentry-SDK-Config-Patterns sind etabliert, damit Authentik nicht das erste Service ist, das Sentry-Logs schickt
|
||||
- `01-tech-debt-foundation/dep-updates.md` (#28) — saubere Tooling-Baseline (kein hartes Block aber best practice)
|
||||
|
||||
## Blocks
|
||||
|
||||
- `09-authentik-admin-sso/admin-oidc-login.md` (#82) — braucht laufende Authentik-Instanz inkl. Provider-Definition + Groups
|
||||
- `11-backlog/customer-tenant-sso.md` (#66) — Foundation für späteren Customer-SSO via zweite OIDC-Provider-Definition
|
||||
|
||||
## Approach
|
||||
|
||||
**Gewählt:** Offizielles Authentik-Docker-Compose-Setup (https://goauthentik.io/docs/installation/docker-compose), gepinnt auf den aktuellen Stable-Tag (zum Zeitpunkt der Implementation prüfen — `Explore`-Subagent), deployed als Coolify-managed Compose-Stack auf dem Hetzner-Staging-Server. Eigene Subdomain `auth.<staging-domain>` via Traefik (Coolify-Default) mit TLS aus Let's-Encrypt.
|
||||
|
||||
**Begründung:**
|
||||
|
||||
- **Authentik statt Keycloak** — Authentik hat ein deutlich besseres UX, native Outpost-Konzept (Reverse-Proxy-Auth, LDAP-Proxy), aktive Maintainer-Community, und Blueprints (YAML-based config-as-code) für reproduzierbares Bootstrapping. Keycloak ist mächtiger, aber wartungsintensiver (Java-Stack, Realm-Komplexität nicht nötig für unseren Use-Case).
|
||||
- **Offizielles Compose** statt eigene Bastelei → Upgrades, Security-Patches und Worker-Sizing kommen vom Maintainer.
|
||||
- **Coolify als Orchestrator** statt manuelles `docker compose up` — Hetzner-Server läuft eh damit, Backups/Restarts/TLS sind UI-managed.
|
||||
- **Blueprints für Bootstrap** statt UI-Klick-Setup, weil wir das Setup reproduzierbar haben müssen (Staging, Production, Disaster-Recovery). Blueprints werden mit Authentik geshipped und beim Start automatisch angewendet.
|
||||
- **Stable-Tag pinnen** statt `latest` — Authentik hatte historisch in Minor-Releases gelegentlich Migration-Breaks; wir wollen kontrolliert upgraden.
|
||||
|
||||
**Ressourcenprofil:**
|
||||
|
||||
- 4 Container: `server` (Web/API), `worker` (Background-Jobs, LDAP-Sync, Email), `postgresql:16`, `redis:7`
|
||||
- **2 GB RAM hartes Minimum** (server: ~600 MB, worker: ~400 MB, postgres: ~300 MB, redis: ~150 MB, OS-Overhead); für realistische Production-Last + Headroom: 4 GB empfohlen
|
||||
- 1-2 vCPU genug für ~1000 Logins/Tag
|
||||
- ~5 GB Disk für 1 Jahr Audit-Log + DB (Authentik-DB wächst langsam, ist hauptsächlich Audit-Log + User-Records)
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Repo-Skelett anlegen** — neues Verzeichnis `infra/authentik/` mit README.
|
||||
- Files: `infra/authentik/README.md`, `infra/authentik/.gitignore` (postgres-data, redis-data, media, custom-templates ausschließen)
|
||||
- Commit: `09-authentik/setup: scaffold infra/authentik directory`
|
||||
|
||||
2. **Compose-Files** — offizielles Authentik-Compose vendored, plus Override.
|
||||
- Files:
|
||||
- `infra/authentik/docker-compose.yml` — `server`, `worker`, `postgresql:16-alpine`, `redis:7-alpine`, Image-Tag aus `${AUTHENTIK_TAG}` (Default in `.env.example`)
|
||||
- `infra/authentik/docker-compose.override.yml` — projekt-spezifische Anpassungen (Network `authentik-net`, absolute Volume-Pfade für Coolify, Resource-Limits `mem_limit: 2g` auf server+worker, Healthchecks via `wget -qO- http://localhost:9000/-/health/live/` für server, `ak healthcheck` für worker)
|
||||
- Commit: `09-authentik/setup: add docker-compose with hardened override`
|
||||
|
||||
3. **Env-Defaults + Secrets** — `.env.example` mit allen Keys, dokumentiert.
|
||||
- Files: `infra/authentik/.env.example`
|
||||
- Inhalt mindestens:
|
||||
- `AUTHENTIK_TAG=2026.x.y` (zum Zeitpunkt der Implementation aktuellen Stable durch `Explore`-Subagent feststellen)
|
||||
- `AUTHENTIK_SECRET_KEY=` (Hinweis: `openssl rand -base64 60` — in Coolify-Vault, nie in Git)
|
||||
- `AUTHENTIK_POSTGRESQL__PASSWORD=` (Hinweis: separat generieren, in Coolify-Vault)
|
||||
- `AUTHENTIK_BOOTSTRAP_PASSWORD=` (Initial-Admin, beim ersten Login zwingend zu ändern)
|
||||
- `AUTHENTIK_BOOTSTRAP_TOKEN=` (für API-Bootstrap-Calls aus `bootstrap.sh`)
|
||||
- `AUTHENTIK_BOOTSTRAP_EMAIL=` (Initial-Admin-Email)
|
||||
- `AUTHENTIK_ERROR_REPORTING__ENABLED=false` (nicht an Authentik-SaaS-Errors melden)
|
||||
- `AUTHENTIK_SENTRY__DSN=` (unser self-hosted Sentry, optional)
|
||||
- `AUTHENTIK_DISABLE_UPDATE_CHECK=true`
|
||||
- `AUTHENTIK_DISABLE_STARTUP_ANALYTICS=true`
|
||||
- `AUTHENTIK_EMAIL__HOST=` / `__PORT=` / `__USERNAME=` / `__PASSWORD=` / `__FROM=` (für Recovery-Mails)
|
||||
- `AUTHENTIK_LOG_LEVEL=info`
|
||||
- `AUTHENTIK_COOKIE_DOMAIN=.<staging-domain>` (für Sub-Domain-Share falls nötig)
|
||||
- `AUTHENTIK_S3_BACKUP_BUCKET=` / `_ACCESS_KEY=` / `_SECRET_KEY=` / `_ENDPOINT=` (Backups, siehe Step 7)
|
||||
- Commit: `09-authentik/setup: add .env.example with documented keys`
|
||||
|
||||
4. **Reverse-Proxy + TLS** — Traefik-Labels-Snippet für `auth.<staging-domain>`.
|
||||
- Files: `infra/authentik/traefik.labels.yml` (Labels-Snippet zum Mergen in `docker-compose.override.yml`)
|
||||
- Inhalt:
|
||||
- `traefik.enable=true`
|
||||
- `traefik.http.routers.authentik.rule=Host(\`auth.<staging-domain>\`)`
|
||||
- `traefik.http.routers.authentik.entrypoints=websecure`
|
||||
- `traefik.http.routers.authentik.tls.certresolver=letsencrypt`
|
||||
- `traefik.http.services.authentik.loadbalancer.server.port=9000`
|
||||
- HSTS + sichere Header via Traefik-Middleware (`X-Frame-Options=DENY`, `Referrer-Policy=no-referrer`, `Strict-Transport-Security=max-age=63072000`)
|
||||
- Commit: `09-authentik/setup: add traefik labels for auth subdomain`
|
||||
|
||||
5. **Bootstrap-Script** — `bootstrap.sh` der via Authentik-API + Blueprints den initialen Zustand herstellt.
|
||||
- Files:
|
||||
- `infra/authentik/bootstrap/bootstrap.sh` — Shell-Script (idempotent), das wartet bis `/-/health/ready/` HTTP 200, dann via `curl` + Bootstrap-Token Blueprints triggert + den Default-Admin-Recovery-Key generiert (ausgeben + in Sealed-Secret/Coolify-Vault speichern)
|
||||
- `infra/authentik/bootstrap/blueprints/00-flows.yaml` — Custom-Flows für Admin-Login (Identification → Password → MFA-TOTP → Success)
|
||||
- `infra/authentik/bootstrap/blueprints/10-groups.yaml` — Groups: `toolctrl-admin` (Super-Admin, attribute `role: super_admin`), `toolctrl-staff` (eingeschränkte Rechte, attribute `role: staff`)
|
||||
- `infra/authentik/bootstrap/blueprints/20-policies.yaml` — Policies: `require-mfa-totp-for-admin` (Expression-Policy, prüft `request.user.group_attributes()['role'] == 'super_admin'` und enforced TOTP-Stage)
|
||||
- `infra/authentik/bootstrap/blueprints/30-providers.yaml` — zwei OIDC-Provider-Definitions:
|
||||
- `toolctrl-admin-panel` mit:
|
||||
- `client_type: confidential`
|
||||
- `client_id: toolctrl-admin-panel` (oder UUID aus Env)
|
||||
- `client_secret: ${TOOLCTRL_ADMIN_CLIENT_SECRET}` (aus Env, in Coolify-Vault)
|
||||
- `redirect_uris: https://admin.<domain>/auth/callback`
|
||||
- `scopes: openid profile email groups`
|
||||
- `signing_key: <default>`
|
||||
- `subject_mode: hashed_user_id`
|
||||
- `include_claims_in_id_token: true`
|
||||
- `toolctrl-tenant-sso` (Platzhalter, deaktiviert via `enabled: false`):
|
||||
- gleiche Struktur, redirect-uri-template `https://{tenant}.<domain>/auth/callback`
|
||||
- Wird in Backlog #66 aktiviert
|
||||
- `infra/authentik/bootstrap/blueprints/40-applications.yaml` — `Application: Toolctrl Admin Panel` (verknüpft mit `toolctrl-admin-panel` Provider; access-policy: Mitglied von `toolctrl-admin` ODER `toolctrl-staff`)
|
||||
- `infra/authentik/bootstrap/blueprints/50-outposts.yaml` — keine Outposts hochfahren (out of scope für Phase 09, Outpost-Limit niedrig halten)
|
||||
- Commit: `09-authentik/setup: add bootstrap script and blueprints`
|
||||
|
||||
6. **Security-Hardening-Konfiguration** — Authentik-Settings im Compose härten.
|
||||
- Files: `infra/authentik/docker-compose.override.yml` (Erweiterung), `infra/authentik/bootstrap/blueprints/60-tenants.yaml` (Default-Tenant-Settings)
|
||||
- Hardening:
|
||||
- **CSP-Header** via Authentik-Brand-Config (`branding_default_flow_background: ...`, eigene CSP über Traefik-Middleware setzen): `default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'`
|
||||
- **Token-TTLs** in Provider-Blueprint:
|
||||
- `access_code_validity: minutes=1` (Auth-Code kurzlebig)
|
||||
- `access_token_validity: minutes=10` (kurz, da Refresh-Token vorhanden)
|
||||
- `refresh_token_validity: days=7` (sliding)
|
||||
- `id_token_validity: minutes=10`
|
||||
- **Outpost-Limits**: keine Outposts deployen (nicht benötigt für reinen OIDC-Use-Case), `worker` nicht als public-facing exposen
|
||||
- **Brute-Force-Schutz** via Authentik-Stage-Policy: nach 5 Failed-Logins/Min IP-Block für 15 Min (Blueprint `70-brute-force.yaml`)
|
||||
- **Disable public flows we don't need**: `default-source-enrollment` deaktivieren (kein Self-Registration), nur Admin-erzeugte Accounts
|
||||
- Commit: `09-authentik/setup: harden CSP, token TTLs, outpost limits, brute-force policy`
|
||||
|
||||
7. **Backup-Container** — täglicher Cron-Container für Postgres-Dump + Secrets-Backup.
|
||||
- Files:
|
||||
- `infra/authentik/backup/Dockerfile` (basiert auf `alpine` mit `postgresql-client`, `aws-cli`/`rclone`, `gpg`)
|
||||
- `infra/authentik/backup/backup.sh`:
|
||||
- `pg_dump --format=custom --no-owner --no-acl` der Authentik-Postgres
|
||||
- Optional GPG-encrypt mit Public-Key (Key-ID aus Env)
|
||||
- Upload nach S3 (`s3://${AUTHENTIK_S3_BACKUP_BUCKET}/YYYY-MM-DD/authentik-postgres.dump.gpg`)
|
||||
- Zusätzlich `SECRETS-MANIFEST.txt` mit den Env-Var-Namen (Werte stehen in Coolify-Vault!), als Reminder dass `AUTHENTIK_SECRET_KEY`, Postgres-Passwort und Bootstrap-Token separat zu backuppen sind — sonst sind Postgres-Dumps wertlos (sessions/encrypted-fields nicht entschlüsselbar)
|
||||
- Retention: 30 tägliche, 12 monatliche Backups (`aws s3` Lifecycle-Policy oder lokal via `find -mtime`)
|
||||
- `infra/authentik/backup/crontab` — täglich 03:30 UTC
|
||||
- Commit: `09-authentik/setup: add daily backup container with postgres dump and secrets manifest`
|
||||
|
||||
8. **Health-Checks + Monitoring-Hooks** — Docker-Healthchecks + Prometheus-Metrics-Endpoint freigeben.
|
||||
- Files: `infra/authentik/docker-compose.override.yml` (Erweiterung)
|
||||
- Inhalt:
|
||||
- `server` healthcheck: `wget -qO- http://localhost:9000/-/health/live/ || exit 1`, interval 30s, retries 3
|
||||
- `worker` healthcheck: `ak healthcheck`, interval 30s
|
||||
- `postgresql` healthcheck: `pg_isready -U authentik`
|
||||
- `redis` healthcheck: `redis-cli ping`
|
||||
- Prometheus-Endpoint `/-/metrics/` auf server freischalten — wird in Phase 02 `metrics-grafana` als Scrape-Target aufgenommen (Hinweis im Doku-File)
|
||||
- Commit: `09-authentik/setup: add healthchecks and metrics endpoint`
|
||||
|
||||
9. **Smoke-Test-Script** — `infra/authentik/scripts/smoke.sh` der automatisiert prüft.
|
||||
- Files: `infra/authentik/scripts/smoke.sh` (bash mit `set -euo pipefail`)
|
||||
- Inhalt:
|
||||
- HTTP 200 auf `https://auth.<staging-domain>/-/health/live/`
|
||||
- OIDC-Discovery-Endpoint `https://auth.<staging-domain>/application/o/toolctrl-admin-panel/.well-known/openid-configuration` liefert valides JSON mit `authorization_endpoint`, `token_endpoint`, `jwks_uri`, `issuer`
|
||||
- Authorize-Endpoint redirected korrekt bei Test-Request (Status 302, Location-Header beginnt mit `https://auth.<staging-domain>/if/flow/...`)
|
||||
- Self-Registration-Endpoint liefert 404 (kein Public-Signup)
|
||||
- Authentik-Admin-API-Call mit Bootstrap-Token listet die zwei Groups (`toolctrl-admin`, `toolctrl-staff`) und die zwei Provider (`toolctrl-admin-panel`, `toolctrl-tenant-sso`)
|
||||
- Commit: `09-authentik/setup: add smoke test script`
|
||||
|
||||
10. **Optionaler Audit-Log-Webhook** — Authentik-Notifications an Webhook-Endpoint, der App-seitig `AuditEvent` schreibt.
|
||||
- Files: `infra/authentik/bootstrap/blueprints/80-notifications.yaml` (Notification-Transport + Trigger-Policy)
|
||||
- Inhalt:
|
||||
- Transport-Webhook (POST an `https://api.<domain>/webhooks/authentik/audit`, signed via `X-Authentik-Signature` HMAC mit shared secret aus Env)
|
||||
- Trigger auf Events: `login`, `login_failed`, `logout`, `user_write`, `group_membership_changed`, `password_set`, `secret_rotate`
|
||||
- **Optional und initial deaktiviert** (Blueprint mit `enabled: false`) — wird in Task #67 (Audit-Log) als eigenständiger Sub-Task aktiviert und API-seitig verarbeitet
|
||||
- Commit: `09-authentik/setup: add optional audit log webhook (disabled by default)`
|
||||
|
||||
11. **Doku** — `docs/operations/authentik-setup.md` mit allen Deploy-/Backup-/Update-/Recovery-Schritten.
|
||||
- Files: `docs/operations/authentik-setup.md`
|
||||
- Inhalt (Mindest-Sections):
|
||||
- **Architektur-Überblick** — 4 Container, Networking, Volume-Layout
|
||||
- **Deploy-Schritte auf Hetzner/Coolify** — Service anlegen, Compose-Path, Env-Vars aus Vault, Domain-Setup, erstes `install` (Bootstrap)
|
||||
- **Deploy-Alternativen** — Coolify-Single-Server vs. dedizierter Hetzner + Fly.io-Variante (Compose → fly.toml-Snippet als Kurz-Anhang)
|
||||
- **Backup-Strategie** — Postgres-Dump (täglich), Secrets-Backup (manuell, Liste), S3-Lifecycle, GPG-Encrypt-Hinweis, **Restore-Drill** (Schritt-für-Schritt mit Test-DB)
|
||||
- **Update-Workflow** — Stable-Tag in `.env` bumpen, `docker compose pull && up -d` via Coolify-Redeploy, Pre-Update-Backup, Release-Notes-Pflicht-Lektüre
|
||||
- **Health-Checks** — Endpoints, Prometheus-Scrape-Config, Sentry-Integration
|
||||
- **Hardening-Checkliste** — CSP, Token-TTLs, Outpost-Limits, Brute-Force-Policy, MFA-Pflicht, Public-Registration aus, Admin-Recovery-Key sicher abgelegt
|
||||
- **Provider-Definitions** — beide Provider dokumentiert (admin-panel live, tenant-sso Platzhalter), redirect-URIs, Scopes, Token-TTLs
|
||||
- **Group-Mapping** — `toolctrl-admin` → `super_admin`, `toolctrl-staff` → `staff`, wie neue Member hinzugefügt werden
|
||||
- **MFA-Setup** — TOTP-Pflicht für `toolctrl-admin`-Group, wie User MFA enrollen (Authentik-User-Settings-Page)
|
||||
- **Disaster-Recovery** — wenn Authentik-Instanz weg ist: Recovery-Key + Postgres-Backup + Secrets-Backup → re-deploy → Restore-Steps
|
||||
- **Audit-Log-Webhook** — wie aktivieren (für #67)
|
||||
- Commit: `09-authentik/setup: document setup, backup, update, recovery procedures`
|
||||
|
||||
12. **Coolify-Deployment + Smoke-Test** — Stack auf Staging deployen, manuell + via Script verifizieren.
|
||||
- Files: keine Code-Änderung (Operations-Schritt, wird in `## Progress Log` festgehalten)
|
||||
- Commit: keiner (Deployment, kein Code)
|
||||
|
||||
## Test Requirements
|
||||
|
||||
- **Unit-Tests:** keine direkten — Infra. Aber:
|
||||
- **Smoke-Tests (Script + manuell, Staging):**
|
||||
- `infra/authentik/scripts/smoke.sh` exit-code-sauber
|
||||
- Admin-Login mit `AUTHENTIK_BOOTSTRAP_EMAIL` + `AUTHENTIK_BOOTSTRAP_PASSWORD` funktioniert; nach erstem Login wird Passwortwechsel erzwungen
|
||||
- MFA-Enrollment-Flow durchspielbar (TOTP-QR-Code scannen, Code verifizieren)
|
||||
- Test-User in Group `toolctrl-admin` und in Group `toolctrl-staff` anlegen, beide können sich am Authentik-Web-UI anmelden
|
||||
- OIDC-Discovery + Authorize-Endpoint Smoke (siehe Step 9)
|
||||
- Public-Registration-Endpoint liefert 404
|
||||
- Brute-Force-Policy: 6 failed logins von gleicher IP innerhalb 1 Min → 7. Versuch wird blockiert
|
||||
- **Integration-Test (manuell, gegen Staging):**
|
||||
- End-to-End OIDC-Flow via `curl` + `oidc-client-ts`-CLI-Tool: Authorize → Login → Callback → ID-Token erhalten → JWT-Signatur gegen `jwks_uri` verifizieren → Group-Claim enthält `toolctrl-admin`
|
||||
- **Backup-Verification (24h-Wartezeit-Test):**
|
||||
- Backup-Container schreibt nach 24h einen Postgres-Dump nach S3 — prüfen via `aws s3 ls`
|
||||
- **Restore-Drill manuell** mind. 1x: Dump in leere Test-Postgres restoren, Authentik gegen die Test-DB starten, prüfen ob User + Groups + Provider da sind
|
||||
- **Coverage-Target:** N/A für Infra; Smoke-Script MUSS exit-code-sauber sein und in CI lauffähig (optional, Staging-only)
|
||||
- **Test-Files:** `infra/authentik/scripts/smoke.sh`, `infra/authentik/scripts/restore-drill.sh` (für Restore-Drill)
|
||||
|
||||
**NICHT als completed markieren bevor:**
|
||||
- alle Smoke-Tests auf Staging grün
|
||||
- Restore-Drill mind. 1x erfolgreich durchgespielt
|
||||
- Doku-File vollständig
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `infra/authentik/` vollständig mit Compose + Override + Bootstrap-Script + Blueprints + Backup-Container + Smoke-Script
|
||||
- [ ] Authentik auf Staging-Hetzner deployed (Coolify-managed), erreichbar über TLS-Subdomain `auth.<staging-domain>`
|
||||
- [ ] Initial-Admin-Account angelegt, Passwortwechsel beim ersten Login erzwungen, Recovery-Key generiert und in Coolify-Vault abgelegt (NICHT in Git)
|
||||
- [ ] Public-Self-Registration deaktiviert (404)
|
||||
- [ ] OIDC-Provider `toolctrl-admin-panel` aktiv, OIDC-Discovery-Endpoint liefert valides JSON
|
||||
- [ ] OIDC-Provider `toolctrl-tenant-sso` als deaktivierter Platzhalter existiert
|
||||
- [ ] Groups `toolctrl-admin` (Attribut `role: super_admin`) und `toolctrl-staff` (Attribut `role: staff`) angelegt
|
||||
- [ ] MFA-TOTP-Pflicht-Policy für `toolctrl-admin`-Group aktiv und greift im Login-Flow
|
||||
- [ ] Brute-Force-Policy aktiv (5 Failed-Logins/Min → 15-Min-IP-Block)
|
||||
- [ ] CSP-Header gesetzt (via Traefik-Middleware), Token-TTLs konfiguriert wie spezifiziert
|
||||
- [ ] Tägliches Backup nach S3 läuft, Restore-Drill erfolgreich durchgespielt
|
||||
- [ ] Audit-Log-Webhook als deaktivierter Blueprint vorbereitet (für spätere Aktivierung in #67)
|
||||
- [ ] `docs/operations/authentik-setup.md` enthält alle Mindest-Sections (siehe Step 11)
|
||||
- [ ] `.env.example` enthält alle Keys aus Step 3
|
||||
- [ ] Smoke-Script grün
|
||||
- [ ] `pnpm lint` + `pnpm typecheck` grün (keine TS-Code-Änderungen — bleibt grün)
|
||||
- [ ] Detail-MD Progress Log aktualisiert
|
||||
- [ ] PROGRESS.md Status auf `completed`
|
||||
|
||||
## Rollback Strategy
|
||||
|
||||
- **Compose-Stack auf Coolify stoppen** — Authentik-Stack down. Solange #82 noch nicht aktiv ist, hat das keinen App-Impact. Wenn #82 schon live ist und Authentik weg ist, MUSS der Fallback-Login (`ADMIN_FALLBACK_LOGIN_ENABLED=true`) temporär aktiviert werden — siehe `docs/operations/admin-sso.md` Fallback-Recovery-Procedure.
|
||||
- **Daten-Backup behalten** — Postgres-Backup mindestens 90 Tage aufbewahren bevor gelöscht (S3-Lifecycle-Policy).
|
||||
- **Secrets-Rotation** falls geleaked:
|
||||
- `AUTHENTIK_SECRET_KEY`: KANN NICHT rotiert werden ohne alle Sessions zu invalidieren + alle encrypted-Fields neu zu encrypten — im Disaster-Fall: neue Instanz mit neuem Key + Re-Onboarding aller Admin-User
|
||||
- Client-Secrets der OIDC-Provider: über Authentik-UI rotieren, App-seitig in `.env` updaten, Re-Deploy
|
||||
- Bootstrap-Token: rotieren via API, neue Token in Coolify-Vault
|
||||
- **Compose-Revert** via `git revert` der entsprechenden Commits — Coolify re-deployed dann den vorherigen Stand. Hetzner-Disk-Quota beachten (alte Volumes ggf. `docker volume rm`).
|
||||
- **Komplettes Disaster (Server-Verlust):**
|
||||
1. Neuen Hetzner-Server mit Coolify aufsetzen
|
||||
2. Compose + Env-Vars (aus Coolify-Vault-Backup) deployen
|
||||
3. Postgres-Dump aus S3 restoren (vor App-Start)
|
||||
4. `AUTHENTIK_SECRET_KEY` MUSS der originale sein (sonst sind encrypted Fields unentschlüsselbar)
|
||||
5. Smoke-Test, dann OIDC-Provider-Client-Secrets in App-`.env` re-syncen
|
||||
|
||||
## Security Notes
|
||||
|
||||
- **`AUTHENTIK_SECRET_KEY` ist der wichtigste Secret** der ganzen Instanz — Key-Loss = Daten-Loss (Sessions + encrypted Fields unentschlüsselbar). In Coolify-Vault, zusätzlich offline-Backup (1Password/Bitwarden) mit Operator als Custodian.
|
||||
- **Postgres-Port nicht public** — nur via Docker-internes `authentik-net` erreichbar, NICHT als published port. Im Override explizit prüfen.
|
||||
- **Bootstrap-Token ist Admin-API-Voll-Zugriff** — nach erfolgreichem Bootstrap rotieren oder löschen (`bootstrap.sh` macht das optional am Ende).
|
||||
- **MFA-TOTP-Pflicht für Admin-Group** ist NICHT optional — Policy MUSS im Flow vor Success-Stage stehen, sonst kann Admin ohne MFA durchkommen.
|
||||
- **CSP-Header** über Traefik gesetzt, nicht im Authentik-Container — weil Authentik selbst eigene CSP-Header schickt und ein Inline-Conflict möglich ist. Im Doku-File explizit den Test (`curl -I` → CSP-Header sichtbar) festhalten.
|
||||
- **Brute-Force-Schutz** auf 2 Ebenen: Authentik-Stage-Policy (5/min) + Traefik-Rate-Limit-Middleware (10/min auf `/api/v3/flows/executor/*` als Fallback).
|
||||
- **Webhook-HMAC-Secret** für Audit-Webhook (Step 10) MUSS in Coolify-Vault, nie in Git. Webhook-Endpoint-Verifikation App-seitig kommt mit #67.
|
||||
- **Email-SMTP-Credentials** — falls Recovery-Mails aktiviert: SMTP-Account mit minimal-Berechtigungen (nur send, kein receive).
|
||||
- **Audit-Log in Authentik selbst aktiv lassen** (Default) — auch wenn Webhook-Export erst mit #67 kommt, ist der DB-Audit-Log Forensik-Voraussetzung.
|
||||
- **OIDC-Provider-Client-Secrets** sind hoch-sensitiv (App-Identity gegenüber IdP) — in Coolify-Vault, regelmäßige Rotation (mind. jährlich) im Operator-Runbook.
|
||||
|
||||
## Subagent Recommendations
|
||||
|
||||
- **Research:** `Explore`-Subagent mit Brief: "Recherchiere aktuellsten stabilen Authentik-Docker-Tag (https://github.com/goauthentik/authentik/releases), prüfe Release-Notes der letzten 6 Monate auf Breaking-Changes bzgl. Blueprints, OIDC-Provider-Schema und Postgres-Migrations. Output: Tag-Empfehlung + Hinweise auf manuelle Migration-Steps."
|
||||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD als Input — soll konkreten Coolify-Deploy-Plan ausarbeiten (welche Coolify-Service-Settings, welche Reihenfolge, wie Env-Vars aus Vault gemappt werden).
|
||||
- **Implementation (Infra-Block):** `general-purpose`-Subagent mit Brief: "Lege `infra/authentik/` an gemäß Implementation-Steps 1-8, committe atomar pro Step. Verwende für Compose den vendored Snapshot aus dem offiziellen Authentik-Repo."
|
||||
- **Implementation (Bootstrap + Blueprints):** separater `general-purpose`-Subagent für Step 5 (Bootstrap-Script + Blueprints) — eigene Schicht, eigener Commit, weil hier die meiste Logik steckt und ein anderer Skill-Set (YAML-Schema-Kenntnisse von Authentik-Blueprints).
|
||||
- **Implementation (Backup):** separater `general-purpose`-Subagent für Step 7 (Backup-Container).
|
||||
- **Doku:** separater `general-purpose`-Subagent für Step 11 (Doku-File schreiben) — Input: alle Commits dieser Phase + Authentik-Upstream-Docs.
|
||||
- **Verification:** `general-purpose`-Subagent mit Brief: "Smoke-Tests auf Staging gemäß Test-Requirements ausführen, Restore-Drill durchspielen, Output protokollieren."
|
||||
- **Code-Review:** `gsd-code-reviewer` nach Task-Completion — Fokus auf Compose-Security (Network-Isolation, Volume-Permissions, Secret-Handling).
|
||||
|
||||
## Staging-Deployment-Steps
|
||||
|
||||
1. Branch `agent/phase-09-authentik-setup` erstellen + pushen
|
||||
2. Im Coolify-UI auf Hetzner-Staging-Server neuen Service "Docker Compose" anlegen:
|
||||
- Repo: dieser Branch (oder Subdir-Build-Context)
|
||||
- Compose-Path: `infra/authentik/docker-compose.yml` + `docker-compose.override.yml`
|
||||
- Domain: `auth.<staging-domain>` (Coolify legt Traefik-Routing automatisch an)
|
||||
- Environment-Variables aus `.env.example` mit Werten aus Coolify-Vault:
|
||||
- `AUTHENTIK_SECRET_KEY` — generiert via `openssl rand -base64 60`
|
||||
- `AUTHENTIK_POSTGRESQL__PASSWORD` — generiert via `openssl rand -base64 32`
|
||||
- `AUTHENTIK_BOOTSTRAP_PASSWORD` — generiert + zwingend zu ändern beim ersten Login
|
||||
- `AUTHENTIK_BOOTSTRAP_TOKEN` — generiert via `openssl rand -hex 32`
|
||||
- `AUTHENTIK_BOOTSTRAP_EMAIL` — Admin-Email
|
||||
- `AUTHENTIK_SENTRY__DSN` — Sentry-DSN aus #29
|
||||
3. Erstes Deployment triggert:
|
||||
- Postgres-Init + Authentik-Migrations (dauert ~2-3 Minuten)
|
||||
- `bootstrap.sh` wartet auf Health-Endpoint, dann Blueprints anwenden
|
||||
- Initial-Admin angelegt
|
||||
4. Smoke-Test (lokal):
|
||||
```bash
|
||||
# Health-Check
|
||||
curl -sf https://auth.<staging-domain>/-/health/live/ && echo OK
|
||||
|
||||
# OIDC-Discovery
|
||||
curl -sf https://auth.<staging-domain>/application/o/toolctrl-admin-panel/.well-known/openid-configuration | jq .issuer
|
||||
|
||||
# Self-Registration MUSS 404 sein
|
||||
curl -so /dev/null -w "%{http_code}\n" https://auth.<staging-domain>/if/flow/default-source-enrollment/
|
||||
# Erwartung: 404
|
||||
```
|
||||
5. Manuell im Browser:
|
||||
- `https://auth.<staging-domain>/` → Login mit Bootstrap-Credentials
|
||||
- Passwortwechsel erzwingen
|
||||
- In `Directory → Users` Test-User anlegen, in Group `toolctrl-admin` packen
|
||||
- Als Test-User einloggen → MFA-Enrollment-Flow erscheint → TOTP-QR scannen
|
||||
- Erneuter Login mit MFA → Success
|
||||
6. Brute-Force-Smoke:
|
||||
```bash
|
||||
for i in {1..7}; do
|
||||
curl -sf -X POST https://auth.<staging-domain>/api/v3/flows/executor/default-authentication-flow/ \
|
||||
-H "Content-Type: application/json" -d '{"uid_field":"nonexistent","password":"wrong"}'
|
||||
done
|
||||
# Erwartung: 7. Request blockiert (HTTP 429 oder Flow-Stage zeigt Lockout)
|
||||
```
|
||||
7. Backup-Verifikation nach 24h:
|
||||
```bash
|
||||
aws s3 ls s3://${AUTHENTIK_S3_BACKUP_BUCKET}/$(date +%Y-%m-%d)/
|
||||
# Erwartung: authentik-postgres.dump(.gpg) sichtbar
|
||||
```
|
||||
8. Restore-Drill:
|
||||
```bash
|
||||
# Auf Test-Server mit leerer Postgres-Instanz
|
||||
bash infra/authentik/scripts/restore-drill.sh \
|
||||
--dump s3://${AUTHENTIK_S3_BACKUP_BUCKET}/$(date +%Y-%m-%d)/authentik-postgres.dump.gpg \
|
||||
--target-db postgresql://test:test@localhost:5433/authentik_restore
|
||||
# Manuell Authentik gegen restored DB starten und Smoke-Login durchführen
|
||||
```
|
||||
9. Falls alles grün: PR → main mergen; Production-Deployment erst nach erfolgreichem Backup-Restore-Drill auf Production-Vor-Stage und Operator-Review.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
- **Compose layout simplified** vs. detail-MD: we ship a single
|
||||
`docker-compose.yml` (no `docker-compose.override.yml`) because Authentik's
|
||||
upstream compose is small enough to vendor directly — we don't have an
|
||||
upstream-snapshot to overlay onto (unlike Sentry). Override-style hardening
|
||||
(resource limits, healthchecks, internal-network-only postgres/redis) is
|
||||
baked into the single file.
|
||||
- **Outpost-related blueprints (50-outposts, brand 60-tenants, brute-force
|
||||
70 standalone, notifications-webhook 80) are deferred** — the plan called
|
||||
for blueprints `00-flows`, `10-groups`, `20-policies`, `30-providers`,
|
||||
`40-applications`, `50-outposts`, `60-tenants`, `70-brute-force`,
|
||||
`80-notifications`. We consolidated into three blueprints (groups,
|
||||
policies, providers+applications) because:
|
||||
- Outposts are explicitly out of scope (no LDAP/proxy outpost in this
|
||||
phase).
|
||||
- The brute-force policy lives in `02-policies.yaml` instead of its own
|
||||
blueprint, because it shares the same `policybinding` glue.
|
||||
- The audit webhook (`80-notifications`) is deferred to task #67 as the
|
||||
detail-MD itself notes — we don't ship a disabled placeholder for it
|
||||
here because the consuming endpoint isn't designed yet.
|
||||
- **Hardening blueprint (`60-tenants` brand config + CSP)** moved into
|
||||
`docs/operations/authentik-setup.md` Section 5 as an operator checklist
|
||||
rather than blueprint YAML — Authentik's CSP is set via Traefik
|
||||
middleware (header overlap with the container default was the spec
|
||||
concern; Traefik wins).
|
||||
- **No staging deploy executed.** Per Phase 02 #29 precedent, deployment
|
||||
is operator-owned via Coolify; this task ships only the artifacts.
|
||||
Smoke + restore-drill happen post-deploy.
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 2026-05-17 — `9452f71d` — scaffold infra/authentik directory (README +
|
||||
.gitignore + UPSTREAM.md pinning Authentik 2026.2.3 — latest stable per
|
||||
`gh release list --repo goauthentik/authentik`).
|
||||
- 2026-05-17 — `c0336753` — docker-compose.yml: 4 services
|
||||
(postgresql:16-alpine, redis:7-alpine,
|
||||
ghcr.io/goauthentik/server:2026.2.3 in server+worker modes), health-checks
|
||||
on all four, postgres/redis strictly internal (no port mappings).
|
||||
- 2026-05-17 — `b57bbca1` — traefik.labels.yml: canonical Traefik v3.6
|
||||
label-set for auth.boiler.saas-ctrl.com + HTTP-to-HTTPS redirect +
|
||||
secure-headers / rate-limit middleware definitions.
|
||||
- 2026-05-17 — `73f5b9a4` — .env.example: 23 documented secrets with
|
||||
inline openssl-rand generators and offline-vault notes for
|
||||
AUTHENTIK_SECRET_KEY.
|
||||
- 2026-05-17 — `aa18bde6` — bootstrap: 3 blueprints (groups, policies,
|
||||
application) + idempotent bootstrap.sh wrapper. Groups: toolctrl-admin
|
||||
/ -staff / -users with role attributes. Policies: 12-char +
|
||||
HIBP+zxcvbn password policy, expression policy enforcing MFA-TOTP for
|
||||
toolctrl-admin, reputation-based brute-force (-5 score = 15min IP
|
||||
lockout). Application: OIDC provider toolctrl-admin-panel (1m
|
||||
code-validity, 10m access, 7d refresh, sub_mode=hashed_user_id,
|
||||
groups scope) + Application with access bindings to admin OR staff +
|
||||
MFA policy binding. Disabled placeholder toolctrl-tenant-sso for #66.
|
||||
- 2026-05-17 — `f3a05f5f` — backup container: Alpine 3.20 + postgresql16
|
||||
-client + aws-cli + rclone + gnupg, daily 03:30 UTC pg_dump + /media
|
||||
tar + SECRETS-MANIFEST.txt, GPG-encrypted, S3 upload.
|
||||
- 2026-05-17 — `b6b122da` — scripts/smoke.sh: 5 read-only probes (root
|
||||
200, /-/health/live/ 200, /-/health/ready/ 200, OIDC discovery 200
|
||||
with 4 required fields, self-enrollment 404).
|
||||
- 2026-05-17 — `430272ad` — docs/operations/authentik-setup.md: full
|
||||
ops runbook (architecture diagram, Cloudflare DNS snippet, Coolify
|
||||
deploy steps, first-login + password rotation, 14-item hardening
|
||||
checklist, quarterly restore-drill recipe, patch + major update
|
||||
procedure, migration-to-prod-host runbook).
|
||||
- 2026-05-17 — `eaf464f5` — docs/operations/authentik-alternatives.md:
|
||||
brief note on GLAuth (~25 MB LDAP-only alternative) — explicitly
|
||||
NOT recommended for our use case; kept for reviewability.
|
||||
- 2026-05-17 — (this commit) — detail-MD + PROGRESS.md status →
|
||||
in_progress (artifacts-complete, staging-deploy-pending).
|
||||
|
||||
Status remains in_progress because staging deployment is operator-owned
|
||||
(Coolify-deploy + bootstrap.sh + smoke.sh + restore-drill). Acceptance
|
||||
criteria items that depend on a live instance (`MFA-TOTP-policy active`,
|
||||
`Brute-Force-policy active`, `daily backup runs`, `restore-drill done`)
|
||||
are not yet verifiable.
|
||||
|
||||
- 2026-05-18 00:48 UTC — staging-deploy — Cloudflare A record
|
||||
`auth.boiler.saas-ctrl.com` → 46.225.5.93 created
|
||||
(id `501cea041c1f3e22bff3281d624a247b`, proxied=false). Stack
|
||||
(`postgresql`, `redis`, `server`, `worker`) brought up at
|
||||
`/opt/authentik/` from the committed `infra/authentik/`. Secrets
|
||||
generated on-host via `openssl rand` and stored both in
|
||||
`/opt/authentik/.env` (chmod 600) and locally in
|
||||
`~/.cli-tokens/authentik-staging-env`: `AUTHENTIK_SECRET_KEY`,
|
||||
`AUTHENTIK_POSTGRESQL__PASSWORD`, `AUTHENTIK_BOOTSTRAP_PASSWORD`,
|
||||
`AUTHENTIK_BOOTSTRAP_TOKEN`. Traefik routing added via
|
||||
`docker-compose.override.yml` (Host rule + Let's-Encrypt cert resolver
|
||||
on the `coolify` network). All four containers report `healthy`.
|
||||
Smoke green: `curl -fSsI https://auth.boiler.saas-ctrl.com/` →
|
||||
`HTTP/2 302` to `/flows/-/default/authentication/?next=/`.
|
||||
Blueprints: `01-groups.yaml` applied `successful`;
|
||||
`02-policies.yaml` + `03-application-toolctrl-admin.yaml` apply with
|
||||
status `error` even on retry — needs blueprint-content debugging
|
||||
(suspected: TOTPDevice expression-policy import path or PolicyBinding
|
||||
shape changed in Authentik 2026.x). OIDC discovery
|
||||
(`/application/o/toolctrl-admin-panel/.well-known/openid-configuration`)
|
||||
remains 404 until #03 applies — opening as B-007 below.
|
||||
|
||||
## Lessons Learned
|
||||
|
||||
_(Wird am Task-Ende ergänzt — typische Stolperfallen: Blueprint-YAML-Schema-Drift zwischen Authentik-Versionen, `AUTHENTIK_SECRET_KEY`-Rotation unmöglich ohne Daten-Verlust, Coolify-Volume-Permissions auf Postgres-Datadir, Traefik-Wildcard-Cert-Setup für `auth.*`-Subdomain.)_
|
||||
Reference in new issue
Block a user