CI / Web-Barrierefreiheitspruefung (axe, Tastatur, Reflow, Textabstaende) (push) Canceled after 0s
CI / Web-Barrierefreiheitspruefung (axe, Tastatur, Reflow, Textabstaende) (pull_request) Canceled after 0s
CI / Web (dms-browser) (push) Canceled after 0s
CI / Core-Modul (Build/Vet/Test) (push) Canceled after 0s
CI / DMS Security-Test-Gate (AC5, Merge-Gate) (push) Canceled after 0s
CI / DMS-Modul Supply-Chain-Scan (govulncheck) (push) Canceled after 0s
CI / Web (pdf-viewer) (push) Canceled after 0s
CI / Web (shl) (push) Canceled after 0s
Supply-Chain-Scan (Go) / govulncheck (push) Canceled after 0s
CI / Core-Modul (Build/Vet/Test) (pull_request) Canceled after 0s
CI / DMS Security-Test-Gate (AC5, Merge-Gate) (pull_request) Canceled after 0s
CI / DMS-Modul Supply-Chain-Scan (govulncheck) (pull_request) Canceled after 0s
CI / Web (dms-browser) (pull_request) Canceled after 0s
CI / Web (pdf-viewer) (pull_request) Canceled after 0s
CI / Web (shl) (pull_request) Canceled after 0s
Core-Schnittstellen-Vertragstests / contract-tests (pull_request) Canceled after 0s
Supply-Chain-Scan (Go) / govulncheck (pull_request) Canceled after 0s
Supply-Chain-Scan (npm) / npm-audit (pull_request) Canceled after 0s
Core-Pflichttest-Gate / pflichttest-gate (pull_request) Canceled after 0s
RBAC-Rollenhierarchie-Pflichtgate / rbac-policy-invariant (pull_request) Canceled after 0s
CI / DMS-Modul (Lint/Build/Test/Coverage/Artefakt) (push) Canceled after 0s
CI / DMS-Modul (Lint/Build/Test/Coverage/Artefakt) (pull_request) Canceled after 0s
Backend (kleinstmoeglich, wie im Ticket vorgesehen): - internal/auth: TokenIssuer.IssueWithTTL, LoginService.LoginWithTTL (additiv, bestehende Issue/Login unveraendert) - internal/totp: LoginWithTOTPTTL (durchlaeuft denselben 2FA-Ablauf) - cmd/account-api: neue Route POST /auth/mobile-login (JSON-Token statt Cookie, 90 Tage TTL statt 30 Minuten) Android-App (android/dms-capture, Kotlin, Gradle-Projekt): - CameraX-Erfassung mit Live-Vorschau, erneuter Aufnahme, Mehrseiten- Sammlung (AC2) - Ruft ausschliesslich die bestehende DOC-01-Upload-API auf, kein neuer Backend-Uploadpfad (AC3) -- echter Architektur-Fund dabei: dms-app erwartet ein audience-gebundenes Modul-Token (aud=dms), kein rohes Sitzungstoken; App tauscht ueber den bereits bestehenden Endpunkt POST /auth/module-token (Cookie-Header), dokumentiert im Pruefprotokoll - Room-basierte Offline-Warteschlange mit sichtbarem Status, WorkManager fuer automatische Nachreichung ohne Nutzeraktion (AC4) - Verstaendliche Fehlermeldungen bei Groessen-/Typ-Ablehnung statt nur Fehlercode (AC5) - Internes APK, kein Play-Store-Zwang (AC6) Real getestet: Ende-zu-Ende-Auth-Kette (Login -> Modul-Token -> Bearer gegen echten dms-app) auf Host 204, 13/13 Kotlin-Unit-Tests gruen, echter APK-Build auf Host 236 (Android-SDK dort vorhanden, kein Install auf der Entwicklungsmaschine, Gradle projektlokal nachgezogen statt System-Install). Offen (Pruefprotokoll): Kamera-/Offline-/Smoke-Install-Pruefungen brauchen einen Android-Emulator; kein System-Image auf Host 236 installiert, Nachinstallation bewusst nicht ohne Rueckfrage vorgenommen. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
285 lines
9.4 KiB
Go
285 lines
9.4 KiB
Go
package totp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
"gitea.perlbach24.de/scripte/nexarch/internal/lockout"
|
|
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
)
|
|
|
|
// Handler stellt Login (inklusive optionalem zweiten Faktor) und die
|
|
// 2FA-Einrichtung als HTTP-Endpunkte bereit (IAM-08). Ersetzt auth.Handler.Login
|
|
// nicht (der bleibt fuer Faelle ohne 2FA-Bedarf nutzbar), bietet aber den
|
|
// EINEN Login-Endpunkt, den das Frontend tatsaechlich aufruft — LoginWithTOTP
|
|
// deckt beide Faelle (mit/ohne 2FA) bereits ab.
|
|
type Handler struct {
|
|
users *user.TenantUserStore
|
|
totp *Store
|
|
login *auth.LoginService
|
|
issuer string // fuer die otpauth://-Provisioning-URI (Akzeptanzkriterium 1)
|
|
|
|
// QA-15 F-04: optionaler Schutz gegen Rate-Guessing (Kontosperre ueber
|
|
// Postgres, Begrenzung je Quelladresse im Prozess).
|
|
lockStore *lockout.Store
|
|
ipLimiter *lockout.IPLimiter
|
|
trustForwarded bool
|
|
}
|
|
|
|
// WithLoginGuard aktiviert Kontosperre und Quelladressen-Begrenzung fuer Login.
|
|
// Ein nil-Argument laesst die jeweilige Pruefung aus.
|
|
func (h *Handler) WithLoginGuard(store *lockout.Store, limiter *lockout.IPLimiter, trustForwarded bool) *Handler {
|
|
c := *h
|
|
c.lockStore, c.ipLimiter, c.trustForwarded = store, limiter, trustForwarded
|
|
return &c
|
|
}
|
|
|
|
func NewHandler(users *user.TenantUserStore, totpStore *Store, login *auth.LoginService, issuer string) *Handler {
|
|
return &Handler{users: users, totp: totpStore, login: login, issuer: issuer}
|
|
}
|
|
|
|
type loginRequest struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
TOTPCode string `json:"totp_code"`
|
|
}
|
|
|
|
type loginErrorResponse struct {
|
|
// Error ist bewusst IMMER dieselbe generische Meldung fuer falsches
|
|
// Passwort/Token (Akzeptanzkriterium 3 / Pruefung 1) — Code unterscheidet
|
|
// intern zwischen "second_factor_required" (Formular soll TOTP-Feld
|
|
// einblenden) und "invalid_credentials" (alles andere), ohne dem Client
|
|
// mehr ueber den tatsaechlichen Fehlgrund zu verraten.
|
|
Error string `json:"error"`
|
|
Code string `json:"code"`
|
|
}
|
|
|
|
// Login ist der einzige Login-Endpunkt des Frontends (Akzeptanzkriterium 1).
|
|
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
|
if h.ipLimiter != nil {
|
|
if ok, retry := h.ipLimiter.Allow(lockout.ClientIP(r, h.trustForwarded)); !ok {
|
|
lockout.WriteRateLimited(w, retry)
|
|
return
|
|
}
|
|
}
|
|
|
|
var req loginRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if h.lockStore != nil {
|
|
locked, until, err := h.lockStore.IsLocked(r.Context(), req.Email)
|
|
if err != nil {
|
|
http.Error(w, "anmeldung voruebergehend nicht verfuegbar", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
if locked {
|
|
// Gleiche Antwort fuer bestehende und unbekannte Konten: die
|
|
// Sperre haengt an der E-Mail-Adresse, nicht am Konto.
|
|
lockout.WriteRateLimited(w, time.Until(until))
|
|
return
|
|
}
|
|
}
|
|
|
|
token, err := LoginWithTOTP(r.Context(), h.users, h.totp, h.login, req.Email, req.Password, req.TOTPCode)
|
|
if err != nil {
|
|
// Fehlversuch zaehlt bei falschem Passwort/Konto und bei falschem
|
|
// Code; ein fehlender Code nach richtigem Passwort und interne Fehler
|
|
// nicht (mehrstufiger Formularablauf).
|
|
if h.lockStore != nil && (errors.Is(err, auth.ErrInvalidCredentials) || errors.Is(err, ErrSecondFactorInvalid)) {
|
|
if _, _, lerr := h.lockStore.RecordFailure(r.Context(), req.Email); lerr != nil {
|
|
log.Printf("totp: fehlversuch nicht vermerkt: %v", lerr)
|
|
}
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if errors.Is(err, ErrSecondFactorRequired) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_ = json.NewEncoder(w).Encode(loginErrorResponse{
|
|
Error: "Anmeldedaten oder Code ungültig.",
|
|
Code: "second_factor_required",
|
|
})
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_ = json.NewEncoder(w).Encode(loginErrorResponse{
|
|
Error: "Anmeldedaten oder Code ungültig.",
|
|
Code: "invalid_credentials",
|
|
})
|
|
return
|
|
}
|
|
|
|
if h.lockStore != nil {
|
|
if err := h.lockStore.RecordSuccess(r.Context(), req.Email); err != nil {
|
|
log.Printf("totp: erfolg nicht vermerkt: %v", err)
|
|
}
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: auth.CookieName,
|
|
Value: token,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: true,
|
|
SameSite: http.SameSiteStrictMode,
|
|
MaxAge: int(auth.AccessTokenTTL.Seconds()),
|
|
})
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
type statusResponse struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
// Status liefert, ob 2FA fuer den angemeldeten Benutzer aktiv ist — fuer die
|
|
// Profilseite (Akzeptanzkriterium 2: zeigt an, ob Einrichtung schon
|
|
// stattgefunden hat). Muss hinter auth.RequireAuth haengen.
|
|
func (h *Handler) Status(w http.ResponseWriter, r *http.Request) {
|
|
claims, ok := auth.ClaimsFromContext(r.Context())
|
|
if !ok {
|
|
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
enabled, err := h.totp.IsEnabled(r.Context(), claims.UserID)
|
|
if err != nil {
|
|
http.Error(w, "status konnte nicht ermittelt werden", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(statusResponse{Enabled: enabled})
|
|
}
|
|
|
|
type setupBeginResponse struct {
|
|
Secret string `json:"secret"`
|
|
ProvisioningURI string `json:"provisioning_uri"`
|
|
}
|
|
|
|
// SetupBegin startet die 2FA-Einrichtung (Akzeptanzkriterium 2) — muss hinter
|
|
// auth.RequireAuth haengen.
|
|
func (h *Handler) SetupBegin(w http.ResponseWriter, r *http.Request) {
|
|
claims, ok := auth.ClaimsFromContext(r.Context())
|
|
if !ok {
|
|
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
u, err := h.users.Get(r.Context(), claims.UserID)
|
|
if err != nil {
|
|
http.Error(w, "benutzer nicht gefunden", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
secret, uri, err := h.totp.BeginSetup(r.Context(), claims.UserID, h.issuer, u.Email)
|
|
if err != nil {
|
|
http.Error(w, "einrichtung konnte nicht gestartet werden", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(setupBeginResponse{Secret: secret, ProvisioningURI: uri})
|
|
}
|
|
|
|
type setupConfirmRequest struct {
|
|
Code string `json:"code"`
|
|
}
|
|
|
|
type setupConfirmResponse struct {
|
|
RecoveryCodes []string `json:"recovery_codes"`
|
|
}
|
|
|
|
// SetupConfirm bestaetigt die Einrichtung und liefert die Wiederherstellungscodes
|
|
// EINMALIG im Klartext (Akzeptanzkriterium 2) — muss hinter auth.RequireAuth haengen.
|
|
func (h *Handler) SetupConfirm(w http.ResponseWriter, r *http.Request) {
|
|
claims, ok := auth.ClaimsFromContext(r.Context())
|
|
if !ok {
|
|
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
var req setupConfirmRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
codes, err := h.totp.ConfirmSetup(r.Context(), claims.UserID, req.Code)
|
|
if err != nil {
|
|
http.Error(w, "Code ungültig.", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(setupConfirmResponse{RecoveryCodes: codes})
|
|
}
|
|
|
|
type mobileLoginResponse struct {
|
|
Token string `json:"token"`
|
|
ExpiresAt string `json:"expiresAt"`
|
|
}
|
|
|
|
// MobileLogin ist wie Login, gibt das Token aber im JSON-Body zurueck (kein
|
|
// Cookie — native Clients haben keinen Cookie-Speicher) und mit
|
|
// auth.MobileAccessTokenTTL statt auth.AccessTokenTTL (INT-21). Durchlaeuft
|
|
// dieselbe Kontosperre/Rate-Begrenzung und denselben 2FA-Ablauf wie Login.
|
|
func (h *Handler) MobileLogin(w http.ResponseWriter, r *http.Request) {
|
|
if h.ipLimiter != nil {
|
|
if ok, retry := h.ipLimiter.Allow(lockout.ClientIP(r, h.trustForwarded)); !ok {
|
|
lockout.WriteRateLimited(w, retry)
|
|
return
|
|
}
|
|
}
|
|
|
|
var req loginRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if h.lockStore != nil {
|
|
locked, until, err := h.lockStore.IsLocked(r.Context(), req.Email)
|
|
if err != nil {
|
|
http.Error(w, "anmeldung voruebergehend nicht verfuegbar", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
if locked {
|
|
lockout.WriteRateLimited(w, time.Until(until))
|
|
return
|
|
}
|
|
}
|
|
|
|
token, err := LoginWithTOTPTTL(r.Context(), h.users, h.totp, h.login, req.Email, req.Password, req.TOTPCode, auth.MobileAccessTokenTTL)
|
|
if err != nil {
|
|
if h.lockStore != nil && (errors.Is(err, auth.ErrInvalidCredentials) || errors.Is(err, ErrSecondFactorInvalid)) {
|
|
if _, _, lerr := h.lockStore.RecordFailure(r.Context(), req.Email); lerr != nil {
|
|
log.Printf("totp: fehlversuch nicht vermerkt: %v", lerr)
|
|
}
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if errors.Is(err, ErrSecondFactorRequired) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_ = json.NewEncoder(w).Encode(loginErrorResponse{Error: "Anmeldedaten oder Code ungültig.", Code: "second_factor_required"})
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_ = json.NewEncoder(w).Encode(loginErrorResponse{Error: "Anmeldedaten oder Code ungültig.", Code: "invalid_credentials"})
|
|
return
|
|
}
|
|
|
|
if h.lockStore != nil {
|
|
if err := h.lockStore.RecordSuccess(r.Context(), req.Email); err != nil {
|
|
log.Printf("totp: erfolg nicht vermerkt: %v", err)
|
|
}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
_ = json.NewEncoder(w).Encode(mobileLoginResponse{
|
|
Token: token,
|
|
ExpiresAt: time.Now().Add(auth.MobileAccessTokenTTL).UTC().Format(time.RFC3339),
|
|
})
|
|
}
|