Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d63db93a4c |
@@ -1,4 +1,2 @@
|
|||||||
*.log
|
*.log
|
||||||
.env
|
.env
|
||||||
web/*/node_modules/
|
|
||||||
web/*/.next/
|
|
||||||
|
|||||||
@@ -64,9 +64,6 @@ Keine Änderungen ermittelbar.
|
|||||||
## 2026-08-27 17:28 – 17:29 (1m)
|
## 2026-08-27 17:28 – 17:29 (1m)
|
||||||
**Beschreibung:** Claude Code Session
|
**Beschreibung:** Claude Code Session
|
||||||
**Projekt:** code
|
**Projekt:** code
|
||||||
## 2026-08-28 21:44 – 21:44 (0m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** nexarch
|
|
||||||
|
|
||||||
### Commits
|
### Commits
|
||||||
Keine Commits in dieser Session.
|
Keine Commits in dieser Session.
|
||||||
@@ -130,98 +127,5 @@ Keine Commits in dieser Session.
|
|||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||||
- internal/db/db.go | 11 +++++++++++
|
- internal/db/db.go | 11 +++++++++++
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||||
- web/shl/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/__tests__/Dialog.test.tsx | 38 ++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/__tests__/tokens.test.ts | 39 +++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/components/Dialog.tsx | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/components/FormElements.tsx | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/components/Shell.tsx | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/components/Table.tsx | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/components/Toast.tsx | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/i18n/i18n.tsx | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/index.ts | 25 +++++++++++++++++++++++++
|
|
||||||
- web/shl/package.json | 23 +++++++++++++++++++++++
|
|
||||||
- web/shl/theme/ThemeProvider.tsx | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/tokens/tokens.ts | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/shl/tsconfig.json | 18 ++++++++++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-28 21:51 – 21:57 (5m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** nexarch
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
- 3c226da SHL-01: fix — vitest jsdom-environment + jest-dom-Setup (3 Dialog-Tests schlugen ohne DOM fehl)
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- web/shl/package.json | 2 ++
|
|
||||||
- web/shl/vitest.config.ts | 8 ++++++++
|
|
||||||
- web/shl/vitest.setup.ts | 1 +
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-28 23:45 – 23:51 (5m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
- b27a640 CFG-04: benachrichtigungs-einstellungen-oberflaeche (handler+tests fuer notifyprefs, web/notifications next.js-frontend auf shl-01)
|
|
||||||
- 81ff8c1 Merge branch 'feature/shl-01-ui-shell-design-system-zentral' into feature/cfg-04-benachrichtigungs-einstellungen-oberflaeche
|
|
||||||
- 22b3349 Merge branch 'feature/iam-02-login-session-jwt-grundgeruest' into feature/cfg-04-benachrichtigungs-einstellungen-oberflaeche
|
|
||||||
- 2df3f93 CFG-04: backend teil 1 — internal/notifyprefs (praeferenz-store + enqueueifallowed-filter vor dispatcher)
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- internal/notifyprefs/handler.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- internal/notifyprefs/handler_test.go | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- internal/notifyprefs/prefs_test.go | 183 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/layout.tsx | 30 ++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/overview/page.tsx | 43 +++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/page.tsx | 5 +++++
|
|
||||||
- web/notifications/app/settings/page.tsx | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/lib/api.ts | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/next.config.mjs | 5 +++++
|
|
||||||
- web/notifications/package.json | 22 ++++++++++++++++++++++
|
|
||||||
- web/notifications/tsconfig.json | 21 +++++++++++++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-28 23:51 – 23:51 (0m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
Keine Commits in dieser Session.
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- internal/notifyprefs/handler.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- internal/notifyprefs/handler_test.go | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- internal/notifyprefs/prefs_test.go | 183 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/layout.tsx | 30 ++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/overview/page.tsx | 43 +++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/page.tsx | 5 +++++
|
|
||||||
- web/notifications/app/settings/page.tsx | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/lib/api.ts | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/next.config.mjs | 5 +++++
|
|
||||||
- web/notifications/package.json | 22 ++++++++++++++++++++++
|
|
||||||
- web/notifications/tsconfig.json | 21 +++++++++++++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-28 23:52 – 23:52 (0m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
Keine Commits in dieser Session.
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- internal/notifyprefs/handler.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- internal/notifyprefs/handler_test.go | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- internal/notifyprefs/prefs_test.go | 183 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/layout.tsx | 30 ++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/overview/page.tsx | 43 +++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/app/page.tsx | 5 +++++
|
|
||||||
- web/notifications/app/settings/page.tsx | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/lib/api.ts | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- web/notifications/next.config.mjs | 5 +++++
|
|
||||||
- web/notifications/package.json | 22 ++++++++++++++++++++++
|
|
||||||
- web/notifications/tsconfig.json | 21 +++++++++++++++++++++
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+1
-10
@@ -8,7 +8,6 @@ import (
|
|||||||
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/tenant"
|
"gitea.perlbach24.de/scripte/nexarch/internal/tenant"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -35,20 +34,12 @@ func main() {
|
|||||||
provisioner := tenant.NewProvisioner(adminPool, registry, cfg.TenantDSNTemplate)
|
provisioner := tenant.NewProvisioner(adminPool, registry, cfg.TenantDSNTemplate)
|
||||||
tenantHandler := tenant.NewHandler(provisioner)
|
tenantHandler := tenant.NewHandler(provisioner)
|
||||||
|
|
||||||
// Superadmin-Konten leben mandantenuebergreifend in der Registry-DB.
|
|
||||||
// Tenant-User-CRUD (user.TenantUserStore) braucht Connection-Routing pro
|
|
||||||
// Mandant (TEN-06, noch nicht gebaut) und wird hier bewusst noch nicht
|
|
||||||
// verdrahtet — Package ist bereits eigenstaendig nutzbar/testbar.
|
|
||||||
superadmins := user.NewSuperadminStore(registryPool)
|
|
||||||
userHandler := user.NewHandler(nil, superadmins)
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
})
|
})
|
||||||
// Vorlaeufige Pfade ohne Versionierung/Auth — werden mit API-01/IAM-02 abgeloest.
|
// Vorlaeufiger Pfad ohne Versionierung/Auth — wird mit API-01/IAM-01 abgeloest.
|
||||||
mux.HandleFunc("/internal/tenants", tenantHandler.CreateTenant)
|
mux.HandleFunc("/internal/tenants", tenantHandler.CreateTenant)
|
||||||
mux.HandleFunc("/internal/superadmins", userHandler.CreateSuperadmin)
|
|
||||||
|
|
||||||
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
||||||
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
||||||
|
|||||||
@@ -2,16 +2,13 @@ module gitea.perlbach24.de/scripte/nexarch
|
|||||||
|
|
||||||
go 1.22
|
go 1.22
|
||||||
|
|
||||||
require (
|
require github.com/jackc/pgx/v5 v5.6.0
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
|
||||||
github.com/jackc/pgx/v5 v5.6.0
|
|
||||||
golang.org/x/crypto v0.17.0
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||||
|
golang.org/x/crypto v0.17.0 // indirect
|
||||||
golang.org/x/sync v0.1.0 // indirect
|
golang.org/x/sync v0.1.0 // indirect
|
||||||
golang.org/x/text v0.14.0 // indirect
|
golang.org/x/text v0.14.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler stellt Login/Logout als HTTP-Endpunkte bereit. Registrierung,
|
|
||||||
// Passwort-Reset, 2FA, SSO/LDAP und Rate-Limiting sind ausdruecklich nicht
|
|
||||||
// Teil dieser Kachel (siehe IAM-03..07).
|
|
||||||
type Handler struct {
|
|
||||||
login *LoginService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(login *LoginService) *Handler {
|
|
||||||
return &Handler{login: login}
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginRequest struct {
|
|
||||||
Email string `json:"email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req loginRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
token, err := h.login.Login(r.Context(), req.Email, req.Password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, ErrInvalidCredentials.Error(), http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: CookieName,
|
|
||||||
Value: token,
|
|
||||||
Path: "/",
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: true,
|
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
MaxAge: int(AccessTokenTTL.Seconds()),
|
|
||||||
})
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logout loescht das Session-Cookie. Da JWT hier bewusst zustandslos bleibt
|
|
||||||
// (kein serverseitiger Blocklist-Speicher — das waere ueber "Grundgerüst"
|
|
||||||
// hinaus und widerspraeche der projektweiten zustandslosen-JWT-Entscheidung),
|
|
||||||
// bleibt ein bereits ausgestelltes Token bis zu seinem Ablauf technisch
|
|
||||||
// gueltig, wenn es separat vom Cookie extrahiert und wiederverwendet wird.
|
|
||||||
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: CookieName,
|
|
||||||
Value: "",
|
|
||||||
Path: "/",
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: true,
|
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
MaxAge: -1,
|
|
||||||
Expires: time.Unix(0, 0),
|
|
||||||
})
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ErrInvalidCredentials = errors.New("auth: E-Mail oder Passwort falsch")
|
|
||||||
|
|
||||||
// LoginService arbeitet gegen GENAU EINE Tenant-Datenbank (uebergeben ueber
|
|
||||||
// den TenantUserStore-Pool) — das Login ist damit strukturell auf den
|
|
||||||
// richtigen Tenant gescopt, siehe user.TenantUserStore.GetByEmailForAuth.
|
|
||||||
type LoginService struct {
|
|
||||||
users *user.TenantUserStore
|
|
||||||
issuer *TokenIssuer
|
|
||||||
// tenantSlug identifiziert im ausgestellten Token, gegen welchen Mandanten
|
|
||||||
// eingeloggt wurde (fuer nachgelagerte Pruefungen, z.B. Middleware-Logs).
|
|
||||||
tenantSlug string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLoginService(users *user.TenantUserStore, issuer *TokenIssuer, tenantSlug string) *LoginService {
|
|
||||||
return &LoginService{users: users, issuer: issuer, tenantSlug: tenantSlug}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login liefert bei falscher E-Mail UND bei falschem Passwort denselben
|
|
||||||
// Fehler (ErrInvalidCredentials), um keine Rueckschluesse auf die Existenz
|
|
||||||
// eines Kontos zuzulassen (User-Enumeration-Schutz).
|
|
||||||
func (s *LoginService) Login(ctx context.Context, email, password string) (string, error) {
|
|
||||||
creds, err := s.users.GetByEmailForAuth(ctx, email)
|
|
||||||
if err != nil {
|
|
||||||
// Trotzdem einen bcrypt-Vergleich gegen einen Dummy-Hash ausfuehren,
|
|
||||||
// damit die Antwortzeit bei unbekannter E-Mail nicht messbar kuerzer
|
|
||||||
// ist als bei falschem Passwort (Timing-Seitenkanal).
|
|
||||||
VerifyPassword(dummyHash, password)
|
|
||||||
return "", ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
|
|
||||||
if creds.User.Status != user.StatusActive {
|
|
||||||
return "", ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
|
|
||||||
if !VerifyPassword(creds.PasswordHash, password) {
|
|
||||||
return "", ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.issuer.Issue(creds.User.ID, s.tenantSlug)
|
|
||||||
}
|
|
||||||
|
|
||||||
// dummyHash ist ein echter bcrypt-Hash (Kostenfaktor BcryptCost) eines
|
|
||||||
// beliebigen Platzhalter-Klartexts — bewusst KEIN kaputtes Format, da
|
|
||||||
// bcrypt.CompareHashAndPassword bei ungueltigem Hash sofort ohne den
|
|
||||||
// eigentlichen Kostenfaktor-Vergleich zurueckkehrt und die
|
|
||||||
// Timing-Angleichung damit wirkungslos waere.
|
|
||||||
const dummyHash = "$2a$12$cmwiETrG9DK5/uTM2fg4uetngYUspKjME5P8fNpk0QYTaO64N0r3C"
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
const usersSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
password_hash TEXT NOT NULL DEFAULT '',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
func setupTenantDB(t *testing.T, dbName string) *pgxpool.Pool {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("admin pool: %v", err)
|
|
||||||
}
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
if _, err := adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
|
||||||
t.Fatalf("testdatenbank anlegen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dsn := strings.Replace(adminDSN, "/postgres?", "/"+dbName+"?", 1)
|
|
||||||
pool, err := pgxpool.New(ctx, dsn)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("connect testdatenbank: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, usersSchema); err != nil {
|
|
||||||
t.Fatalf("schema anwenden: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
pool.Close()
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
adminPool.Close()
|
|
||||||
})
|
|
||||||
return pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func createUserWithPassword(t *testing.T, store *user.TenantUserStore, email, password string) user.User {
|
|
||||||
t.Helper()
|
|
||||||
ctx := context.Background()
|
|
||||||
u, err := store.Create(ctx, email, "Test User")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create user: %v", err)
|
|
||||||
}
|
|
||||||
hash, err := HashPassword(password)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash password: %v", err)
|
|
||||||
}
|
|
||||||
if err := store.SetPasswordHash(ctx, u.ID, hash); err != nil {
|
|
||||||
t.Fatalf("set password: %v", err)
|
|
||||||
}
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoginService_SuccessAndWrongPassword(t *testing.T) {
|
|
||||||
pool := setupTenantDB(t, "test_iam02_login")
|
|
||||||
store := user.NewTenantUserStore(pool)
|
|
||||||
createUserWithPassword(t, store, "alice@example.com", "korrektes-passwort")
|
|
||||||
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
login := NewLoginService(store, issuer, "acme")
|
|
||||||
|
|
||||||
token, err := login.Login(context.Background(), "alice@example.com", "korrektes-passwort")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("login: %v", err)
|
|
||||||
}
|
|
||||||
if token == "" {
|
|
||||||
t.Fatal("erwartet nicht-leeres token")
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := login.Login(context.Background(), "alice@example.com", "falsches-passwort"); !errors.Is(err, ErrInvalidCredentials) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidCredentials, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := login.Login(context.Background(), "unbekannt@example.com", "irgendwas"); !errors.Is(err, ErrInvalidCredentials) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidCredentials bei unbekannter email, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 1: kein Cross-Tenant-Login moeglich, obwohl dieselbe E-Mail in
|
|
||||||
// zwei unterschiedlichen Tenant-Datenbanken mit unterschiedlichen Passwoertern
|
|
||||||
// existiert.
|
|
||||||
func TestLoginService_NoCrossTenantLogin(t *testing.T) {
|
|
||||||
poolA := setupTenantDB(t, "test_iam02_tenant_a")
|
|
||||||
poolB := setupTenantDB(t, "test_iam02_tenant_b")
|
|
||||||
|
|
||||||
storeA := user.NewTenantUserStore(poolA)
|
|
||||||
storeB := user.NewTenantUserStore(poolB)
|
|
||||||
createUserWithPassword(t, storeA, "shared@example.com", "passwort-tenant-a")
|
|
||||||
createUserWithPassword(t, storeB, "shared@example.com", "passwort-tenant-b")
|
|
||||||
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
loginA := NewLoginService(storeA, issuer, "tenant-a")
|
|
||||||
|
|
||||||
// Login gegen Tenant A mit dem Passwort von Tenant B darf nicht klappen,
|
|
||||||
// obwohl die E-Mail-Adresse identisch ist — die Store-Instanz kennt
|
|
||||||
// strukturell nur die Zeilen ihrer eigenen Datenbank.
|
|
||||||
if _, err := loginA.Login(context.Background(), "shared@example.com", "passwort-tenant-b"); !errors.Is(err, ErrInvalidCredentials) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidCredentials fuer fremdes tenant-passwort, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
token, err := loginA.Login(context.Background(), "shared@example.com", "passwort-tenant-a")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("login gegen eigenen tenant sollte klappen: %v", err)
|
|
||||||
}
|
|
||||||
claims, err := issuer.Verify(token)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("verify: %v", err)
|
|
||||||
}
|
|
||||||
if claims.TenantSlug != "tenant-a" {
|
|
||||||
t.Fatalf("token tenant = %q, want tenant-a", claims.TenantSlug)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: geschuetzte Route ohne gueltige Session nicht erreichbar.
|
|
||||||
func TestRequireAuth_BlocksWithoutValidCookie(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
protected := RequireAuth(issuer, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Kein Cookie.
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/geschuetzt", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
protected(rec, req)
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("ohne cookie: status = %d, want 401", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Manipuliertes Cookie.
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/geschuetzt", nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: CookieName, Value: "kaputt.token.hier"})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
protected(rec, req)
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("mit kaputtem cookie: status = %d, want 401", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gueltiges Token.
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/geschuetzt", nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: CookieName, Value: token})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
protected(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("mit gueltigem cookie: status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
const CookieName = "nexarch_session"
|
|
||||||
|
|
||||||
type contextKey int
|
|
||||||
|
|
||||||
const claimsContextKey contextKey = iota
|
|
||||||
|
|
||||||
// RequireAuth schuetzt eine Route: ohne gueltiges, nicht abgelaufenes Token
|
|
||||||
// im Session-Cookie wird 401 zurueckgegeben und der Handler nicht aufgerufen
|
|
||||||
// (IAM-02 Akzeptanzkriterium 3).
|
|
||||||
func RequireAuth(issuer *TokenIssuer, next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
cookie, err := r.Cookie(CookieName)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := issuer.Verify(cookie.Value)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.WithValue(r.Context(), claimsContextKey, claims)
|
|
||||||
next(w, r.WithContext(ctx))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClaimsFromContext liest die Claims, die RequireAuth in den Request-Context
|
|
||||||
// gelegt hat.
|
|
||||||
func ClaimsFromContext(ctx context.Context) (*Claims, bool) {
|
|
||||||
c, ok := ctx.Value(claimsContextKey).(*Claims)
|
|
||||||
return c, ok
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
// Package auth implementiert Core IAM-02: Login/Logout, Passwort-Hashing und
|
|
||||||
// die Middleware zum Schutz von Routen. Autorisierung (was ein Benutzer darf)
|
|
||||||
// ist ausdruecklich NICHT Teil dieses Pakets, siehe RBAC-01 — auth prueft nur
|
|
||||||
// "wer bin ich" (Casbin-Architekturprinzip, siehe IAM-02-Ticket).
|
|
||||||
package auth
|
|
||||||
|
|
||||||
import "golang.org/x/crypto/bcrypt"
|
|
||||||
|
|
||||||
// BcryptCost ist bewusst explizit festgelegt statt bcrypt.DefaultCost (10)
|
|
||||||
// unreflektiert zu uebernehmen (IAM-02 Akzeptanzkriterium 4). Kostenfaktor 12
|
|
||||||
// wurde gegen die Ziel-Login-Latenz benchmarkt, siehe password_bench_test.go
|
|
||||||
// und den Pruefungs-Eintrag in der Commit-Nachricht.
|
|
||||||
const BcryptCost = 12
|
|
||||||
|
|
||||||
func HashPassword(plain string) (string, error) {
|
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(plain), BcryptCost)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return string(hash), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// VerifyPassword ist timing-safe: bcrypt.CompareHashAndPassword vergleicht
|
|
||||||
// konstant in der Zeit bzgl. des Hash-Inhalts (Referenzimplementierung fuer
|
|
||||||
// die projektweite Timing-safe-Vergleich-Konvention aus IAM-02).
|
|
||||||
func VerifyPassword(hash, plain string) bool {
|
|
||||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TargetLoginLatency ist der Zielwert aus IAM-02 Akzeptanzkriterium 4: der
|
|
||||||
// bcrypt-Vergleich allein darf die Login-Latenz nicht dominieren. 400ms ist
|
|
||||||
// grosszuegig genug, um auf unterschiedlicher Hardware stabil zu sein, aber
|
|
||||||
// eng genug, um eine versehentliche Kostenfaktor-Explosion (z.B. 16 statt 12)
|
|
||||||
// zuverlaessig aufzudecken.
|
|
||||||
const TargetLoginLatency = 400 * time.Millisecond
|
|
||||||
|
|
||||||
// TestBcryptCostAgainstLatencyTarget misst die tatsaechliche Dauer eines
|
|
||||||
// Passwort-Vergleichs mit dem festgelegten BcryptCost und dokumentiert das
|
|
||||||
// Ergebnis (IAM-02 Pruefung 4).
|
|
||||||
func TestBcryptCostAgainstLatencyTarget(t *testing.T) {
|
|
||||||
hash, err := HashPassword("benchmark-passwort")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
|
||||||
if !VerifyPassword(hash, "benchmark-passwort") {
|
|
||||||
t.Fatal("verifikation haette erfolgreich sein muessen")
|
|
||||||
}
|
|
||||||
elapsed := time.Since(start)
|
|
||||||
|
|
||||||
t.Logf("bcrypt-vergleich mit cost=%d dauerte %s (ziel: unter %s)", BcryptCost, elapsed, TargetLoginLatency)
|
|
||||||
if elapsed > TargetLoginLatency {
|
|
||||||
t.Fatalf("bcrypt-vergleich zu langsam: %s > ziel %s", elapsed, TargetLoginLatency)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkVerifyPassword(b *testing.B) {
|
|
||||||
hash, _ := HashPassword("benchmark-passwort")
|
|
||||||
b.ResetTimer()
|
|
||||||
for i := 0; i < b.N; i++ {
|
|
||||||
VerifyPassword(hash, "benchmark-passwort")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestHashAndVerifyPassword(t *testing.T) {
|
|
||||||
hash, err := HashPassword("s3hr-geheim!")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash: %v", err)
|
|
||||||
}
|
|
||||||
if hash == "s3hr-geheim!" {
|
|
||||||
t.Fatal("passwort wurde nicht gehasht")
|
|
||||||
}
|
|
||||||
if !VerifyPassword(hash, "s3hr-geheim!") {
|
|
||||||
t.Fatal("erwartet erfolgreiche verifikation")
|
|
||||||
}
|
|
||||||
if VerifyPassword(hash, "falsches-passwort") {
|
|
||||||
t.Fatal("erwartet fehlgeschlagene verifikation")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDummyHashIsValidBcryptHash(t *testing.T) {
|
|
||||||
// Stellt sicher, dass der Timing-Angleichs-Hash in login.go tatsaechlich
|
|
||||||
// ein gueltiges bcrypt-Format hat und den vollen Kostenfaktor durchlaeuft
|
|
||||||
// (siehe Kommentar dort) statt sofort mit einem Format-Fehler abzubrechen.
|
|
||||||
if VerifyPassword(dummyHash, "irgendein-text") {
|
|
||||||
t.Fatal("dummyHash sollte fuer beliebigen text nicht passen")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// AccessTokenTTL ist bewusst kurz gehalten (Session-Ablauf statt langlebiger
|
|
||||||
// Tokens), passend zur "so vertrauenswuerdig wie noetig"-Produkt-DNA.
|
|
||||||
const AccessTokenTTL = 30 * time.Minute
|
|
||||||
|
|
||||||
var ErrInvalidToken = errors.New("auth: ungueltiges oder abgelaufenes token")
|
|
||||||
|
|
||||||
type Claims struct {
|
|
||||||
UserID string `json:"uid"`
|
|
||||||
TenantSlug string `json:"tenant"`
|
|
||||||
jwt.RegisteredClaims
|
|
||||||
}
|
|
||||||
|
|
||||||
// TokenIssuer signiert/verifiziert JWTs mit einem HMAC-Secret. Das
|
|
||||||
// asymmetrische Core-weite Signaturschema (API-05, kid-Rotation) ist
|
|
||||||
// ausdruecklich nicht Teil dieser Kachel — hier geht es nur um das
|
|
||||||
// Login-Grundgerüst innerhalb eines einzelnen Core-Prozesses.
|
|
||||||
type TokenIssuer struct {
|
|
||||||
secret []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTokenIssuer(secret string) *TokenIssuer {
|
|
||||||
return &TokenIssuer{secret: []byte(secret)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *TokenIssuer) Issue(userID, tenantSlug string) (string, error) {
|
|
||||||
now := time.Now()
|
|
||||||
claims := Claims{
|
|
||||||
UserID: userID,
|
|
||||||
TenantSlug: tenantSlug,
|
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
|
||||||
IssuedAt: jwt.NewNumericDate(now),
|
|
||||||
ExpiresAt: jwt.NewNumericDate(now.Add(AccessTokenTTL)),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
return token.SignedString(i.secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify prueft Signatur UND Ablauf (jwt.ParseWithClaims lehnt abgelaufene
|
|
||||||
// Tokens automatisch ab) — der Signaturvergleich in golang-jwt ist
|
|
||||||
// timing-safe (hmac.Equal).
|
|
||||||
func (i *TokenIssuer) Verify(tokenString string) (*Claims, error) {
|
|
||||||
claims := &Claims{}
|
|
||||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
|
||||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
||||||
return nil, ErrInvalidToken
|
|
||||||
}
|
|
||||||
return i.secret, nil
|
|
||||||
})
|
|
||||||
if err != nil || !token.Valid {
|
|
||||||
return nil, ErrInvalidToken
|
|
||||||
}
|
|
||||||
return claims, nil
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestTokenIssueAndVerify(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := issuer.Verify(token)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("verify: %v", err)
|
|
||||||
}
|
|
||||||
if claims.UserID != "user-1" || claims.TenantSlug != "acme" {
|
|
||||||
t.Fatalf("claims unerwartet: %+v", claims)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 2: Token-Manipulationstest.
|
|
||||||
func TestTokenVerify_RejectsManipulatedPayload(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(token, ".")
|
|
||||||
if len(parts) != 3 {
|
|
||||||
t.Fatalf("unerwartetes token-format: %d teile", len(parts))
|
|
||||||
}
|
|
||||||
// Payload-Segment leicht veraendern (Signatur passt danach nicht mehr).
|
|
||||||
tampered := parts[0] + "." + parts[1] + "x" + "." + parts[2]
|
|
||||||
|
|
||||||
if _, err := issuer.Verify(tampered); err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei manipuliertem token, habe nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTokenVerify_RejectsWrongSecret(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("secret-a")
|
|
||||||
other := NewTokenIssuer("secret-b")
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := other.Verify(token); err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei falschem secret, habe nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 3: abgelaufenes Token erzwingt Neuanmeldung.
|
|
||||||
func TestTokenVerify_RejectsExpiredToken(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
|
|
||||||
claims := Claims{
|
|
||||||
UserID: "user-1",
|
|
||||||
TenantSlug: "acme",
|
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
|
||||||
IssuedAt: jwt.NewNumericDate(time.Now().Add(-2 * AccessTokenTTL)),
|
|
||||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
expired, err := tok.SignedString([]byte("test-secret-nur-fuer-tests"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("signieren: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := issuer.Verify(expired); err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei abgelaufenem token, habe nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
package cfgservice
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultCacheTTL ist die dokumentierte Cache-Invalidierungszeit
|
|
||||||
// (Akzeptanzkriterium 2 / Pruefung 2 in diesem Ticket bezieht sich auf die
|
|
||||||
// Aenderungsnachvollziehbarkeit — die Cache-Frist selbst folgt demselben
|
|
||||||
// Muster wie internal/flag.DefaultCacheTTL).
|
|
||||||
const DefaultCacheTTL = 5 * time.Second
|
|
||||||
|
|
||||||
type cacheEntry struct {
|
|
||||||
value Value
|
|
||||||
expiresAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// Service ist die Leseseite mit Vorrangregel (Akzeptanzkriterium 1:
|
|
||||||
// Tenant-Override vor Global-Default) und lokalem TTL-Cache.
|
|
||||||
type Service struct {
|
|
||||||
store *Store
|
|
||||||
ttl time.Duration
|
|
||||||
|
|
||||||
mu sync.RWMutex
|
|
||||||
cache map[string]cacheEntry // Schluessel: key + "\x00" + tenantSlug
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewService(store *Store, ttl time.Duration) *Service {
|
|
||||||
if ttl <= 0 {
|
|
||||||
ttl = DefaultCacheTTL
|
|
||||||
}
|
|
||||||
return &Service{store: store, ttl: ttl, cache: make(map[string]cacheEntry)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func cacheKey(key, tenantSlug string) string {
|
|
||||||
return key + "\x00" + tenantSlug
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve liefert den Konfigurationswert fuer einen Tenant: ein
|
|
||||||
// Tenant-spezifischer Override hat Vorrang vor dem globalen Default
|
|
||||||
// (Akzeptanzkriterium 1 / Pruefung 1). tenantSlug == "" wertet nur den
|
|
||||||
// globalen Wert aus.
|
|
||||||
func (s *Service) Resolve(ctx context.Context, tenantSlug, key string) (Value, error) {
|
|
||||||
ck := cacheKey(key, tenantSlug)
|
|
||||||
|
|
||||||
s.mu.RLock()
|
|
||||||
entry, exists := s.cache[ck]
|
|
||||||
fresh := exists && time.Now().Before(entry.expiresAt)
|
|
||||||
s.mu.RUnlock()
|
|
||||||
if fresh {
|
|
||||||
return entry.value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
v, err := s.resolveUncached(ctx, tenantSlug, key)
|
|
||||||
if err != nil {
|
|
||||||
return Value{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
s.mu.Lock()
|
|
||||||
s.cache[ck] = cacheEntry{value: v, expiresAt: time.Now().Add(s.ttl)}
|
|
||||||
s.mu.Unlock()
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) resolveUncached(ctx context.Context, tenantSlug, key string) (Value, error) {
|
|
||||||
if tenantSlug != "" {
|
|
||||||
v, err := s.store.Get(ctx, key, tenantSlug)
|
|
||||||
if err == nil {
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
if !errors.Is(err, ErrNotFound) {
|
|
||||||
return Value{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s.store.Get(ctx, key, GlobalScope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalidate erzwingt beim naechsten Resolve-Aufruf ein sofortiges Neuladen
|
|
||||||
// fuer einen bestimmten (key, tenantSlug) statt auf den TTL-Ablauf zu warten
|
|
||||||
// — analog internal/flag.Service.Invalidate.
|
|
||||||
func (s *Service) Invalidate(key, tenantSlug string) {
|
|
||||||
s.mu.Lock()
|
|
||||||
delete(s.cache, cacheKey(key, tenantSlug))
|
|
||||||
s.mu.Unlock()
|
|
||||||
}
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
package cfgservice
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 1: Tenant-Override hat Vorrang vor
|
|
||||||
// Global-Default, automatisiert getestet.
|
|
||||||
func TestService_TenantOverrideTakesPrecedenceOverGlobal(t *testing.T) {
|
|
||||||
store, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if _, err := store.Set(ctx, "test_precedence_key", GlobalScope, "global-wert"); err != nil {
|
|
||||||
t.Fatalf("set global: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := store.Set(ctx, "test_precedence_key", "test_acme", "tenant-wert"); err != nil {
|
|
||||||
t.Fatalf("set tenant: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := NewService(store, time.Hour)
|
|
||||||
|
|
||||||
got, err := svc.Resolve(ctx, "test_acme", "test_precedence_key")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve mit override: %v", err)
|
|
||||||
}
|
|
||||||
if got.Value != "tenant-wert" {
|
|
||||||
t.Fatalf("erwartet tenant-override, habe %q", got.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
gotOther, err := svc.Resolve(ctx, "test_anderer_tenant", "test_precedence_key")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve ohne override: %v", err)
|
|
||||||
}
|
|
||||||
if gotOther.Value != "global-wert" {
|
|
||||||
t.Fatalf("erwartet global-default fuer tenant ohne override, habe %q", gotOther.Value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: Cache-Invalidierung nach
|
|
||||||
// Konfigurationsaenderung innerhalb dokumentierter Zeit gemessen.
|
|
||||||
func TestService_CacheInvalidationTiming(t *testing.T) {
|
|
||||||
store, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
const ttl = 150 * time.Millisecond
|
|
||||||
if _, err := store.Set(ctx, "test_ttl_key", GlobalScope, "alt"); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc := NewService(store, ttl)
|
|
||||||
|
|
||||||
v, err := svc.Resolve(ctx, "", "test_ttl_key")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve: %v", err)
|
|
||||||
}
|
|
||||||
if v.Value != "alt" {
|
|
||||||
t.Fatalf("erwartet 'alt', habe %q", v.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
changedAt := time.Now()
|
|
||||||
if _, err := store.Set(ctx, "test_ttl_key", GlobalScope, "neu"); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
v, err = svc.Resolve(ctx, "", "test_ttl_key")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve direkt nach aenderung: %v", err)
|
|
||||||
}
|
|
||||||
if v.Value != "alt" {
|
|
||||||
t.Fatalf("cache haette den alten wert liefern sollen, habe %q", v.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
deadline := changedAt.Add(ttl + 100*time.Millisecond)
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
v, err := svc.Resolve(ctx, "", "test_ttl_key")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve: %v", err)
|
|
||||||
}
|
|
||||||
if v.Value == "neu" {
|
|
||||||
t.Logf("aenderung wurde nach %s wirksam (ziel: innerhalb %s + toleranz)", time.Since(changedAt), ttl)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
time.Sleep(10 * time.Millisecond)
|
|
||||||
}
|
|
||||||
t.Fatalf("aenderung wurde nicht innerhalb von %s wirksam", deadline.Sub(changedAt))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestService_InvalidateForcesImmediateRefresh(t *testing.T) {
|
|
||||||
store, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if _, err := store.Set(ctx, "test_invalidate_key", GlobalScope, "alt"); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc := NewService(store, time.Hour)
|
|
||||||
_, _ = svc.Resolve(ctx, "", "test_invalidate_key")
|
|
||||||
|
|
||||||
if _, err := store.Set(ctx, "test_invalidate_key", GlobalScope, "neu"); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc.Invalidate("test_invalidate_key", "")
|
|
||||||
|
|
||||||
v, err := svc.Resolve(ctx, "", "test_invalidate_key")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve: %v", err)
|
|
||||||
}
|
|
||||||
if v.Value != "neu" {
|
|
||||||
t.Fatalf("erwartet sofort sichtbaren neuen wert nach Invalidate, habe %q", v.Value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
// Package cfgservice implementiert Core CFG-01: den zentralen Dienst fuer
|
|
||||||
// globale und tenant-spezifische Konfigurationswerte mit Versionierung und
|
|
||||||
// Cache-Invalidierung. Andere Module lesen Konfiguration AUSSCHLIESSLICH
|
|
||||||
// ueber dieses Paket (Akzeptanzkriterium 3), niemals ueber eigene Tabellen.
|
|
||||||
package cfgservice
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// GlobalScope ist der reservierte Scope-Wert fuer globale Defaults — jeder
|
|
||||||
// andere Scope-Wert ist ein Tenant-Slug (Akzeptanzkriterium 1).
|
|
||||||
const GlobalScope = "global"
|
|
||||||
|
|
||||||
var ErrNotFound = errors.New("cfgservice: kein wert fuer diesen key gefunden")
|
|
||||||
|
|
||||||
type Value struct {
|
|
||||||
Key string
|
|
||||||
Scope string
|
|
||||||
Value string
|
|
||||||
Version int
|
|
||||||
}
|
|
||||||
|
|
||||||
type HistoryEntry struct {
|
|
||||||
Key string
|
|
||||||
Scope string
|
|
||||||
Value string
|
|
||||||
Version int
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store ist die Schreib-/Verwaltungsseite. Set schreibt IMMER sowohl den
|
|
||||||
// aktuellen Stand (config_values) als auch einen Historieneintrag
|
|
||||||
// (config_value_history) in derselben Transaktion — eine Aenderung ohne
|
|
||||||
// Versionshistorie ist strukturell ausgeschlossen (Akzeptanzkriterium 2).
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool) *Store {
|
|
||||||
return &Store{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set schreibt einen neuen Wert fuer (key, scope) und erhoeht die Version um 1
|
|
||||||
// (Version 1 bei erstmaligem Setzen).
|
|
||||||
func (s *Store) Set(ctx context.Context, key, scope, value string) (Value, error) {
|
|
||||||
if scope == "" {
|
|
||||||
return Value{}, errors.New("cfgservice: scope darf nicht leer sein")
|
|
||||||
}
|
|
||||||
|
|
||||||
tx, err := s.pool.Begin(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return Value{}, fmt.Errorf("transaktion starten: %w", err)
|
|
||||||
}
|
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
|
||||||
|
|
||||||
var currentVersion int
|
|
||||||
err = tx.QueryRow(ctx, `SELECT version FROM config_values WHERE key = $1 AND scope = $2`, key, scope).Scan(¤tVersion)
|
|
||||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return Value{}, fmt.Errorf("aktuelle version lesen: %w", err)
|
|
||||||
}
|
|
||||||
newVersion := currentVersion + 1
|
|
||||||
|
|
||||||
if _, err := tx.Exec(ctx, `
|
|
||||||
INSERT INTO config_values (key, scope, value, version, updated_at)
|
|
||||||
VALUES ($1, $2, $3, $4, now())
|
|
||||||
ON CONFLICT (key, scope) DO UPDATE SET value = $3, version = $4, updated_at = now()
|
|
||||||
`, key, scope, value, newVersion); err != nil {
|
|
||||||
return Value{}, fmt.Errorf("wert speichern: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := tx.Exec(ctx, `
|
|
||||||
INSERT INTO config_value_history (key, scope, value, version, changed_at)
|
|
||||||
VALUES ($1, $2, $3, $4, now())
|
|
||||||
`, key, scope, value, newVersion); err != nil {
|
|
||||||
return Value{}, fmt.Errorf("historie schreiben: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return Value{}, fmt.Errorf("transaktion committen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return Value{Key: key, Scope: scope, Value: value, Version: newVersion}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get liefert den Wert fuer GENAU EINEN Scope (kein Vorrang-Fallback) — die
|
|
||||||
// Vorrangregel (Tenant vor Global) lebt bewusst in Service.Resolve, damit
|
|
||||||
// Store rein CRUD bleibt.
|
|
||||||
func (s *Store) Get(ctx context.Context, key, scope string) (Value, error) {
|
|
||||||
var v Value
|
|
||||||
v.Key, v.Scope = key, scope
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT value, version FROM config_values WHERE key = $1 AND scope = $2
|
|
||||||
`, key, scope).Scan(&v.Value, &v.Version)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return Value{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return Value{}, fmt.Errorf("wert lesen: %w", err)
|
|
||||||
}
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// History liefert die vollstaendige Versionshistorie eines (key, scope) in
|
|
||||||
// aufsteigender Reihenfolge (Akzeptanzkriterium 2 / Pruefung 3).
|
|
||||||
func (s *Store) History(ctx context.Context, key, scope string) ([]HistoryEntry, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT key, scope, value, version FROM config_value_history
|
|
||||||
WHERE key = $1 AND scope = $2 ORDER BY version
|
|
||||||
`, key, scope)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("historie abfragen: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []HistoryEntry
|
|
||||||
for rows.Next() {
|
|
||||||
var h HistoryEntry
|
|
||||||
if err := rows.Scan(&h.Key, &h.Scope, &h.Value, &h.Version); err != nil {
|
|
||||||
return nil, fmt.Errorf("historieneintrag lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, h)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
package cfgservice
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupStoreTest(t *testing.T) (*Store, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS config_values (
|
|
||||||
key TEXT NOT NULL,
|
|
||||||
scope TEXT NOT NULL CHECK (scope <> ''),
|
|
||||||
value TEXT NOT NULL,
|
|
||||||
version INT NOT NULL,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (key, scope)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS config_value_history (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
key TEXT NOT NULL,
|
|
||||||
scope TEXT NOT NULL,
|
|
||||||
value TEXT NOT NULL,
|
|
||||||
version INT NOT NULL,
|
|
||||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() {
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM config_value_history WHERE key LIKE 'test\_%' ESCAPE '\'`)
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM config_values WHERE key LIKE 'test\_%' ESCAPE '\'`)
|
|
||||||
pool.Close()
|
|
||||||
}
|
|
||||||
return NewStore(pool), cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStore_SetIncrementsVersion(t *testing.T) {
|
|
||||||
store, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
v1, err := store.Set(ctx, "test_key", GlobalScope, "erster-wert")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("set 1: %v", err)
|
|
||||||
}
|
|
||||||
if v1.Version != 1 {
|
|
||||||
t.Fatalf("erwartet version 1, habe %d", v1.Version)
|
|
||||||
}
|
|
||||||
|
|
||||||
v2, err := store.Set(ctx, "test_key", GlobalScope, "zweiter-wert")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("set 2: %v", err)
|
|
||||||
}
|
|
||||||
if v2.Version != 2 {
|
|
||||||
t.Fatalf("erwartet version 2, habe %d", v2.Version)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, "test_key", GlobalScope)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Value != "zweiter-wert" || got.Version != 2 {
|
|
||||||
t.Fatalf("aktueller wert unerwartet: %+v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 3: Versionierungshistorie ueber mehrere
|
|
||||||
// Aenderungen hinweg nachvollzogen.
|
|
||||||
func TestStore_HistoryTracksAllChanges(t *testing.T) {
|
|
||||||
store, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
values := []string{"v1", "v2", "v3"}
|
|
||||||
for _, v := range values {
|
|
||||||
if _, err := store.Set(ctx, "test_history_key", GlobalScope, v); err != nil {
|
|
||||||
t.Fatalf("set %q: %v", v, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
history, err := store.History(ctx, "test_history_key", GlobalScope)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("history: %v", err)
|
|
||||||
}
|
|
||||||
if len(history) != 3 {
|
|
||||||
t.Fatalf("erwartet 3 historieneintraege, habe %d", len(history))
|
|
||||||
}
|
|
||||||
for i, h := range history {
|
|
||||||
if h.Version != i+1 || h.Value != values[i] {
|
|
||||||
t.Fatalf("historieneintrag[%d] unerwartet: %+v", i, h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStore_GetUnknownKeyReturnsNotFound(t *testing.T) {
|
|
||||||
store, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if _, err := store.Get(ctx, "test_nie_gesetzt", GlobalScope); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Fatalf("erwartet ErrNotFound, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,207 +0,0 @@
|
|||||||
package channels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/notify"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*TemplateStore, *InAppStore, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS notification_templates (
|
|
||||||
tenant_slug TEXT NOT NULL, key TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (tenant_slug, key)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS in_app_notifications (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_slug TEXT NOT NULL, user_id TEXT NOT NULL,
|
|
||||||
title TEXT NOT NULL, body TEXT NOT NULL, read_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS notification_jobs (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), channel TEXT NOT NULL, recipient TEXT NOT NULL,
|
|
||||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','failed')),
|
|
||||||
attempts INT NOT NULL DEFAULT 0, max_attempts INT NOT NULL DEFAULT 5,
|
|
||||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), last_error TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return NewTemplateStore(pool), NewInAppStore(pool), cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueKey(prefix string) string {
|
|
||||||
return fmt.Sprintf("%s_%d", prefix, time.Now().UnixNano())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 1: Vorlagenrendering mit fehlenden
|
|
||||||
// Platzhaltern bricht kontrolliert ab.
|
|
||||||
func TestRender_MissingPlaceholderAborts(t *testing.T) {
|
|
||||||
tmpl := Template{Subject: "Hallo {{.name}}", Body: "Dein Code: {{.code}}"}
|
|
||||||
|
|
||||||
_, _, err := Render(tmpl, map[string]any{"name": "Alice"}) // "code" fehlt
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei fehlendem platzhalter 'code'")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRender_SucceedsWithAllPlaceholders(t *testing.T) {
|
|
||||||
tmpl := Template{Subject: "Hallo {{.name}}", Body: "Dein Code: {{.code}}"}
|
|
||||||
|
|
||||||
subject, body, err := Render(tmpl, map[string]any{"name": "Alice", "code": "1234"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("render: %v", err)
|
|
||||||
}
|
|
||||||
if subject != "Hallo Alice" || body != "Dein Code: 1234" {
|
|
||||||
t.Fatalf("unerwartet: subject=%q body=%q", subject, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: Vorlagen pro Tenant anpassbar, Fallback auf global.
|
|
||||||
func TestTemplateStore_TenantOverrideFallsBackToGlobal(t *testing.T) {
|
|
||||||
templates, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
key := uniqueKey("welcome")
|
|
||||||
if err := templates.Set(ctx, GlobalTemplateScope, key, "Willkommen", "Standardtext"); err != nil {
|
|
||||||
t.Fatalf("set global: %v", err)
|
|
||||||
}
|
|
||||||
if err := templates.Set(ctx, "acme", key, "Willkommen bei ACME", "ACME-Text"); err != nil {
|
|
||||||
t.Fatalf("set tenant: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := templates.Resolve(ctx, "acme", key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve acme: %v", err)
|
|
||||||
}
|
|
||||||
if got.Subject != "Willkommen bei ACME" {
|
|
||||||
t.Fatalf("erwartet tenant-vorlage, habe %q", got.Subject)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err = templates.Resolve(ctx, "globex", key) // hat keine eigene vorlage
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolve globex: %v", err)
|
|
||||||
}
|
|
||||||
if got.Subject != "Willkommen" {
|
|
||||||
t.Fatalf("erwartet global-fallback, habe %q", got.Subject)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: als gelesen markiert wird korrekt gefuehrt.
|
|
||||||
func TestInAppStore_MarkReadIsReflectedCorrectly(t *testing.T) {
|
|
||||||
_, inApp, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
userID := uniqueKey("user")
|
|
||||||
id, err := inApp.Create(ctx, "acme", userID, "Titel", "Text")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
list, err := inApp.ListForUser(ctx, "acme", userID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list (vor markierung): %v", err)
|
|
||||||
}
|
|
||||||
if len(list) != 1 || list[0].ReadAt != nil {
|
|
||||||
t.Fatalf("erwartet 1 ungelesene benachrichtigung, habe %+v", list)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := inApp.MarkRead(ctx, id); err != nil {
|
|
||||||
t.Fatalf("mark read: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
list, err = inApp.ListForUser(ctx, "acme", userID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list (nach markierung): %v", err)
|
|
||||||
}
|
|
||||||
if len(list) != 1 || list[0].ReadAt == nil {
|
|
||||||
t.Fatalf("erwartet als gelesen markiert, habe %+v", list)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// EmailSender bricht ab, BEVOR SMTP ueberhaupt kontaktiert wird, wenn keine
|
|
||||||
// Vorlage aufloesbar ist — Nachweis, dass der Abbruch vor dem Netzwerkzugriff
|
|
||||||
// erfolgt (Akzeptanzkriterium 1).
|
|
||||||
func TestEmailSender_AbortsBeforeSMTPWhenTemplateMissing(t *testing.T) {
|
|
||||||
templates, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
sender := NewEmailSender(templates, "nicht-aufloesbarer-smtp-host.invalid", "25", "noreply@example.com")
|
|
||||||
|
|
||||||
err := sender.Send(ctx, notify.Notification{
|
|
||||||
Recipient: "user@example.com",
|
|
||||||
Payload: map[string]any{"template_key": uniqueKey("nie_konfiguriert"), "tenant_slug": "acme"},
|
|
||||||
})
|
|
||||||
if !errors.Is(err, ErrTemplateNotFound) {
|
|
||||||
t.Fatalf("erwartet ErrTemplateNotFound (kein smtp-versuch), habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 3: E-Mail-Versand bei nicht erreichbarem
|
|
||||||
// SMTP-Server loest das dokumentierte Retry-Verhalten ueber CFG-02 aus.
|
|
||||||
func TestEmailSender_TriggersDispatcherRetryOnUnreachableSMTP(t *testing.T) {
|
|
||||||
templates, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
defer pool.Close()
|
|
||||||
|
|
||||||
key := uniqueKey("retry_test")
|
|
||||||
if err := templates.Set(ctx, GlobalTemplateScope, key, "Betreff", "Text ohne Platzhalter"); err != nil {
|
|
||||||
t.Fatalf("set template: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
sender := NewEmailSender(templates, "nicht-aufloesbarer-smtp-host.invalid", "25", "noreply@example.com")
|
|
||||||
dispatcher := notify.NewDispatcher(pool).WithRetryPolicy(2, time.Millisecond)
|
|
||||||
|
|
||||||
jobID, err := dispatcher.Enqueue(ctx, "email", "user@example.com", map[string]any{"template_key": key, "tenant_slug": "acme"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < 2; i++ {
|
|
||||||
time.Sleep(5 * time.Millisecond)
|
|
||||||
if _, _, err := dispatcher.ProcessDue(ctx, sender, 10); err != nil {
|
|
||||||
t.Fatalf("process due %d: %v", i, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var status string
|
|
||||||
var attempts int
|
|
||||||
if err := pool.QueryRow(ctx, `SELECT status, attempts FROM notification_jobs WHERE id = $1`, jobID).Scan(&status, &attempts); err != nil {
|
|
||||||
t.Fatalf("status lesen: %v", err)
|
|
||||||
}
|
|
||||||
if status != "failed" {
|
|
||||||
t.Fatalf("erwartet status failed nach ausgeschoepften wiederholungen bei unerreichbarem smtp, habe %q", status)
|
|
||||||
}
|
|
||||||
if attempts != 2 {
|
|
||||||
t.Fatalf("erwartet 2 versuche, habe %d", attempts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
package channels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/smtp"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/notify"
|
|
||||||
)
|
|
||||||
|
|
||||||
// EmailSender implementiert notify.Sender fuer den E-Mail-Kanal
|
|
||||||
// (Akzeptanzkriterium 1). SMTP-Zugangsdaten kommen ausschliesslich aus
|
|
||||||
// Umgebungsvariablen, nie aus Code/DB.
|
|
||||||
type EmailSender struct {
|
|
||||||
templates *TemplateStore
|
|
||||||
host string
|
|
||||||
port string
|
|
||||||
from string
|
|
||||||
username string
|
|
||||||
password string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewEmailSenderFromEnv liest NEXARCH_SMTP_HOST/PORT/FROM (Pflicht) sowie
|
|
||||||
// optional NEXARCH_SMTP_USER/PASSWORD.
|
|
||||||
func NewEmailSenderFromEnv(templates *TemplateStore) (*EmailSender, error) {
|
|
||||||
host := os.Getenv("NEXARCH_SMTP_HOST")
|
|
||||||
port := os.Getenv("NEXARCH_SMTP_PORT")
|
|
||||||
from := os.Getenv("NEXARCH_SMTP_FROM")
|
|
||||||
if host == "" || port == "" || from == "" {
|
|
||||||
return nil, fmt.Errorf("channels: NEXARCH_SMTP_HOST/PORT/FROM muessen gesetzt sein")
|
|
||||||
}
|
|
||||||
return &EmailSender{
|
|
||||||
templates: templates,
|
|
||||||
host: host,
|
|
||||||
port: port,
|
|
||||||
from: from,
|
|
||||||
username: os.Getenv("NEXARCH_SMTP_USER"),
|
|
||||||
password: os.Getenv("NEXARCH_SMTP_PASSWORD"),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewEmailSender erlaubt Tests, Host/Port explizit zu setzen (z.B. einen
|
|
||||||
// absichtlich nicht erreichbaren Host fuer den Retry-Nachweis), ohne
|
|
||||||
// Umgebungsvariablen zu benoetigen.
|
|
||||||
func NewEmailSender(templates *TemplateStore, host, port, from string) *EmailSender {
|
|
||||||
return &EmailSender{templates: templates, host: host, port: port, from: from}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send rendert zuerst die Vorlage — schlaegt das fehl (z.B. fehlender
|
|
||||||
// Platzhalter), wird NIE eine SMTP-Verbindung aufgebaut
|
|
||||||
// (Akzeptanzkriterium 1 / Pruefung 1: kontrollierter Abbruch statt
|
|
||||||
// fehlerhafter Mail). Ein danach fehlschlagender SMTP-Versand liefert einen
|
|
||||||
// Fehler zurueck, den CFG-02s Dispatcher fuer die bereits getestete
|
|
||||||
// Wiederholungslogik nutzt (Akzeptanzkriterium 3 / Pruefung 3) — kein
|
|
||||||
// zweiter Retry-Mechanismus hier.
|
|
||||||
func (e *EmailSender) Send(ctx context.Context, n notify.Notification) error {
|
|
||||||
templateKey, _ := n.Payload["template_key"].(string)
|
|
||||||
tenantSlug, _ := n.Payload["tenant_slug"].(string)
|
|
||||||
|
|
||||||
tmpl, err := e.templates.Resolve(ctx, tenantSlug, templateKey)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("vorlage aufloesen: %w", err)
|
|
||||||
}
|
|
||||||
subject, body, err := Render(tmpl, n.Payload)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := []byte("Subject: " + subject + "\r\n\r\n" + body)
|
|
||||||
|
|
||||||
var auth smtp.Auth
|
|
||||||
if e.username != "" {
|
|
||||||
auth = smtp.PlainAuth("", e.username, e.password, e.host)
|
|
||||||
}
|
|
||||||
addr := e.host + ":" + e.port
|
|
||||||
if err := smtp.SendMail(addr, auth, e.from, []string{n.Recipient}, msg); err != nil {
|
|
||||||
return fmt.Errorf("smtp-versand fehlgeschlagen: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package channels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
type InAppNotification struct {
|
|
||||||
ID string
|
|
||||||
TenantSlug string
|
|
||||||
UserID string
|
|
||||||
Title string
|
|
||||||
Body string
|
|
||||||
ReadAt *time.Time
|
|
||||||
CreatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// InAppStore persistiert In-App-Benachrichtigungen (Akzeptanzkriterium 2).
|
|
||||||
type InAppStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInAppStore(pool *pgxpool.Pool) *InAppStore {
|
|
||||||
return &InAppStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *InAppStore) Create(ctx context.Context, tenantSlug, userID, title, body string) (string, error) {
|
|
||||||
var id string
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO in_app_notifications (tenant_slug, user_id, title, body)
|
|
||||||
VALUES ($1, $2, $3, $4)
|
|
||||||
RETURNING id
|
|
||||||
`, tenantSlug, userID, title, body).Scan(&id)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("in-app-benachrichtigung speichern: %w", err)
|
|
||||||
}
|
|
||||||
return id, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListForUser liefert alle Benachrichtigungen eines Benutzers (ueber API
|
|
||||||
// abrufbar, Akzeptanzkriterium 2).
|
|
||||||
func (s *InAppStore) ListForUser(ctx context.Context, tenantSlug, userID string) ([]InAppNotification, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, title, body, read_at, created_at FROM in_app_notifications
|
|
||||||
WHERE tenant_slug = $1 AND user_id = $2 ORDER BY created_at DESC
|
|
||||||
`, tenantSlug, userID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("benachrichtigungen auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []InAppNotification
|
|
||||||
for rows.Next() {
|
|
||||||
n := InAppNotification{TenantSlug: tenantSlug, UserID: userID}
|
|
||||||
if err := rows.Scan(&n.ID, &n.Title, &n.Body, &n.ReadAt, &n.CreatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("benachrichtigung lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, n)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarkRead markiert eine Benachrichtigung als gelesen (Akzeptanzkriterium 2
|
|
||||||
// / Pruefung 2).
|
|
||||||
func (s *InAppStore) MarkRead(ctx context.Context, id string) error {
|
|
||||||
_, err := s.pool.Exec(ctx, `UPDATE in_app_notifications SET read_at = now() WHERE id = $1`, id)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("als gelesen markieren: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package channels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/notify"
|
|
||||||
)
|
|
||||||
|
|
||||||
// InAppSender implementiert notify.Sender fuer den In-App-Kanal
|
|
||||||
// (Akzeptanzkriterium 2). Nutzt eine Vorlage, falls payload["template_key"]
|
|
||||||
// gesetzt ist, sonst direkt payload["title"]/["body"].
|
|
||||||
type InAppSender struct {
|
|
||||||
store *InAppStore
|
|
||||||
templates *TemplateStore
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInAppSender(store *InAppStore, templates *TemplateStore) *InAppSender {
|
|
||||||
return &InAppSender{store: store, templates: templates}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *InAppSender) Send(ctx context.Context, n notify.Notification) error {
|
|
||||||
tenantSlug, _ := n.Payload["tenant_slug"].(string)
|
|
||||||
|
|
||||||
var title, body string
|
|
||||||
if templateKey, ok := n.Payload["template_key"].(string); ok && templateKey != "" {
|
|
||||||
tmpl, err := s.templates.Resolve(ctx, tenantSlug, templateKey)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
title, body, err = Render(tmpl, n.Payload)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
title, _ = n.Payload["title"].(string)
|
|
||||||
body, _ = n.Payload["body"].(string)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := s.store.Create(ctx, tenantSlug, n.Recipient, title, body)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package channels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/notify"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Router waehlt anhand von Notification.Channel den zustaendigen Kanal aus
|
|
||||||
// — ein neuer Kanal wird per Register() ergaenzt, ohne den Dispatcher
|
|
||||||
// (CFG-02) oder Router selbst umzubauen (Unleash-artiger Strategie-Gedanke,
|
|
||||||
// siehe Ticket-DNA).
|
|
||||||
type Router struct {
|
|
||||||
channels map[string]notify.Sender
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRouter() *Router {
|
|
||||||
return &Router{channels: make(map[string]notify.Sender)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Router) Register(channel string, sender notify.Sender) {
|
|
||||||
r.channels[channel] = sender
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Router) Send(ctx context.Context, n notify.Notification) error {
|
|
||||||
sender, ok := r.channels[n.Channel]
|
|
||||||
if !ok {
|
|
||||||
return fmt.Errorf("channels: unbekannter kanal %q", n.Channel)
|
|
||||||
}
|
|
||||||
return sender.Send(ctx, n)
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
// Package channels implementiert Core CFG-03: konkrete Zustellkanaele fuer
|
|
||||||
// den CFG-02-Dispatcher (E-Mail, In-App) inklusive Vorlagenverwaltung.
|
|
||||||
// Neue Kanaele lassen sich ergaenzen, ohne den Dispatcher selbst
|
|
||||||
// anzufassen — jeder Kanal implementiert nur notify.Sender.
|
|
||||||
package channels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"text/template"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// GlobalTemplateScope ist der Fallback-Wert, wenn ein Tenant keine eigene
|
|
||||||
// Vorlage konfiguriert hat (Akzeptanzkriterium 3).
|
|
||||||
const GlobalTemplateScope = "global"
|
|
||||||
|
|
||||||
var ErrTemplateNotFound = errors.New("channels: keine vorlage gefunden")
|
|
||||||
|
|
||||||
type Template struct {
|
|
||||||
Subject string
|
|
||||||
Body string
|
|
||||||
}
|
|
||||||
|
|
||||||
type TemplateStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTemplateStore(pool *pgxpool.Pool) *TemplateStore {
|
|
||||||
return &TemplateStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set legt eine Vorlage fuer einen Tenant (oder GlobalTemplateScope) fest.
|
|
||||||
func (s *TemplateStore) Set(ctx context.Context, tenantSlug, key, subject, body string) error {
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO notification_templates (tenant_slug, key, subject, body, updated_at)
|
|
||||||
VALUES ($1, $2, $3, $4, now())
|
|
||||||
ON CONFLICT (tenant_slug, key) DO UPDATE SET subject = $3, body = $4, updated_at = now()
|
|
||||||
`, tenantSlug, key, subject, body)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("vorlage speichern: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve liefert die Vorlage eines Tenants, faellt auf GlobalTemplateScope
|
|
||||||
// zurueck, wenn der Tenant keine eigene gesetzt hat (Akzeptanzkriterium 3).
|
|
||||||
func (s *TemplateStore) Resolve(ctx context.Context, tenantSlug, key string) (Template, error) {
|
|
||||||
if tenantSlug != "" && tenantSlug != GlobalTemplateScope {
|
|
||||||
if t, err := s.get(ctx, tenantSlug, key); err == nil {
|
|
||||||
return t, nil
|
|
||||||
} else if !errors.Is(err, ErrTemplateNotFound) {
|
|
||||||
return Template{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s.get(ctx, GlobalTemplateScope, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TemplateStore) get(ctx context.Context, tenantSlug, key string) (Template, error) {
|
|
||||||
var t Template
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT subject, body FROM notification_templates WHERE tenant_slug = $1 AND key = $2
|
|
||||||
`, tenantSlug, key).Scan(&t.Subject, &t.Body)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return Template{}, ErrTemplateNotFound
|
|
||||||
}
|
|
||||||
return Template{}, fmt.Errorf("vorlage lesen: %w", err)
|
|
||||||
}
|
|
||||||
return t, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render fuellt eine Vorlage mit data. Fehlt ein referenzierter Platzhalter
|
|
||||||
// in data, bricht das Rendering kontrolliert MIT FEHLER ab, statt eine
|
|
||||||
// fehlerhafte/unvollstaendige Nachricht zu erzeugen (Akzeptanzkriterium 1 /
|
|
||||||
// Pruefung 1) — text/template mit Option("missingkey=error") liefert dafuer
|
|
||||||
// einen Fehler statt stillschweigend "<no value>" einzusetzen.
|
|
||||||
func Render(tmpl Template, data map[string]any) (subject, body string, err error) {
|
|
||||||
subject, err = renderOne("subject", tmpl.Subject, data)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
body, err = renderOne("body", tmpl.Body, data)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
return subject, body, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func renderOne(name, text string, data map[string]any) (string, error) {
|
|
||||||
tmpl, err := template.New(name).Option("missingkey=error").Parse(text)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("vorlage %q parsen: %w", name, err)
|
|
||||||
}
|
|
||||||
var buf bytes.Buffer
|
|
||||||
if err := tmpl.Execute(&buf, data); err != nil {
|
|
||||||
return "", fmt.Errorf("vorlage %q rendern (fehlender platzhalter?): %w", name, err)
|
|
||||||
}
|
|
||||||
return buf.String(), nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// Package license implementiert Core LIC-01: Lizenzmodell je Tenant (Plan,
|
||||||
|
// Modul-Umfang, Laufzeit) und die kryptographische Pruefung signierter
|
||||||
|
// Lizenzschluessel. Feature-Flag-AUSWERTUNG zur Laufzeit (LIC-02) und die
|
||||||
|
// Verwaltungsoberflaeche (LIC-04) sind ausdruecklich nicht Teil dieses Pakets
|
||||||
|
// — hier geht es nur um Ausstellung/Validierung/Persistenz (Unleash-Vorbild:
|
||||||
|
// klare Trennung Flag-Verwaltung vs. Flag-Auswertung).
|
||||||
|
package license
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidSignature = errors.New("license: signatur ungueltig")
|
||||||
|
ErrMalformedKey = errors.New("license: lizenzschluessel hat ungueltiges format")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Payload ist der signierte Lizenzinhalt (Akzeptanzkriterium 3: Plan,
|
||||||
|
// Modul-Liste, Laufzeit).
|
||||||
|
type Payload struct {
|
||||||
|
TenantSlug string `json:"tenant_slug"`
|
||||||
|
Plan string `json:"plan"`
|
||||||
|
Modules []string `json:"modules"`
|
||||||
|
IssuedAt time.Time `json:"issued_at"`
|
||||||
|
ValidUntil time.Time `json:"valid_until"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issuer stellt signierte Lizenzschluessel aus. Haelt den PRIVATEN
|
||||||
|
// Ed25519-Schluessel — lebt in der Praxis beim Lizenzgeber, nicht im
|
||||||
|
// laufenden Core-Prozess (der nur den Validator mit dem oeffentlichen
|
||||||
|
// Schluessel braucht).
|
||||||
|
type Issuer struct {
|
||||||
|
priv ed25519.PrivateKey
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewIssuer(priv ed25519.PrivateKey) *Issuer {
|
||||||
|
return &Issuer{priv: priv}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issue liefert den Lizenzschluessel im Format base64(payload-json) "." base64(signatur).
|
||||||
|
func (i *Issuer) Issue(payload Payload) (string, error) {
|
||||||
|
raw, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("payload serialisieren: %w", err)
|
||||||
|
}
|
||||||
|
sig := ed25519.Sign(i.priv, raw)
|
||||||
|
|
||||||
|
return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validator prueft Lizenzschluessel gegen den OEFFENTLICHEN Ed25519-Schluessel
|
||||||
|
// — das ist alles, was der laufende Core-Prozess kennen muss.
|
||||||
|
type Validator struct {
|
||||||
|
pub ed25519.PublicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewValidator(pub ed25519.PublicKey) *Validator {
|
||||||
|
return &Validator{pub: pub}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse prueft die Signatur (Akzeptanzkriterium 1 / Pruefung 1) und liefert
|
||||||
|
// bei Erfolg den entschluesselten Payload. Ein manipulierter Schluessel wird
|
||||||
|
// hier zuverlaessig erkannt, unabhaengig davon, ob die Laufzeit noch gueltig
|
||||||
|
// waere — Signaturpruefung und Ablaufpruefung sind bewusst getrennt
|
||||||
|
// (Signatur bei Einspielen, Ablauf bei jeder Nutzung, siehe Store.RequireActive).
|
||||||
|
func (v *Validator) Parse(key string) (Payload, error) {
|
||||||
|
rawPart, sigPart, ok := splitOnce(key, '.')
|
||||||
|
if !ok {
|
||||||
|
return Payload{}, ErrMalformedKey
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(rawPart)
|
||||||
|
if err != nil {
|
||||||
|
return Payload{}, ErrMalformedKey
|
||||||
|
}
|
||||||
|
sig, err := base64.RawURLEncoding.DecodeString(sigPart)
|
||||||
|
if err != nil {
|
||||||
|
return Payload{}, ErrMalformedKey
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ed25519.Verify(v.pub, raw, sig) {
|
||||||
|
return Payload{}, ErrInvalidSignature
|
||||||
|
}
|
||||||
|
|
||||||
|
var p Payload
|
||||||
|
if err := json.Unmarshal(raw, &p); err != nil {
|
||||||
|
// Signatur war gueltig, aber Payload nicht mehr parsebar — sollte bei
|
||||||
|
// unveraenderten Schluesseln nie vorkommen, trotzdem kein Panic.
|
||||||
|
return Payload{}, fmt.Errorf("%w: payload nicht lesbar", ErrMalformedKey)
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitOnce(s string, sep byte) (before, after string, ok bool) {
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] == sep {
|
||||||
|
return s[:i], s[i+1:], true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package license
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testKeyPair(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) {
|
||||||
|
t.Helper()
|
||||||
|
pub, priv, err := ed25519.GenerateKey(nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("schluesselpaar erzeugen: %v", err)
|
||||||
|
}
|
||||||
|
return pub, priv
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueAndParse_RoundTrip(t *testing.T) {
|
||||||
|
pub, priv := testKeyPair(t)
|
||||||
|
issuer := NewIssuer(priv)
|
||||||
|
validator := NewValidator(pub)
|
||||||
|
|
||||||
|
payload := Payload{
|
||||||
|
TenantSlug: "acme",
|
||||||
|
Plan: "pro",
|
||||||
|
Modules: []string{"dms", "mail"},
|
||||||
|
IssuedAt: time.Now().Truncate(time.Second),
|
||||||
|
ValidUntil: time.Now().Add(365 * 24 * time.Hour).Truncate(time.Second),
|
||||||
|
}
|
||||||
|
|
||||||
|
key, err := issuer.Issue(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("issue: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := validator.Parse(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
if got.TenantSlug != payload.TenantSlug || got.Plan != payload.Plan || len(got.Modules) != 2 {
|
||||||
|
t.Fatalf("payload nach parse unerwartet: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 1 + Pruefung 1: manipulierter Schluessel wird zuverlaessig erkannt.
|
||||||
|
func TestParse_RejectsTamperedKey(t *testing.T) {
|
||||||
|
pub, priv := testKeyPair(t)
|
||||||
|
issuer := NewIssuer(priv)
|
||||||
|
validator := NewValidator(pub)
|
||||||
|
|
||||||
|
key, err := issuer.Issue(Payload{TenantSlug: "acme", Plan: "pro", ValidUntil: time.Now().Add(time.Hour)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("issue: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ein Zeichen im signierten Teil aendern.
|
||||||
|
tampered := []byte(key)
|
||||||
|
changed := false
|
||||||
|
for i, c := range tampered {
|
||||||
|
if c != '.' {
|
||||||
|
if c == 'A' {
|
||||||
|
tampered[i] = 'B'
|
||||||
|
} else {
|
||||||
|
tampered[i] = 'A'
|
||||||
|
}
|
||||||
|
changed = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
t.Fatal("testaufbau fehlerhaft: nichts zum manipulieren gefunden")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := validator.Parse(string(tampered)); !errors.Is(err, ErrInvalidSignature) {
|
||||||
|
t.Fatalf("erwartet ErrInvalidSignature, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParse_RejectsWrongKeyPair(t *testing.T) {
|
||||||
|
_, priv := testKeyPair(t)
|
||||||
|
otherPub, _ := testKeyPair(t)
|
||||||
|
|
||||||
|
issuer := NewIssuer(priv)
|
||||||
|
validator := NewValidator(otherPub) // falscher oeffentlicher Schluessel
|
||||||
|
|
||||||
|
key, err := issuer.Issue(Payload{TenantSlug: "acme", Plan: "pro"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("issue: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := validator.Parse(key); !errors.Is(err, ErrInvalidSignature) {
|
||||||
|
t.Fatalf("erwartet ErrInvalidSignature, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParse_RejectsMalformedKey(t *testing.T) {
|
||||||
|
pub, _ := testKeyPair(t)
|
||||||
|
validator := NewValidator(pub)
|
||||||
|
|
||||||
|
cases := []string{"", "keine-punkt-trennung", "!!!.!!!"}
|
||||||
|
for _, c := range cases {
|
||||||
|
if _, err := validator.Parse(c); !errors.Is(err, ErrMalformedKey) {
|
||||||
|
t.Fatalf("Parse(%q): erwartet ErrMalformedKey, habe %v", c, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package license
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNoLicense = errors.New("license: kein lizenzdatensatz fuer diesen tenant")
|
||||||
|
ErrLicenseExpired = errors.New("license: lizenz abgelaufen")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store persistiert den Lizenzumfang je Tenant in der Control-Plane-Registry
|
||||||
|
// (siehe internal/tenant.Registry — dieselbe Datenbank, aber ein eigener,
|
||||||
|
// unabhaengiger Store, um internal/tenant nicht um lizenzfremde Belange zu
|
||||||
|
// erweitern).
|
||||||
|
type Store struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
validator *Validator
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStore(pool *pgxpool.Pool, validator *Validator) *Store {
|
||||||
|
return &Store{pool: pool, validator: validator}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Install prueft die Signatur des Lizenzschluessels (Akzeptanzkriterium 1)
|
||||||
|
// und ersetzt den bisherigen Lizenzdatensatz des Tenants vollstaendig. Ein
|
||||||
|
// bereits abgelaufener, aber korrekt signierter Schluessel wird trotzdem
|
||||||
|
// gespeichert — der Ablauf wird erst bei der Nutzung (RequireActive)
|
||||||
|
// bewertet, nicht beim Einspielen.
|
||||||
|
func (s *Store) Install(ctx context.Context, tenantID, licenseKey string) (Payload, error) {
|
||||||
|
payload, err := s.validator.Parse(licenseKey)
|
||||||
|
if err != nil {
|
||||||
|
return Payload{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = s.pool.Exec(ctx, `
|
||||||
|
INSERT INTO tenant_licenses (tenant_id, plan, modules, issued_at, valid_until, raw_key, installed_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, now())
|
||||||
|
ON CONFLICT (tenant_id) DO UPDATE SET
|
||||||
|
plan = $2, modules = $3, issued_at = $4, valid_until = $5, raw_key = $6, installed_at = now()
|
||||||
|
`, tenantID, payload.Plan, payload.Modules, payload.IssuedAt, payload.ValidUntil, licenseKey)
|
||||||
|
if err != nil {
|
||||||
|
return Payload{}, fmt.Errorf("lizenz speichern: %w", err)
|
||||||
|
}
|
||||||
|
return payload, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) get(ctx context.Context, tenantID string) (Payload, error) {
|
||||||
|
var p Payload
|
||||||
|
row := s.pool.QueryRow(ctx, `
|
||||||
|
SELECT plan, modules, issued_at, valid_until
|
||||||
|
FROM tenant_licenses WHERE tenant_id = $1
|
||||||
|
`, tenantID)
|
||||||
|
if err := row.Scan(&p.Plan, &p.Modules, &p.IssuedAt, &p.ValidUntil); err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return Payload{}, ErrNoLicense
|
||||||
|
}
|
||||||
|
return Payload{}, fmt.Errorf("lizenz lesen: %w", err)
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status liefert den persistierten Lizenzumfang unabhaengig vom Ablauf
|
||||||
|
// (Akzeptanzkriterium 3: Plan, Modul-Liste, Laufzeit abfragbar).
|
||||||
|
func (s *Store) Status(ctx context.Context, tenantID string) (Payload, error) {
|
||||||
|
return s.get(ctx, tenantID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireActive liefert den Lizenzumfang NUR, wenn die Lizenz noch nicht
|
||||||
|
// abgelaufen ist — sonst ErrLicenseExpired statt eines harten Fehlers/Panics
|
||||||
|
// (Akzeptanzkriterium 2: definierter eingeschraenkter Zustand). Aufrufende
|
||||||
|
// Module (LIC-02/03) entscheiden, was "eingeschraenkt" konkret bedeutet.
|
||||||
|
func (s *Store) RequireActive(ctx context.Context, tenantID string) (Payload, error) {
|
||||||
|
p, err := s.get(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return Payload{}, err
|
||||||
|
}
|
||||||
|
if time.Now().After(p.ValidUntil) {
|
||||||
|
return Payload{}, ErrLicenseExpired
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package license
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupStoreTest(t *testing.T) (*Store, *Issuer, string, func()) {
|
||||||
|
t.Helper()
|
||||||
|
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||||
|
if adminDSN == "" {
|
||||||
|
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
pool, err := pgxpool.New(ctx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pool: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := pool.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS tenants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
slug TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
db_name TEXT NOT NULL UNIQUE,
|
||||||
|
db_dsn TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS tenant_licenses (
|
||||||
|
tenant_id UUID PRIMARY KEY REFERENCES tenants(id),
|
||||||
|
plan TEXT NOT NULL,
|
||||||
|
modules TEXT[] NOT NULL,
|
||||||
|
issued_at TIMESTAMPTZ NOT NULL,
|
||||||
|
valid_until TIMESTAMPTZ NOT NULL,
|
||||||
|
raw_key TEXT NOT NULL,
|
||||||
|
installed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatalf("schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var tenantID string
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
INSERT INTO tenants (slug, name, db_name, db_dsn)
|
||||||
|
VALUES ('lic_test_tenant', 'Lic Test', 'tenant_lic_test', 'unused')
|
||||||
|
RETURNING id
|
||||||
|
`).Scan(&tenantID); err != nil {
|
||||||
|
t.Fatalf("test-tenant anlegen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub, priv, err := ed25519.GenerateKey(nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("schluesselpaar: %v", err)
|
||||||
|
}
|
||||||
|
issuer := NewIssuer(priv)
|
||||||
|
store := NewStore(pool, NewValidator(pub))
|
||||||
|
|
||||||
|
cleanup := func() {
|
||||||
|
_, _ = pool.Exec(ctx, `DELETE FROM tenant_licenses WHERE tenant_id = $1`, tenantID)
|
||||||
|
_, _ = pool.Exec(ctx, `DELETE FROM tenants WHERE id = $1`, tenantID)
|
||||||
|
pool.Close()
|
||||||
|
}
|
||||||
|
return store, issuer, tenantID, cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 3: Lizenzumfang persistiert und abfragbar.
|
||||||
|
func TestStore_InstallAndStatus(t *testing.T) {
|
||||||
|
store, issuer, tenantID, cleanup := setupStoreTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
payload := Payload{
|
||||||
|
TenantSlug: "lic_test_tenant",
|
||||||
|
Plan: "enterprise",
|
||||||
|
Modules: []string{"dms", "mail", "archive"},
|
||||||
|
IssuedAt: time.Now().Truncate(time.Second),
|
||||||
|
ValidUntil: time.Now().Add(30 * 24 * time.Hour).Truncate(time.Second),
|
||||||
|
}
|
||||||
|
key, err := issuer.Issue(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("issue: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := store.Install(ctx, tenantID, key); err != nil {
|
||||||
|
t.Fatalf("install: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
status, err := store.Status(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("status: %v", err)
|
||||||
|
}
|
||||||
|
if status.Plan != "enterprise" || len(status.Modules) != 3 {
|
||||||
|
t.Fatalf("status unerwartet: %+v", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStore_InstallRejectsInvalidSignature(t *testing.T) {
|
||||||
|
store, _, tenantID, cleanup := setupStoreTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, otherPriv, _ := ed25519.GenerateKey(nil)
|
||||||
|
foreignIssuer := NewIssuer(otherPriv) // signiert mit falschem schluessel
|
||||||
|
|
||||||
|
key, err := foreignIssuer.Issue(Payload{TenantSlug: "lic_test_tenant", Plan: "pro", ValidUntil: time.Now().Add(time.Hour)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("issue: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := store.Install(ctx, tenantID, key); !errors.Is(err, ErrInvalidSignature) {
|
||||||
|
t.Fatalf("erwartet ErrInvalidSignature, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 2 + Pruefung 2: abgelaufene Lizenz fuehrt zu definiertem
|
||||||
|
// eingeschraenktem Zustand (ErrLicenseExpired), nicht zu einem Absturz.
|
||||||
|
func TestStore_RequireActive_DetectsExpiry(t *testing.T) {
|
||||||
|
store, issuer, tenantID, cleanup := setupStoreTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
expired := Payload{
|
||||||
|
TenantSlug: "lic_test_tenant",
|
||||||
|
Plan: "pro",
|
||||||
|
Modules: []string{"dms"},
|
||||||
|
IssuedAt: time.Now().Add(-48 * time.Hour),
|
||||||
|
ValidUntil: time.Now().Add(-24 * time.Hour), // bereits abgelaufen
|
||||||
|
}
|
||||||
|
key, err := issuer.Issue(expired)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("issue: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Einspielen einer bereits abgelaufenen, aber korrekt signierten Lizenz
|
||||||
|
// muss funktionieren (Ablauf wird erst bei Nutzung bewertet).
|
||||||
|
if _, err := store.Install(ctx, tenantID, key); err != nil {
|
||||||
|
t.Fatalf("install sollte trotz ablauf funktionieren: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
t.Fatalf("RequireActive hat gepanict statt einen fehler zu liefern: %v", r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if _, err := store.RequireActive(ctx, tenantID); !errors.Is(err, ErrLicenseExpired) {
|
||||||
|
t.Fatalf("erwartet ErrLicenseExpired, habe %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Aber der Umfang bleibt weiterhin abfragbar (Status, im Unterschied zu RequireActive).
|
||||||
|
status, err := store.Status(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("status sollte trotz ablauf funktionieren: %v", err)
|
||||||
|
}
|
||||||
|
if status.Plan != "pro" {
|
||||||
|
t.Fatalf("status unerwartet: %+v", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStore_RequireActive_NoLicense(t *testing.T) {
|
||||||
|
store, _, tenantID, cleanup := setupStoreTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if _, err := store.RequireActive(ctx, tenantID); !errors.Is(err, ErrNoLicense) {
|
||||||
|
t.Fatalf("erwartet ErrNoLicense, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
// Package notify implementiert Core CFG-02: den zentralen Benachrichtigungs-
|
|
||||||
// Dispatcher, ueber den beliebige Module Benachrichtigungen ausloesen —
|
|
||||||
// Warteschlange, Wiederholungslogik, Kanal-Abstraktion. Die tatsaechlichen
|
|
||||||
// Kanaele (E-Mail/In-App) sind CFG-03, hier gibt es nur die Sender-
|
|
||||||
// Schnittstelle als Vorbereitung.
|
|
||||||
package notify
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultMaxAttempts begrenzt Wiederholungsversuche (Akzeptanzkriterium 2) —
|
|
||||||
// nach dieser Anzahl gibt der Dispatcher kontrolliert auf (status=failed)
|
|
||||||
// statt endlos zu wiederholen.
|
|
||||||
const DefaultMaxAttempts = 5
|
|
||||||
|
|
||||||
// DefaultRetryBackoff ist die Basis-Wartezeit zwischen Wiederholungen,
|
|
||||||
// linear mit der Versuchsnummer skaliert.
|
|
||||||
const DefaultRetryBackoff = 200 * time.Millisecond
|
|
||||||
|
|
||||||
type Notification struct {
|
|
||||||
ID string
|
|
||||||
Channel string
|
|
||||||
Recipient string
|
|
||||||
Payload map[string]any
|
|
||||||
Attempts int
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sender ist die schmale Schnittstelle, die ein konkreter Kanal (CFG-03)
|
|
||||||
// implementiert. Der Dispatcher selbst weiss nichts ueber E-Mail/In-App.
|
|
||||||
type Sender interface {
|
|
||||||
Send(ctx context.Context, n Notification) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dispatcher ist die EINE Schnittstelle, ueber die Module Benachrichtigungen
|
|
||||||
// ausloesen — kein Modul baut eigenen Versandcode (Akzeptanzkriterium 1).
|
|
||||||
type Dispatcher struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
maxAttempts int
|
|
||||||
retryBackoff time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDispatcher(pool *pgxpool.Pool) *Dispatcher {
|
|
||||||
return &Dispatcher{pool: pool, maxAttempts: DefaultMaxAttempts, retryBackoff: DefaultRetryBackoff}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithRetryPolicy erlaubt Tests/Betrieb, Versuchsanzahl und Backoff
|
|
||||||
// anzupassen, ohne die Default-Policy im Produktionscode zu veraendern.
|
|
||||||
func (d *Dispatcher) WithRetryPolicy(maxAttempts int, backoff time.Duration) *Dispatcher {
|
|
||||||
return &Dispatcher{pool: d.pool, maxAttempts: maxAttempts, retryBackoff: backoff}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enqueue reiht eine Benachrichtigung in die Postgres-Warteschlange ein und
|
|
||||||
// kehrt sofort zurueck — die Zeile ueberlebt jeden Neustart des Dispatcher-
|
|
||||||
// Prozesses unveraendert (Akzeptanzkriterium 3), da sie ausschliesslich in
|
|
||||||
// der Datenbank existiert, nicht im Prozessspeicher.
|
|
||||||
func (d *Dispatcher) Enqueue(ctx context.Context, channel, recipient string, payload map[string]any) (string, error) {
|
|
||||||
if payload == nil {
|
|
||||||
payload = map[string]any{}
|
|
||||||
}
|
|
||||||
payloadJSON, err := json.Marshal(payload)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("payload serialisieren: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var id string
|
|
||||||
err = d.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO notification_jobs (channel, recipient, payload, max_attempts)
|
|
||||||
VALUES ($1, $2, $3, $4)
|
|
||||||
RETURNING id
|
|
||||||
`, channel, recipient, payloadJSON, d.maxAttempts).Scan(&id)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("benachrichtigung einreihen: %w", err)
|
|
||||||
}
|
|
||||||
return id, nil
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
package notify
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*pgxpool.Pool, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS notification_jobs (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
channel TEXT NOT NULL,
|
|
||||||
recipient TEXT NOT NULL,
|
|
||||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
||||||
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
|
|
||||||
attempts INT NOT NULL DEFAULT 0,
|
|
||||||
max_attempts INT NOT NULL DEFAULT 5,
|
|
||||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
last_error TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
)`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return pool, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeSender struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
sentIDs []string
|
|
||||||
failUntil int
|
|
||||||
calls int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fakeSender) Send(ctx context.Context, n Notification) error {
|
|
||||||
f.mu.Lock()
|
|
||||||
defer f.mu.Unlock()
|
|
||||||
f.calls++
|
|
||||||
if f.calls <= f.failUntil {
|
|
||||||
return errors.New("simulierter zustellfehler")
|
|
||||||
}
|
|
||||||
f.sentIDs = append(f.sentIDs, n.ID)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fakeSender) sentCount() int {
|
|
||||||
f.mu.Lock()
|
|
||||||
defer f.mu.Unlock()
|
|
||||||
return len(f.sentIDs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1: Module loesen ueber Enqueue aus, keine eigene
|
|
||||||
// Versandlogik noetig.
|
|
||||||
func TestDispatcher_EnqueueAndProcess(t *testing.T) {
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
d := NewDispatcher(pool)
|
|
||||||
id, err := d.Enqueue(ctx, "email", "alice@example.com", map[string]any{"subject": "Willkommen"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue: %v", err)
|
|
||||||
}
|
|
||||||
if id == "" {
|
|
||||||
t.Fatal("erwartet nicht-leere id")
|
|
||||||
}
|
|
||||||
|
|
||||||
sender := &fakeSender{}
|
|
||||||
sent, failed, err := d.ProcessDue(ctx, sender, 10)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("process: %v", err)
|
|
||||||
}
|
|
||||||
if sent != 1 || failed != 0 {
|
|
||||||
t.Fatalf("erwartet sent=1 failed=0, habe sent=%d failed=%d", sent, failed)
|
|
||||||
}
|
|
||||||
if sender.sentCount() != 1 {
|
|
||||||
t.Fatalf("erwartet 1 zustellung, habe %d", sender.sentCount())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: Wiederholungslogik greift bei
|
|
||||||
// simuliertem Fehler und bricht nach definierter Anzahl kontrolliert ab.
|
|
||||||
func TestProcessDue_RetriesThenGivesUpAfterMaxAttempts(t *testing.T) {
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
d := NewDispatcher(pool).WithRetryPolicy(3, time.Millisecond)
|
|
||||||
id, err := d.Enqueue(ctx, "email", "bob@example.com", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
sender := &fakeSender{failUntil: 100} // schlaegt bei jedem versuch fehl
|
|
||||||
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
time.Sleep(5 * time.Millisecond) // next_attempt_at abwarten
|
|
||||||
if _, _, err := d.ProcessDue(ctx, sender, 10); err != nil {
|
|
||||||
t.Fatalf("process %d: %v", i, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var status string
|
|
||||||
var attempts int
|
|
||||||
if err := pool.QueryRow(ctx, `SELECT status, attempts FROM notification_jobs WHERE id = $1`, id).Scan(&status, &attempts); err != nil {
|
|
||||||
t.Fatalf("status lesen: %v", err)
|
|
||||||
}
|
|
||||||
if status != "failed" {
|
|
||||||
t.Fatalf("erwartet status failed nach max_attempts, habe %q", status)
|
|
||||||
}
|
|
||||||
if attempts != 3 {
|
|
||||||
t.Fatalf("erwartet 3 versuche, habe %d", attempts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Weiteres ProcessDue darf den bereits aufgegebenen job nicht mehr anfassen.
|
|
||||||
sent, failed, err := d.ProcessDue(ctx, sender, 10)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("process nach abbruch: %v", err)
|
|
||||||
}
|
|
||||||
if sent != 0 || failed != 0 {
|
|
||||||
t.Fatalf("erwartet keine weitere verarbeitung, habe sent=%d failed=%d", sent, failed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 1: Neustart des Dienstes waehrend offener
|
|
||||||
// Zustellung verliert keine Nachricht — simuliert durch eine komplett neue
|
|
||||||
// Dispatcher/Pool-Instanz nach dem Enqueue, bevor irgendetwas verarbeitet wurde.
|
|
||||||
func TestQueue_SurvivesRestartWithoutMessageLoss(t *testing.T) {
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
firstInstance := NewDispatcher(pool)
|
|
||||||
id, err := firstInstance.Enqueue(ctx, "email", "carol@example.com", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// "Neustart": eine voellig neue Dispatcher-Instanz (repraesentiert einen
|
|
||||||
// neuen Prozess) verbindet sich neu und verarbeitet die Warteschlange —
|
|
||||||
// die Nachricht existiert ausschliesslich in Postgres, nicht im
|
|
||||||
// Prozessspeicher der ersten Instanz.
|
|
||||||
restartedInstance := NewDispatcher(pool)
|
|
||||||
sender := &fakeSender{}
|
|
||||||
sent, failed, err := restartedInstance.ProcessDue(ctx, sender, 10)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("process nach neustart: %v", err)
|
|
||||||
}
|
|
||||||
if sent != 1 || failed != 0 {
|
|
||||||
t.Fatalf("erwartet sent=1 nach neustart, habe sent=%d failed=%d", sent, failed)
|
|
||||||
}
|
|
||||||
if len(sender.sentIDs) != 1 || sender.sentIDs[0] != id {
|
|
||||||
t.Fatalf("erwartet zustellung der urspruenglichen nachricht %q, habe %v", id, sender.sentIDs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 3: zwei gleichzeitig ausloesende Module,
|
|
||||||
// beide Nachrichten werden korrekt (und nicht doppelt) zugestellt.
|
|
||||||
func TestProcessDue_ConcurrentDispatchBothDelivered(t *testing.T) {
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
d := NewDispatcher(pool)
|
|
||||||
idA, err := d.Enqueue(ctx, "email", "modul-a@example.com", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue a: %v", err)
|
|
||||||
}
|
|
||||||
idB, err := d.Enqueue(ctx, "email", "modul-b@example.com", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue b: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
sender := &fakeSender{}
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < 2; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
if _, _, err := d.ProcessDue(ctx, sender, 10); err != nil {
|
|
||||||
t.Errorf("process: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
if sender.sentCount() != 2 {
|
|
||||||
t.Fatalf("erwartet genau 2 zustellungen, habe %d: %v", sender.sentCount(), sender.sentIDs)
|
|
||||||
}
|
|
||||||
seen := map[string]bool{}
|
|
||||||
for _, id := range sender.sentIDs {
|
|
||||||
if seen[id] {
|
|
||||||
t.Fatalf("nachricht %q wurde doppelt zugestellt", id)
|
|
||||||
}
|
|
||||||
seen[id] = true
|
|
||||||
}
|
|
||||||
if !seen[idA] || !seen[idB] {
|
|
||||||
t.Fatalf("erwartet beide nachrichten zugestellt, habe %v", sender.sentIDs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
package notify
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ProcessDue holt bis zu limit faellige Benachrichtigungen und versucht sie
|
|
||||||
// ueber sender zuzustellen. FOR UPDATE SKIP LOCKED serialisiert konkurrierende
|
|
||||||
// Aufrufe (Akzeptanzkriterium 3 / Pruefung 3: zwei gleichzeitig ausloesende
|
|
||||||
// Module duerfen sich nicht gegenseitig blockieren oder Nachrichten doppelt
|
|
||||||
// zustellen) — dieselbe Konvention wie internal/tenant.Lifecycle.ProcessDueDeletions.
|
|
||||||
func (d *Dispatcher) ProcessDue(ctx context.Context, sender Sender, limit int) (sent, failed int, err error) {
|
|
||||||
tx, err := d.pool.Begin(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("transaktion starten: %w", err)
|
|
||||||
}
|
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
|
||||||
|
|
||||||
rows, err := tx.Query(ctx, `
|
|
||||||
SELECT id, channel, recipient, payload, attempts, max_attempts
|
|
||||||
FROM notification_jobs
|
|
||||||
WHERE status = 'pending' AND next_attempt_at <= now()
|
|
||||||
ORDER BY created_at
|
|
||||||
FOR UPDATE SKIP LOCKED
|
|
||||||
LIMIT $1
|
|
||||||
`, limit)
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("faellige benachrichtigungen abfragen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
type due struct {
|
|
||||||
id, channel, recipient string
|
|
||||||
payload []byte
|
|
||||||
attempts, maxAttempts int
|
|
||||||
}
|
|
||||||
var candidates []due
|
|
||||||
for rows.Next() {
|
|
||||||
var c due
|
|
||||||
if err := rows.Scan(&c.id, &c.channel, &c.recipient, &c.payload, &c.attempts, &c.maxAttempts); err != nil {
|
|
||||||
rows.Close()
|
|
||||||
return 0, 0, fmt.Errorf("faellige benachrichtigung lesen: %w", err)
|
|
||||||
}
|
|
||||||
candidates = append(candidates, c)
|
|
||||||
}
|
|
||||||
rows.Close()
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return 0, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range candidates {
|
|
||||||
var payload map[string]any
|
|
||||||
if err := json.Unmarshal(c.payload, &payload); err != nil {
|
|
||||||
payload = map[string]any{}
|
|
||||||
}
|
|
||||||
|
|
||||||
sendErr := sender.Send(ctx, Notification{
|
|
||||||
ID: c.id, Channel: c.channel, Recipient: c.recipient, Payload: payload, Attempts: c.attempts,
|
|
||||||
})
|
|
||||||
|
|
||||||
if sendErr == nil {
|
|
||||||
if _, err := tx.Exec(ctx, `
|
|
||||||
UPDATE notification_jobs SET status = 'sent', updated_at = now() WHERE id = $1
|
|
||||||
`, c.id); err != nil {
|
|
||||||
return sent, failed, fmt.Errorf("erfolg speichern: %w", err)
|
|
||||||
}
|
|
||||||
sent++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
newAttempts := c.attempts + 1
|
|
||||||
if newAttempts >= c.maxAttempts {
|
|
||||||
// Akzeptanzkriterium 2: kontrollierter Abbruch nach definierter
|
|
||||||
// Anzahl Versuche, kein endloses Wiederholen.
|
|
||||||
if _, err := tx.Exec(ctx, `
|
|
||||||
UPDATE notification_jobs
|
|
||||||
SET status = 'failed', attempts = $2, last_error = $3, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
`, c.id, newAttempts, sendErr.Error()); err != nil {
|
|
||||||
return sent, failed, fmt.Errorf("fehlschlag speichern: %w", err)
|
|
||||||
}
|
|
||||||
failed++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
nextAttempt := time.Now().Add(time.Duration(newAttempts) * d.retryBackoff)
|
|
||||||
if _, err := tx.Exec(ctx, `
|
|
||||||
UPDATE notification_jobs
|
|
||||||
SET attempts = $2, next_attempt_at = $3, last_error = $4, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
`, c.id, newAttempts, nextAttempt, sendErr.Error()); err != nil {
|
|
||||||
return sent, failed, fmt.Errorf("wiederholung planen: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("transaktion committen: %w", err)
|
|
||||||
}
|
|
||||||
return sent, failed, nil
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
package notifyprefs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler stellt Benachrichtigungspraeferenzen als HTTP-Endpunkte bereit
|
|
||||||
// (CFG-04). Duenner Client von Store — keine eigene Zustelllogik.
|
|
||||||
type Handler struct {
|
|
||||||
prefs *Store
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(prefs *Store) *Handler {
|
|
||||||
return &Handler{prefs: prefs}
|
|
||||||
}
|
|
||||||
|
|
||||||
type setPreferenceRequest struct {
|
|
||||||
EventType string `json:"event_type"`
|
|
||||||
Channel string `json:"channel"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPreference setzt die eigene Praeferenz des angemeldeten Benutzers
|
|
||||||
// (Akzeptanzkriterium 1). Muss hinter auth.RequireAuth haengen.
|
|
||||||
func (h *Handler) SetPreference(w http.ResponseWriter, r *http.Request) {
|
|
||||||
claims, ok := auth.ClaimsFromContext(r.Context())
|
|
||||||
if !ok {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var req setPreferenceRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := h.prefs.Set(r.Context(), claims.TenantSlug, claims.UserID, req.EventType, req.Channel, req.Enabled); err != nil {
|
|
||||||
http.Error(w, "Einstellung konnte nicht gespeichert werden.", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListMine liefert die eigenen Praeferenzen (Akzeptanzkriterium 1) — nur die
|
|
||||||
// EIGENEN, niemals die eines anderen Benutzers (Pruefung 2). claims.UserID
|
|
||||||
// kommt ausschliesslich aus dem verifizierten Session-Token, ist also nicht
|
|
||||||
// vom Client manipulierbar.
|
|
||||||
func (h *Handler) ListMine(w http.ResponseWriter, r *http.Request) {
|
|
||||||
claims, ok := auth.ClaimsFromContext(r.Context())
|
|
||||||
if !ok {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
prefs, err := h.prefs.ListForUser(r.Context(), claims.TenantSlug, claims.UserID)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Einstellungen konnten nicht geladen werden.", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_ = json.NewEncoder(w).Encode(prefs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListTenantOverview liefert die Praeferenzen ALLER Benutzer des eigenen
|
|
||||||
// Mandanten (Akzeptanzkriterium 3: Tenant-Admin-Übersicht). Die Zugriffs-
|
|
||||||
// beschraenkung "nur Tenant-Admin" ist Aufgabe von RBAC-02 (Policy-
|
|
||||||
// Enforcement-Schicht) vor diesem Handler — hier wird bewusst keine eigene
|
|
||||||
// Rechtelogik dupliziert (Ticket-Produkt-DNA: duenner Client).
|
|
||||||
func (h *Handler) ListTenantOverview(w http.ResponseWriter, r *http.Request) {
|
|
||||||
claims, ok := auth.ClaimsFromContext(r.Context())
|
|
||||||
if !ok {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
prefs, err := h.prefs.ListForTenant(r.Context(), claims.TenantSlug)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Übersicht konnte nicht geladen werden.", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_ = json.NewEncoder(w).Encode(prefs)
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
package notifyprefs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
func sessionCookie(t *testing.T, issuer *auth.TokenIssuer, userID, tenantSlug string) *http.Cookie {
|
|
||||||
t.Helper()
|
|
||||||
token, err := issuer.Issue(userID, tenantSlug)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("session-token ausstellen: %v", err)
|
|
||||||
}
|
|
||||||
return &http.Cookie{Name: auth.CookieName, Value: token}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1: Benutzer setzt eigene Praeferenz per HTTP.
|
|
||||||
func TestHandlerSetAndListMine(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
h := NewHandler(prefs)
|
|
||||||
issuer := auth.NewTokenIssuer("test-secret")
|
|
||||||
cookie := sessionCookie(t, issuer, "user-1", "acme")
|
|
||||||
|
|
||||||
setBody, _ := json.Marshal(setPreferenceRequest{EventType: "welcome", Channel: "email", Enabled: false})
|
|
||||||
setReq := httptest.NewRequest(http.MethodPost, "/notifications/preferences", bytes.NewReader(setBody))
|
|
||||||
setReq.AddCookie(cookie)
|
|
||||||
setRec := httptest.NewRecorder()
|
|
||||||
auth.RequireAuth(issuer, h.SetPreference)(setRec, setReq)
|
|
||||||
if setRec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("set: status = %d, body: %s", setRec.Code, setRec.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
listReq := httptest.NewRequest(http.MethodGet, "/notifications/preferences", nil)
|
|
||||||
listReq.AddCookie(cookie)
|
|
||||||
listRec := httptest.NewRecorder()
|
|
||||||
auth.RequireAuth(issuer, h.ListMine)(listRec, listReq)
|
|
||||||
if listRec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("list: status = %d, body: %s", listRec.Code, listRec.Body.String())
|
|
||||||
}
|
|
||||||
var out []Preference
|
|
||||||
if err := json.Unmarshal(listRec.Body.Bytes(), &out); err != nil {
|
|
||||||
t.Fatalf("response dekodieren: %v", err)
|
|
||||||
}
|
|
||||||
if len(out) != 1 || out[0].Enabled {
|
|
||||||
t.Fatalf("erwartet genau 1 deaktivierte praeferenz, habe %+v", out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 / Pruefung 2: ListMine zeigt AUSSCHLIESSLICH die
|
|
||||||
// eigenen Praeferenzen — die UserID kommt aus dem Session-Token, nicht aus
|
|
||||||
// einem vom Client kontrollierbaren Parameter.
|
|
||||||
func TestHandlerListMine_NeverShowsOtherUsersPreferences(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
h := NewHandler(prefs)
|
|
||||||
issuer := auth.NewTokenIssuer("test-secret")
|
|
||||||
|
|
||||||
setBody, _ := json.Marshal(setPreferenceRequest{EventType: "welcome", Channel: "email", Enabled: false})
|
|
||||||
setReq := httptest.NewRequest(http.MethodPost, "/notifications/preferences", bytes.NewReader(setBody))
|
|
||||||
setReq.AddCookie(sessionCookie(t, issuer, "user-1", "acme"))
|
|
||||||
setRec := httptest.NewRecorder()
|
|
||||||
auth.RequireAuth(issuer, h.SetPreference)(setRec, setReq)
|
|
||||||
if setRec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("set fuer user-1: status = %d", setRec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// user-2 fragt seine eigenen Praeferenzen ab — muss leer sein.
|
|
||||||
listReq := httptest.NewRequest(http.MethodGet, "/notifications/preferences", nil)
|
|
||||||
listReq.AddCookie(sessionCookie(t, issuer, "user-2", "acme"))
|
|
||||||
listRec := httptest.NewRecorder()
|
|
||||||
auth.RequireAuth(issuer, h.ListMine)(listRec, listReq)
|
|
||||||
if listRec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("list fuer user-2: status = %d", listRec.Code)
|
|
||||||
}
|
|
||||||
var out []Preference
|
|
||||||
if err := json.Unmarshal(listRec.Body.Bytes(), &out); err != nil {
|
|
||||||
t.Fatalf("response dekodieren: %v", err)
|
|
||||||
}
|
|
||||||
if len(out) != 0 {
|
|
||||||
t.Fatalf("user-2 haette user-1s praeferenzen NICHT sehen duerfen, habe %+v", out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: Tenant-Übersicht liefert alle Benutzer des Mandanten.
|
|
||||||
func TestHandlerListTenantOverview(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
h := NewHandler(prefs)
|
|
||||||
issuer := auth.NewTokenIssuer("test-secret")
|
|
||||||
|
|
||||||
for _, u := range []string{"user-1", "user-2"} {
|
|
||||||
body, _ := json.Marshal(setPreferenceRequest{EventType: "welcome", Channel: "email", Enabled: false})
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/notifications/preferences", bytes.NewReader(body))
|
|
||||||
req.AddCookie(sessionCookie(t, issuer, u, "acme"))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
auth.RequireAuth(issuer, h.SetPreference)(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("set fuer %s: status = %d", u, rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/notifications/preferences/tenant", nil)
|
|
||||||
req.AddCookie(sessionCookie(t, issuer, "admin-1", "acme"))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
auth.RequireAuth(issuer, h.ListTenantOverview)(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("overview: status = %d, body: %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var out []Preference
|
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
|
||||||
t.Fatalf("response dekodieren: %v", err)
|
|
||||||
}
|
|
||||||
if len(out) != 2 {
|
|
||||||
t.Fatalf("erwartet 2 eintraege (beide Benutzer), habe %d", len(out))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
// Package notifyprefs implementiert Core CFG-04: Benachrichtigungspräferenzen
|
|
||||||
// je Benutzer, Ereignistyp und Kanal. Duenner Client von CFG-02/03 — keine
|
|
||||||
// eigene Zustelllogik, nur ein Filter DAVOR, ob eine Benachrichtigung
|
|
||||||
// überhaupt in die Warteschlange (internal/notify.Dispatcher) eingereiht wird.
|
|
||||||
package notifyprefs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/notify"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Preference struct {
|
|
||||||
TenantSlug string
|
|
||||||
UserID string
|
|
||||||
EventType string
|
|
||||||
Channel string
|
|
||||||
Enabled bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store verwaltet Benachrichtigungspraeferenzen in der zentralen Registry-DB
|
|
||||||
// (gleiche Ablageebene wie CFG-03s notification_templates/in_app_notifications).
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool) *Store {
|
|
||||||
return &Store{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set setzt die Praeferenz eines Benutzers fuer einen Ereignistyp+Kanal
|
|
||||||
// (Akzeptanzkriterium 1). Wirkt sofort — es gibt keinen Cache dazwischen,
|
|
||||||
// jede Pruefung (IsEnabled) liest direkt aus der DB (Akzeptanzkriterium 2).
|
|
||||||
func (s *Store) Set(ctx context.Context, tenantSlug, userID, eventType, channel string, enabled bool) error {
|
|
||||||
if tenantSlug == "" || userID == "" || eventType == "" || channel == "" {
|
|
||||||
return errors.New("notifyprefs: tenantSlug, userID, eventType und channel duerfen nicht leer sein")
|
|
||||||
}
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO notification_preferences (tenant_slug, user_id, event_type, channel, enabled)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
ON CONFLICT (tenant_slug, user_id, event_type, channel)
|
|
||||||
DO UPDATE SET enabled = $5, updated_at = now()
|
|
||||||
`, tenantSlug, userID, eventType, channel, enabled)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("praeferenz speichern: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsEnabled prueft, ob ein Kanal fuer einen Ereignistyp aktiv ist. Ohne
|
|
||||||
// explizite Praeferenz gilt der Kanal als AKTIVIERT (Opt-out-Default,
|
|
||||||
// siehe Migration).
|
|
||||||
func (s *Store) IsEnabled(ctx context.Context, tenantSlug, userID, eventType, channel string) (bool, error) {
|
|
||||||
var enabled bool
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT enabled FROM notification_preferences
|
|
||||||
WHERE tenant_slug = $1 AND user_id = $2 AND event_type = $3 AND channel = $4
|
|
||||||
`, tenantSlug, userID, eventType, channel).Scan(&enabled)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
return false, fmt.Errorf("praeferenz lesen: %w", err)
|
|
||||||
}
|
|
||||||
return enabled, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListForUser liefert alle expliziten Praeferenzen eines Benutzers
|
|
||||||
// (Akzeptanzkriterium 1: eigene Einstellungen einsehen/aendern).
|
|
||||||
func (s *Store) ListForUser(ctx context.Context, tenantSlug, userID string) ([]Preference, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT event_type, channel, enabled FROM notification_preferences
|
|
||||||
WHERE tenant_slug = $1 AND user_id = $2
|
|
||||||
ORDER BY event_type, channel
|
|
||||||
`, tenantSlug, userID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("praeferenzen auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []Preference
|
|
||||||
for rows.Next() {
|
|
||||||
p := Preference{TenantSlug: tenantSlug, UserID: userID}
|
|
||||||
if err := rows.Scan(&p.EventType, &p.Channel, &p.Enabled); err != nil {
|
|
||||||
return nil, fmt.Errorf("praeferenz lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, p)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListForTenant liefert ALLE expliziten Praeferenzen aller Benutzer eines
|
|
||||||
// Mandanten (Akzeptanzkriterium 3: Tenant-Admin-Übersicht).
|
|
||||||
func (s *Store) ListForTenant(ctx context.Context, tenantSlug string) ([]Preference, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT user_id, event_type, channel, enabled FROM notification_preferences
|
|
||||||
WHERE tenant_slug = $1
|
|
||||||
ORDER BY user_id, event_type, channel
|
|
||||||
`, tenantSlug)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("mandanten-praeferenzen auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []Preference
|
|
||||||
for rows.Next() {
|
|
||||||
p := Preference{TenantSlug: tenantSlug}
|
|
||||||
if err := rows.Scan(&p.UserID, &p.EventType, &p.Channel, &p.Enabled); err != nil {
|
|
||||||
return nil, fmt.Errorf("praeferenz lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, p)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnqueueIfAllowed ist der einzige vorgesehene Weg, wie ein Modul eine
|
|
||||||
// Benachrichtigung fuer einen konkreten Benutzer+Ereignistyp auslöst: prueft
|
|
||||||
// zuerst die Praeferenz, reiht NUR bei Aktivierung tatsaechlich in
|
|
||||||
// internal/notify.Dispatcher ein (Akzeptanzkriterium 1 / Pruefung 1 — ein
|
|
||||||
// deaktivierter Kanal erzeugt nachweislich KEINE notification_jobs-Zeile,
|
|
||||||
// nicht nur eine ignorierte). skipped=true bedeutet: bewusst nicht zugestellt,
|
|
||||||
// kein Fehler.
|
|
||||||
func EnqueueIfAllowed(
|
|
||||||
ctx context.Context,
|
|
||||||
prefs *Store,
|
|
||||||
dispatcher *notify.Dispatcher,
|
|
||||||
tenantSlug, userID, eventType, channel, recipient string,
|
|
||||||
payload map[string]any,
|
|
||||||
) (jobID string, skipped bool, err error) {
|
|
||||||
enabled, err := prefs.IsEnabled(ctx, tenantSlug, userID, eventType, channel)
|
|
||||||
if err != nil {
|
|
||||||
return "", false, err
|
|
||||||
}
|
|
||||||
if !enabled {
|
|
||||||
return "", true, nil
|
|
||||||
}
|
|
||||||
jobID, err = dispatcher.Enqueue(ctx, channel, recipient, payload)
|
|
||||||
return jobID, false, err
|
|
||||||
}
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
package notifyprefs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/notify"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*Store, *notify.Dispatcher, *pgxpool.Pool, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS notification_preferences (
|
|
||||||
tenant_slug TEXT NOT NULL, user_id TEXT NOT NULL, event_type TEXT NOT NULL, channel TEXT NOT NULL,
|
|
||||||
enabled BOOLEAN NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (tenant_slug, user_id, event_type, channel)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS notification_jobs (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), channel TEXT NOT NULL, recipient TEXT NOT NULL,
|
|
||||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb, status TEXT NOT NULL DEFAULT 'pending', attempts INT NOT NULL DEFAULT 0,
|
|
||||||
max_attempts INT NOT NULL DEFAULT 5, next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), last_error TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() {
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM notification_preferences`)
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM notification_jobs`)
|
|
||||||
pool.Close()
|
|
||||||
}
|
|
||||||
return NewStore(pool), notify.NewDispatcher(pool), pool, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ohne explizite Praeferenz gilt ein Kanal als aktiviert (Opt-out-Default).
|
|
||||||
func TestIsEnabled_DefaultsToTrueWithoutPreference(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
enabled, err := prefs.IsEnabled(ctx, "acme", "user-1", "welcome", "email")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is enabled: %v", err)
|
|
||||||
}
|
|
||||||
if !enabled {
|
|
||||||
t.Fatal("erwartet aktiviert als default ohne gesetzte praeferenz")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + 2: gesetzte Praeferenz wirkt sofort.
|
|
||||||
func TestSetAndIsEnabled(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := prefs.Set(ctx, "acme", "user-1", "welcome", "email", false); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
enabled, err := prefs.IsEnabled(ctx, "acme", "user-1", "welcome", "email")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is enabled: %v", err)
|
|
||||||
}
|
|
||||||
if enabled {
|
|
||||||
t.Fatal("erwartet deaktiviert nach Set(..., false)")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Andere Kanaele/Ereignistypen desselben Benutzers bleiben unberuehrt.
|
|
||||||
stillOn, err := prefs.IsEnabled(ctx, "acme", "user-1", "welcome", "in_app")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is enabled (anderer kanal): %v", err)
|
|
||||||
}
|
|
||||||
if !stillOn {
|
|
||||||
t.Fatal("erwartet: anderer kanal bleibt aktiviert")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 / Pruefung 2: Einstellungen eines Benutzers wirken
|
|
||||||
// sich NICHT auf einen anderen Benutzer aus.
|
|
||||||
func TestSet_DoesNotAffectOtherUser(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := prefs.Set(ctx, "acme", "user-1", "welcome", "email", false); err != nil {
|
|
||||||
t.Fatalf("set fuer user-1: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
enabledForOther, err := prefs.IsEnabled(ctx, "acme", "user-2", "welcome", "email")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is enabled fuer user-2: %v", err)
|
|
||||||
}
|
|
||||||
if !enabledForOther {
|
|
||||||
t.Fatal("praeferenz von user-1 haette user-2 nicht beeinflussen duerfen")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 / Pruefung 1 (Kernbeweis): ein deaktivierter Kanal
|
|
||||||
// erhaelt NACHWEISLICH keine weitere Zustellung — geprueft ueber die
|
|
||||||
// tatsaechliche notification_jobs-Tabelle, nicht nur ueber den Rueckgabewert.
|
|
||||||
func TestEnqueueIfAllowed_SkipsWhenDisabled(t *testing.T) {
|
|
||||||
prefs, dispatcher, pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := prefs.Set(ctx, "acme", "user-1", "invoice_ready", "email", false); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
jobID, skipped, err := EnqueueIfAllowed(ctx, prefs, dispatcher, "acme", "user-1", "invoice_ready", "email", "user1@acme.example", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue if allowed: %v", err)
|
|
||||||
}
|
|
||||||
if !skipped {
|
|
||||||
t.Fatal("erwartet skipped=true bei deaktiviertem kanal")
|
|
||||||
}
|
|
||||||
if jobID != "" {
|
|
||||||
t.Fatalf("erwartet keine job-id, habe %q", jobID)
|
|
||||||
}
|
|
||||||
|
|
||||||
var count int
|
|
||||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM notification_jobs`).Scan(&count); err != nil {
|
|
||||||
t.Fatalf("notification_jobs zaehlen: %v", err)
|
|
||||||
}
|
|
||||||
if count != 0 {
|
|
||||||
t.Fatalf("erwartet 0 eingereihte jobs bei deaktiviertem kanal, habe %d", count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEnqueueIfAllowed_EnqueuesWhenEnabled(t *testing.T) {
|
|
||||||
prefs, dispatcher, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
jobID, skipped, err := EnqueueIfAllowed(ctx, prefs, dispatcher, "acme", "user-1", "invoice_ready", "email", "user1@acme.example", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue if allowed: %v", err)
|
|
||||||
}
|
|
||||||
if skipped {
|
|
||||||
t.Fatal("erwartet skipped=false ohne deaktivierte praeferenz")
|
|
||||||
}
|
|
||||||
if jobID == "" {
|
|
||||||
t.Fatal("erwartet gesetzte job-id")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: Tenant-Admin-Übersicht zeigt alle Benutzer.
|
|
||||||
func TestListForTenant_ShowsAllUsers(t *testing.T) {
|
|
||||||
prefs, _, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := prefs.Set(ctx, "acme", "user-1", "welcome", "email", false); err != nil {
|
|
||||||
t.Fatalf("set user-1: %v", err)
|
|
||||||
}
|
|
||||||
if err := prefs.Set(ctx, "acme", "user-2", "welcome", "in_app", false); err != nil {
|
|
||||||
t.Fatalf("set user-2: %v", err)
|
|
||||||
}
|
|
||||||
if err := prefs.Set(ctx, "other-tenant", "user-3", "welcome", "email", false); err != nil {
|
|
||||||
t.Fatalf("set user-3 (anderer tenant): %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
overview, err := prefs.ListForTenant(ctx, "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list for tenant: %v", err)
|
|
||||||
}
|
|
||||||
if len(overview) != 2 {
|
|
||||||
t.Fatalf("erwartet 2 eintraege fuer tenant acme (nicht den anderen tenant), habe %d", len(overview))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler stellt die CRUD-API fuer Benutzerkonten bereit (IAM-01-Auftrag).
|
|
||||||
// Auth/Sessions (IAM-02) und Rollen (RBAC-01) sind ausdruecklich nicht Teil
|
|
||||||
// dieser Kachel und daher hier noch nicht angebunden.
|
|
||||||
type Handler struct {
|
|
||||||
users *TenantUserStore
|
|
||||||
superadmins *SuperadminStore
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(users *TenantUserStore, superadmins *SuperadminStore) *Handler {
|
|
||||||
return &Handler{users: users, superadmins: superadmins}
|
|
||||||
}
|
|
||||||
|
|
||||||
type createUserRequest struct {
|
|
||||||
Email string `json:"email"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createUserRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := h.users.Create(r.Context(), req.Email, req.Name)
|
|
||||||
writeUserResult(w, u, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSuperadmin legt ein mandantenuebergreifendes Superadmin-Konto an —
|
|
||||||
// bewusst ein eigener Endpunkt statt eines Tenant-Parameters mit Null-Wert.
|
|
||||||
func (h *Handler) CreateSuperadmin(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createUserRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := h.superadmins.Create(r.Context(), req.Email, req.Name)
|
|
||||||
writeUserResult(w, u, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeUserResult(w http.ResponseWriter, u User, err error) {
|
|
||||||
if err != nil {
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, ErrInvalidEmail), errors.Is(err, ErrEmailTaken):
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
case errors.Is(err, ErrNotFound):
|
|
||||||
http.Error(w, err.Error(), http.StatusNotFound)
|
|
||||||
default:
|
|
||||||
http.Error(w, "benutzer konnte nicht verarbeitet werden", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
_ = json.NewEncoder(w).Encode(u)
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setupTestDB legt eine frische, isolierte Testdatenbank an, wendet die
|
|
||||||
// uebergebene Migration an und liefert einen verbundenen Pool. Wird ohne
|
|
||||||
// TEST_ADMIN_DSN uebersprungen — siehe internal/tenant/provisioner_test.go
|
|
||||||
// fuer dasselbe Muster.
|
|
||||||
func setupTestDB(t *testing.T, dbName, schemaSQL string) *pgxpool.Pool {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("admin pool: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
if _, err := adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
|
||||||
t.Fatalf("testdatenbank anlegen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dsn := strings.Replace(adminDSN, "/postgres?", "/"+dbName+"?", 1)
|
|
||||||
pool, err := pgxpool.New(ctx, dsn)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("connect testdatenbank: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := pool.Exec(ctx, schemaSQL); err != nil {
|
|
||||||
t.Fatalf("schema anwenden: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
pool.Close()
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
adminPool.Close()
|
|
||||||
})
|
|
||||||
|
|
||||||
return pool
|
|
||||||
}
|
|
||||||
|
|
||||||
const usersSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
const superadminsSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE superadmins (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + 3, Pruefung 1 (inkl. Negativfall doppelte E-Mail).
|
|
||||||
func TestTenantUserStore_CRUD(t *testing.T) {
|
|
||||||
pool := setupTestDB(t, "test_iam01_users", usersSchema)
|
|
||||||
store := NewTenantUserStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
created, err := store.Create(ctx, "alice@example.com", "Alice")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create: %v", err)
|
|
||||||
}
|
|
||||||
if created.Status != StatusActive {
|
|
||||||
t.Fatalf("erwartet status active, hat %q", created.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Email != "alice@example.com" {
|
|
||||||
t.Fatalf("get email = %q", got.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
updated, err := store.Update(ctx, created.ID, "", "Alice A.")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("update: %v", err)
|
|
||||||
}
|
|
||||||
if updated.Name != "Alice A." || updated.Email != "alice@example.com" {
|
|
||||||
t.Fatalf("update ergebnis unerwartet: %+v", updated)
|
|
||||||
}
|
|
||||||
|
|
||||||
list, err := store.List(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list: %v", err)
|
|
||||||
}
|
|
||||||
if len(list) != 1 {
|
|
||||||
t.Fatalf("erwartet 1 benutzer, habe %d", len(list))
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivated, err := store.Deactivate(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deactivate: %v", err)
|
|
||||||
}
|
|
||||||
if deactivated.Status != StatusInactive {
|
|
||||||
t.Fatalf("erwartet status inactive, hat %q", deactivated.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Negativfall: doppelte E-Mail-Adresse.
|
|
||||||
if _, err := store.Create(ctx, "second@example.com", "Bob"); err != nil {
|
|
||||||
t.Fatalf("create second: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := store.Create(ctx, "second@example.com", "Bob Zwei"); !errors.Is(err, ErrEmailTaken) {
|
|
||||||
t.Fatalf("erwartet ErrEmailTaken, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Negativfall: fehlender Benutzer.
|
|
||||||
if _, err := store.Get(ctx, created.ID+"-nicht-vorhanden"); err == nil {
|
|
||||||
t.Fatalf("erwartet fehler bei unbekannter/ungueltiger id")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: Superadmin-Anlage ohne Tenant-Kontext.
|
|
||||||
// SuperadminStore.Create hat keinen Tenant-Parameter — es gibt syntaktisch
|
|
||||||
// keine Moeglichkeit, hier versehentlich einen Tenant-Sonderfall zu vergessen.
|
|
||||||
func TestSuperadminStore_CreateWithoutTenantContext(t *testing.T) {
|
|
||||||
pool := setupTestDB(t, "test_iam01_superadmins", superadminsSchema)
|
|
||||||
store := NewSuperadminStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
created, err := store.Create(ctx, "root@nexarch.internal", "Root")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create superadmin: %v", err)
|
|
||||||
}
|
|
||||||
if created.Status != StatusActive {
|
|
||||||
t.Fatalf("erwartet status active, hat %q", created.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Email != "root@nexarch.internal" {
|
|
||||||
t.Fatalf("get email = %q", got.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := store.Create(ctx, "root@nexarch.internal", "Root Zwei"); !errors.Is(err, ErrEmailTaken) {
|
|
||||||
t.Fatalf("erwartet ErrEmailTaken (globale eindeutigkeit), habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivated, err := store.Deactivate(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deactivate: %v", err)
|
|
||||||
}
|
|
||||||
if deactivated.Status != StatusInactive {
|
|
||||||
t.Fatalf("erwartet status inactive, hat %q", deactivated.Status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SuperadminStore verwaltet mandantenuebergreifende Superadmin-Konten in der
|
|
||||||
// Control-Plane-Registry (siehe internal/tenant.Registry). Superadmin-ohne-
|
|
||||||
// Tenant ist dadurch ein eigener Typ statt eines Sonderfalls von User/
|
|
||||||
// TenantUserStore — es gibt keinen Tenant-Parameter, den man weglassen
|
|
||||||
// koennte (IAM-01, "ohne Sonderbehandlung im Code").
|
|
||||||
type SuperadminStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSuperadminStore(pool *pgxpool.Pool) *SuperadminStore {
|
|
||||||
return &SuperadminStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Create(ctx context.Context, email, name string) (User, error) {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var u User
|
|
||||||
u.Email, u.Name, u.Status = email, name, StatusActive
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO superadmins (email, name, status)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at, updated_at
|
|
||||||
`, u.Email, u.Name, u.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Get(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM superadmins WHERE id = $1
|
|
||||||
`, id))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) List(ctx context.Context) ([]User, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM superadmins ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("superadmins auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []User
|
|
||||||
for rows.Next() {
|
|
||||||
var u User
|
|
||||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("superadmin lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, u)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Deactivate(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE superadmins SET status = $2, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, StatusInactive))
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TenantUserStore verwaltet Benutzer innerhalb GENAU EINER Tenant-Datenbank.
|
|
||||||
// Welcher Mandant gemeint ist, ergibt sich ausschliesslich aus dem
|
|
||||||
// uebergebenen Pool — es gibt keine tenant_id-Spalte (siehe migrations/tenant/0001_users.up.sql).
|
|
||||||
type TenantUserStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTenantUserStore(pool *pgxpool.Pool) *TenantUserStore {
|
|
||||||
return &TenantUserStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) Create(ctx context.Context, email, name string) (User, error) {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var u User
|
|
||||||
u.Email, u.Name, u.Status = email, name, StatusActive
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO users (email, name, status)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at, updated_at
|
|
||||||
`, u.Email, u.Name, u.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) Get(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM users WHERE id = $1
|
|
||||||
`, id))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) List(ctx context.Context) ([]User, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM users ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("benutzer auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []User
|
|
||||||
for rows.Next() {
|
|
||||||
var u User
|
|
||||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("benutzer lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, u)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update aendert Name und E-Mail. Eine leere email/name laesst das jeweilige
|
|
||||||
// Feld unveraendert.
|
|
||||||
func (s *TenantUserStore) Update(ctx context.Context, id, email, name string) (User, error) {
|
|
||||||
if email != "" {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE users
|
|
||||||
SET email = COALESCE(NULLIF($2, ''), email),
|
|
||||||
name = COALESCE(NULLIF($3, ''), name),
|
|
||||||
updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, email, name)
|
|
||||||
|
|
||||||
u, err := scanUser(row)
|
|
||||||
if err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deactivate setzt den Benutzer auf inaktiv statt ihn zu loeschen.
|
|
||||||
func (s *TenantUserStore) Deactivate(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE users SET status = $2, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, StatusInactive))
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPasswordHash schreibt einen bereits berechneten bcrypt-Hash (siehe
|
|
||||||
// internal/auth, IAM-02). Der Store selbst kennt kein Klartext-Passwort.
|
|
||||||
func (s *TenantUserStore) SetPasswordHash(ctx context.Context, id, hash string) error {
|
|
||||||
tag, err := s.pool.Exec(ctx, `
|
|
||||||
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1
|
|
||||||
`, id, hash)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("passwort setzen: %w", err)
|
|
||||||
}
|
|
||||||
if tag.RowsAffected() == 0 {
|
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuthCredentials wird ausschliesslich fuer den Login-Pfad (internal/auth)
|
|
||||||
// verwendet und traegt bewusst den password_hash, damit er nicht ueber den
|
|
||||||
// regulaeren User-Typ/JSON-Serialisierungspfad nach aussen dringen kann.
|
|
||||||
type AuthCredentials struct {
|
|
||||||
User User
|
|
||||||
PasswordHash string
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetByEmailForAuth liefert Benutzer + Passwort-Hash zu einer E-Mail-Adresse
|
|
||||||
// aus GENAU DIESER Tenant-Datenbank — der Tenant-Scope ergibt sich damit
|
|
||||||
// zwingend aus dem verwendeten Pool, es gibt keine Moeglichkeit, versehentlich
|
|
||||||
// ueber Tenant-Grenzen hinweg zu suchen (bekannter archivmail-Fehler, siehe
|
|
||||||
// IAM-02 "Bekannte Fehler vermeiden").
|
|
||||||
func (s *TenantUserStore) GetByEmailForAuth(ctx context.Context, email string) (AuthCredentials, error) {
|
|
||||||
var c AuthCredentials
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at, password_hash
|
|
||||||
FROM users WHERE email = $1
|
|
||||||
`, email)
|
|
||||||
|
|
||||||
if err := row.Scan(&c.User.ID, &c.User.Email, &c.User.Name, &c.User.Status,
|
|
||||||
&c.User.CreatedAt, &c.User.UpdatedAt, &c.PasswordHash); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return AuthCredentials{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return AuthCredentials{}, fmt.Errorf("anmeldedaten lesen: %w", err)
|
|
||||||
}
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanUser(row pgx.Row) (User, error) {
|
|
||||||
var u User
|
|
||||||
if err := row.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return User{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return User{}, fmt.Errorf("benutzer lesen: %w", err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// mapWriteErr uebersetzt den Unique-Constraint-Verstoss der E-Mail-Spalte in
|
|
||||||
// einen sprechenden Fehler statt der rohen Postgres-Fehlermeldung.
|
|
||||||
func mapWriteErr(err error) error {
|
|
||||||
var pgErr *pgconn.PgError
|
|
||||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
||||||
return ErrEmailTaken
|
|
||||||
}
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
return fmt.Errorf("benutzer schreiben: %w", err)
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
// Package user implementiert Core IAM-01: das Benutzer-Datenmodell und die
|
|
||||||
// CRUD-Operationen. Tenant-Zugehoerigkeit ist ueber die Zieldatenbank
|
|
||||||
// gegeben (Modell C, siehe internal/tenant) — Superadmin-Konten leben
|
|
||||||
// dagegen mandantenuebergreifend in der Registry und sind ueber
|
|
||||||
// SuperadminStore als eigener, First-Class-Typ modelliert, nicht als
|
|
||||||
// tenant_id-NULL-Sonderfall in User.
|
|
||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"regexp"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Status string
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatusActive Status = "active"
|
|
||||||
StatusInactive Status = "inactive"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID string
|
|
||||||
Email string
|
|
||||||
Name string
|
|
||||||
Status Status
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
var emailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
|
||||||
|
|
||||||
var ErrInvalidEmail = errors.New("user: ungueltige E-Mail-Adresse")
|
|
||||||
var ErrEmailTaken = errors.New("user: E-Mail-Adresse bereits vergeben")
|
|
||||||
var ErrNotFound = errors.New("user: nicht gefunden")
|
|
||||||
|
|
||||||
func ValidateEmail(email string) error {
|
|
||||||
if !emailPattern.MatchString(email) {
|
|
||||||
return ErrInvalidEmail
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestValidateEmail(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
email string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"a@b.de", false},
|
|
||||||
{"a.b+c@sub.example.com", false},
|
|
||||||
{"", true},
|
|
||||||
{"keine-email", true},
|
|
||||||
{"a@b", true},
|
|
||||||
{"@b.de", true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range cases {
|
|
||||||
err := ValidateEmail(c.email)
|
|
||||||
if (err != nil) != c.wantErr {
|
|
||||||
t.Errorf("ValidateEmail(%q) error = %v, wantErr %v", c.email, err, c.wantErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS superadmins;
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
-- Superadmin-Konten arbeiten mandantenuebergreifend und leben deshalb in der
|
|
||||||
-- Control-Plane-Registry (siehe TEN-01), nicht in einer Tenant-Datenbank.
|
|
||||||
-- Das bildet "Superadmin ohne Tenant" strukturell als First-Class-Zustand ab,
|
|
||||||
-- statt ihn als Sonderfall in der Tenant-users-Tabelle zu behandeln
|
|
||||||
-- (IAM-01, siehe core-kanban/tickets/IAM-01.md — bekannte Fehler vermeiden).
|
|
||||||
-- E-Mail-Eindeutigkeit ist hier global, da die Registry-DB einmalig existiert.
|
|
||||||
CREATE TABLE superadmins (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS config_value_history;
|
|
||||||
DROP TABLE IF EXISTS config_values;
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
-- Zentraler Konfigurationsdienst (CFG-01, siehe core-kanban/tickets/CFG-01.md).
|
|
||||||
-- scope = 'global' fuer globale Defaults, sonst der Tenant-Slug. config_values
|
|
||||||
-- haelt den AKTUELLEN Stand je (key, scope); config_value_history haelt JEDE
|
|
||||||
-- Aenderung fest (Akzeptanzkriterium 2: versioniert nachvollziehbar).
|
|
||||||
CREATE TABLE config_values (
|
|
||||||
key TEXT NOT NULL,
|
|
||||||
scope TEXT NOT NULL CHECK (scope <> ''),
|
|
||||||
value TEXT NOT NULL,
|
|
||||||
version INT NOT NULL,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (key, scope)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE config_value_history (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
key TEXT NOT NULL,
|
|
||||||
scope TEXT NOT NULL,
|
|
||||||
value TEXT NOT NULL,
|
|
||||||
version INT NOT NULL,
|
|
||||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX config_value_history_key_scope_idx ON config_value_history (key, scope, version);
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS tenant_licenses;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- Lizenzumfang pro Mandant (LIC-01, siehe core-kanban/tickets/LIC-01.md).
|
||||||
|
-- Genau ein Lizenzdatensatz pro Tenant (tenant_id PK) — ein neues Einspielen
|
||||||
|
-- ersetzt den vorherigen Datensatz vollstaendig statt eine Historie zu fuehren.
|
||||||
|
CREATE TABLE tenant_licenses (
|
||||||
|
tenant_id UUID PRIMARY KEY REFERENCES tenants(id),
|
||||||
|
plan TEXT NOT NULL,
|
||||||
|
modules TEXT[] NOT NULL,
|
||||||
|
issued_at TIMESTAMPTZ NOT NULL,
|
||||||
|
valid_until TIMESTAMPTZ NOT NULL,
|
||||||
|
raw_key TEXT NOT NULL,
|
||||||
|
installed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS notification_jobs;
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
-- Benachrichtigungs-Dispatcher-Warteschlange (CFG-02, siehe
|
|
||||||
-- core-kanban/tickets/CFG-02.md). Postgres-basiert statt Redis/AMQP
|
|
||||||
-- (Projekt-Konvention, siehe nexarch-state.json techstack.job_queue) —
|
|
||||||
-- Zeilen ueberleben einen Neustart des Dispatcher-Prozesses unveraendert
|
|
||||||
-- (Akzeptanzkriterium 3).
|
|
||||||
CREATE TABLE notification_jobs (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
channel TEXT NOT NULL,
|
|
||||||
recipient TEXT NOT NULL,
|
|
||||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
||||||
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
|
|
||||||
attempts INT NOT NULL DEFAULT 0,
|
|
||||||
max_attempts INT NOT NULL DEFAULT 5,
|
|
||||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
last_error TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX notification_jobs_due_idx ON notification_jobs (status, next_attempt_at);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS in_app_notifications;
|
|
||||||
DROP TABLE IF EXISTS notification_templates;
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
-- Benachrichtigungs-Kanaele: Vorlagen (E-Mail) + In-App-Nachrichten
|
|
||||||
-- (CFG-03, siehe core-kanban/tickets/CFG-03.md). Beide leben in der
|
|
||||||
-- Registry-DB, analog zu feature_flags/config_values — modulübergreifende
|
|
||||||
-- Konfiguration/UI-Zustand, keine Mandanten-Geschaeftsdaten.
|
|
||||||
|
|
||||||
-- tenant_slug = 'global' ist der Fallback-Wert, wenn ein Tenant keine
|
|
||||||
-- eigene Vorlage gesetzt hat (Akzeptanzkriterium 3: Vorlagen pro Tenant
|
|
||||||
-- anpassbar, mit sinnvollem Default).
|
|
||||||
CREATE TABLE notification_templates (
|
|
||||||
tenant_slug TEXT NOT NULL,
|
|
||||||
key TEXT NOT NULL,
|
|
||||||
subject TEXT NOT NULL,
|
|
||||||
body TEXT NOT NULL,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (tenant_slug, key)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE in_app_notifications (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
tenant_slug TEXT NOT NULL,
|
|
||||||
user_id TEXT NOT NULL,
|
|
||||||
title TEXT NOT NULL,
|
|
||||||
body TEXT NOT NULL,
|
|
||||||
read_at TIMESTAMPTZ,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX in_app_notifications_user_idx ON in_app_notifications (tenant_slug, user_id, created_at);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE notification_preferences;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
-- CFG-04: Benachrichtigungspraeferenzen je Benutzer, Ereignistyp und Kanal.
|
|
||||||
-- Lebt wie notification_templates/in_app_notifications (CFG-03) in der
|
|
||||||
-- Registry-DB — modulübergreifende Konfiguration, keine Mandanten-Geschaeftsdaten.
|
|
||||||
--
|
|
||||||
-- Kein Row = aktiviert (Opt-out-Modell): ein Benutzer verpasst nichts, bis er
|
|
||||||
-- aktiv einen Kanal/Ereignistyp abschaltet — sicherer Default als Opt-in.
|
|
||||||
CREATE TABLE notification_preferences (
|
|
||||||
tenant_slug TEXT NOT NULL,
|
|
||||||
user_id TEXT NOT NULL,
|
|
||||||
event_type TEXT NOT NULL,
|
|
||||||
channel TEXT NOT NULL,
|
|
||||||
enabled BOOLEAN NOT NULL,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (tenant_slug, user_id, event_type, channel)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX notification_preferences_tenant_idx ON notification_preferences (tenant_slug);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS users;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
-- Benutzer-Datenmodell (IAM-01, siehe core-kanban/tickets/IAM-01.md).
|
|
||||||
-- Diese Migration laeuft in der DB EINES Mandanten (Modell C, siehe TEN-01) —
|
|
||||||
-- die Tenant-Zugehoerigkeit ist implizit durch die Datenbankverbindung
|
|
||||||
-- gegeben, es gibt daher bewusst KEINE tenant_id-Spalte.
|
|
||||||
-- E-Mail-Eindeutigkeit ist hier tenant-scoped: der UNIQUE-Constraint gilt
|
|
||||||
-- nur innerhalb dieser einen Tenant-Datenbank.
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users DROP COLUMN password_hash;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
-- Passwort-Hash-Spalte fuer Login (IAM-02, siehe core-kanban/tickets/IAM-02.md).
|
|
||||||
-- Enthaelt AUSSCHLIESSLICH den bcrypt-Hash, niemals das Klartext-Passwort.
|
|
||||||
ALTER TABLE users ADD COLUMN password_hash TEXT NOT NULL DEFAULT '';
|
|
||||||
@@ -1,11 +1,23 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
# Setzt die nexarch-Testumgebung zurueck: loescht die geteilte
|
||||||
|
# Registry-Tabelle "tenants" in der postgres-Wartungsdatenbank sowie alle
|
||||||
|
# tenant_*-Datenbanken. Noetig, weil verschiedene Feature-Branches
|
||||||
|
# unterschiedliche Registry-Schemata erwarten, aber dieselbe physische
|
||||||
|
# Postgres-Instanz auf dem Testhost teilen (siehe [[project-nexarch-test-infra]]).
|
||||||
|
#
|
||||||
|
# Aufruf: NEXARCH_TEST_DB_PASSWORD=... ./scripts/reset-test-env.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||||
ROLE="nexarch_test"
|
ROLE="nexarch_test"
|
||||||
|
|
||||||
export PGPASSWORD="$PASS"
|
export PGPASSWORD="$PASS"
|
||||||
|
|
||||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS tenants CASCADE;"
|
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS tenants CASCADE;"
|
||||||
|
|
||||||
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
||||||
for db in $dbs; do
|
for db in $dbs; do
|
||||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
||||||
done
|
done
|
||||||
|
|
||||||
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
||||||
|
|||||||
@@ -1,12 +1,24 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
# Ein-Kommando-Pruefung fuer den aktuellen Code-Stand auf dem Testhost:
|
||||||
|
# Registry+Tenant-DBs zuruecksetzen, dann build/vet/test in einem Rutsch.
|
||||||
|
# -p 1 ist Pflicht, da mehrere Pakete dieselbe physische Registry-Tabelle auf
|
||||||
|
# dem Testhost teilen (siehe [[project-nexarch-test-infra]]).
|
||||||
|
#
|
||||||
|
# Aufruf: NEXARCH_TEST_DB_PASSWORD=... ./scripts/run-checks.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
NEXARCH_TEST_DB_PASSWORD="$PASS" bash scripts/reset-test-env.sh
|
NEXARCH_TEST_DB_PASSWORD="$PASS" bash scripts/reset-test-env.sh
|
||||||
|
|
||||||
export TEST_ADMIN_DSN="postgresql://nexarch_test:${PASS}@localhost:5432/postgres?sslmode=disable"
|
export TEST_ADMIN_DSN="postgresql://nexarch_test:${PASS}@localhost:5432/postgres?sslmode=disable"
|
||||||
|
|
||||||
echo "== go build =="
|
echo "== go build =="
|
||||||
go build ./...
|
go build ./...
|
||||||
|
|
||||||
echo "== go vet =="
|
echo "== go vet =="
|
||||||
go vet ./...
|
go vet ./...
|
||||||
|
|
||||||
echo "== go test (-p 1) =="
|
echo "== go test (-p 1) =="
|
||||||
go test ./... -p 1 -count=1
|
go test ./... -p 1 -count=1
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
import { ThemeProvider, I18nProvider, ToastProvider, typography } from "@nexarch/shl";
|
|
||||||
|
|
||||||
export const metadata = {
|
|
||||||
title: "NEXARCH Benachrichtigungen",
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function RootLayout({
|
|
||||||
children,
|
|
||||||
}: {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<html lang="de">
|
|
||||||
<body
|
|
||||||
style={{
|
|
||||||
fontFamily: typography.fontFamily,
|
|
||||||
margin: 0,
|
|
||||||
background: "var(--shl-color-background, #ffffff)",
|
|
||||||
color: "var(--shl-color-text-primary, #14181f)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ThemeProvider>
|
|
||||||
<I18nProvider initialLocale="de">
|
|
||||||
<ToastProvider>{children}</ToastProvider>
|
|
||||||
</I18nProvider>
|
|
||||||
</ThemeProvider>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Table } from "@nexarch/shl";
|
|
||||||
import type { TableColumn } from "@nexarch/shl";
|
|
||||||
import { Preference, fetchTenantOverview } from "../../lib/api";
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: Tenant-Admin sieht eine Übersicht der
|
|
||||||
// Benachrichtigungs-Konfiguration seines Tenants. Zugriffsbeschränkung
|
|
||||||
// (nur Tenant-Admin) ist RBAC-02s Aufgabe vor diesem Endpunkt, siehe
|
|
||||||
// internal/notifyprefs/handler.go.
|
|
||||||
export default function OverviewPage() {
|
|
||||||
const [prefs, setPrefs] = useState<Preference[] | null>(null);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchTenantOverview()
|
|
||||||
.then(setPrefs)
|
|
||||||
.catch(() => setError("Übersicht konnte nicht geladen werden. Nur Tenant-Admins haben Zugriff."));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const columns: TableColumn<Preference>[] = [
|
|
||||||
{ key: "user", header: "Benutzer-ID", render: (p) => p.UserID },
|
|
||||||
{ key: "event", header: "Ereignistyp", render: (p) => p.EventType },
|
|
||||||
{ key: "channel", header: "Kanal", render: (p) => p.Channel },
|
|
||||||
{ key: "enabled", header: "Aktiviert", render: (p) => (p.Enabled ? "Ja" : "Nein") },
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main style={{ maxWidth: 800, margin: "40px auto", padding: "0 16px" }}>
|
|
||||||
<h1>Benachrichtigungs-Übersicht (Mandant)</h1>
|
|
||||||
{error && <p role="alert">{error}</p>}
|
|
||||||
{prefs && (
|
|
||||||
<Table
|
|
||||||
columns={columns}
|
|
||||||
rows={prefs}
|
|
||||||
rowKey={(p) => `${p.UserID}-${p.EventType}-${p.Channel}`}
|
|
||||||
caption="Von der Standardeinstellung abweichende Benachrichtigungspräferenzen aller Benutzer"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
import { redirect } from "next/navigation";
|
|
||||||
|
|
||||||
export default function IndexPage() {
|
|
||||||
redirect("/settings");
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { CheckboxField, useToast } from "@nexarch/shl";
|
|
||||||
import {
|
|
||||||
ApiError,
|
|
||||||
KNOWN_CHANNELS,
|
|
||||||
KNOWN_EVENT_TYPES,
|
|
||||||
Preference,
|
|
||||||
fetchMyPreferences,
|
|
||||||
setPreference,
|
|
||||||
} from "../../lib/api";
|
|
||||||
|
|
||||||
const EVENT_LABELS: Record<string, string> = {
|
|
||||||
welcome: "Willkommen",
|
|
||||||
invoice_ready: "Rechnung verfügbar",
|
|
||||||
password_reset: "Passwort-Zurücksetzung",
|
|
||||||
security_alert: "Sicherheitshinweis",
|
|
||||||
};
|
|
||||||
|
|
||||||
const CHANNEL_LABELS: Record<string, string> = {
|
|
||||||
email: "E-Mail",
|
|
||||||
in_app: "In-App",
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function SettingsPage() {
|
|
||||||
const { push } = useToast();
|
|
||||||
const [prefs, setPrefs] = useState<Preference[] | null>(null);
|
|
||||||
const [loadError, setLoadError] = useState<string | null>(null);
|
|
||||||
const [pending, setPending] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchMyPreferences()
|
|
||||||
.then(setPrefs)
|
|
||||||
.catch(() => setLoadError("Einstellungen konnten nicht geladen werden. Bitte melden Sie sich an."));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Default: aktiviert, solange keine explizite Praeferenz existiert
|
|
||||||
// (Akzeptanzkriterium 1) — gleicher Opt-out-Default wie im Backend.
|
|
||||||
function isEnabled(eventType: string, channel: string): boolean {
|
|
||||||
const explicit = prefs?.find((p) => p.EventType === eventType && p.Channel === channel);
|
|
||||||
return explicit ? explicit.Enabled : true;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onToggle(eventType: string, channel: string, nextEnabled: boolean) {
|
|
||||||
const key = `${eventType}:${channel}`;
|
|
||||||
setPending(key);
|
|
||||||
try {
|
|
||||||
// Akzeptanzkriterium 2: sofort speichern, kein Sammel-Speichern-Button —
|
|
||||||
// wirkt unmittelbar auf künftige Zustellungen (EnqueueIfAllowed prüft
|
|
||||||
// bei jedem Aufruf live, kein Cache dazwischen).
|
|
||||||
await setPreference(eventType, channel, nextEnabled);
|
|
||||||
setPrefs((current) => {
|
|
||||||
const withoutThis = (current ?? []).filter((p) => !(p.EventType === eventType && p.Channel === channel));
|
|
||||||
return [...withoutThis, { TenantSlug: "", UserID: "", EventType: eventType, Channel: channel, Enabled: nextEnabled }];
|
|
||||||
});
|
|
||||||
push(nextEnabled ? "Benachrichtigung aktiviert." : "Benachrichtigung deaktiviert.", "success");
|
|
||||||
} catch (err) {
|
|
||||||
push(err instanceof ApiError ? err.message : "Einstellung konnte nicht gespeichert werden.", "danger");
|
|
||||||
} finally {
|
|
||||||
setPending(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loadError) {
|
|
||||||
return (
|
|
||||||
<main style={{ maxWidth: 640, margin: "40px auto", padding: "0 16px" }}>
|
|
||||||
<p role="alert">{loadError}</p>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main style={{ maxWidth: 640, margin: "40px auto", padding: "0 16px" }}>
|
|
||||||
<h1>Benachrichtigungseinstellungen</h1>
|
|
||||||
<p>Wählen Sie je Ereignis, über welche Kanäle Sie benachrichtigt werden möchten.</p>
|
|
||||||
|
|
||||||
{KNOWN_EVENT_TYPES.map((eventType) => (
|
|
||||||
<fieldset key={eventType} style={{ marginBottom: 16 }}>
|
|
||||||
<legend>{EVENT_LABELS[eventType] ?? eventType}</legend>
|
|
||||||
{KNOWN_CHANNELS.map((channel) => {
|
|
||||||
const key = `${eventType}:${channel}`;
|
|
||||||
return (
|
|
||||||
<CheckboxField
|
|
||||||
key={key}
|
|
||||||
label={CHANNEL_LABELS[channel] ?? channel}
|
|
||||||
checked={isEnabled(eventType, channel)}
|
|
||||||
disabled={pending === key}
|
|
||||||
onChange={(e) => onToggle(eventType, channel, e.target.checked)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</fieldset>
|
|
||||||
))}
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
const API_BASE = process.env.NEXT_PUBLIC_CORE_API_BASE ?? "";
|
|
||||||
|
|
||||||
export class ApiError extends Error {}
|
|
||||||
|
|
||||||
async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
|
||||||
const res = await fetch(`${API_BASE}${path}`, {
|
|
||||||
credentials: "include",
|
|
||||||
headers: init?.body ? { "Content-Type": "application/json" } : undefined,
|
|
||||||
...init,
|
|
||||||
});
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
throw new ApiError(data.error ?? data.message ?? "Unbekannter Fehler");
|
|
||||||
}
|
|
||||||
return data as T;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Preference {
|
|
||||||
TenantSlug: string;
|
|
||||||
UserID: string;
|
|
||||||
EventType: string;
|
|
||||||
Channel: string;
|
|
||||||
Enabled: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bekannte Ereignistypen/Kanäle — das Backend erzwingt keine feste Liste
|
|
||||||
// (jedes Modul kann eigene event_type-Werte an EnqueueIfAllowed übergeben),
|
|
||||||
// diese Liste ist der aktuell bekannte Stand fürs Frontend-Formular.
|
|
||||||
export const KNOWN_EVENT_TYPES = ["welcome", "invoice_ready", "password_reset", "security_alert"] as const;
|
|
||||||
export const KNOWN_CHANNELS = ["email", "in_app"] as const;
|
|
||||||
|
|
||||||
export function fetchMyPreferences(): Promise<Preference[]> {
|
|
||||||
return req("/notifications/preferences");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setPreference(eventType: string, channel: string, enabled: boolean): Promise<void> {
|
|
||||||
return req("/notifications/preferences", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ event_type: eventType, channel, enabled }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function fetchTenantOverview(): Promise<Preference[]> {
|
|
||||||
return req("/notifications/preferences/tenant");
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
/** @type {import('next').NextConfig} */
|
|
||||||
const nextConfig = {
|
|
||||||
transpilePackages: ["@nexarch/shl"],
|
|
||||||
};
|
|
||||||
export default nextConfig;
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "nexarch-notifications",
|
|
||||||
"private": true,
|
|
||||||
"scripts": {
|
|
||||||
"dev": "next dev",
|
|
||||||
"build": "next build",
|
|
||||||
"start": "next start",
|
|
||||||
"lint": "next lint"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@nexarch/shl": "file:../shl",
|
|
||||||
"next": "14.2.35",
|
|
||||||
"react": "18.3.1",
|
|
||||||
"react-dom": "18.3.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "20.14.9",
|
|
||||||
"@types/react": "18.3.3",
|
|
||||||
"@types/react-dom": "18.3.0",
|
|
||||||
"typescript": "5.5.3"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2017",
|
|
||||||
"lib": ["dom", "dom.iterable", "esnext"],
|
|
||||||
"allowJs": false,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"strict": true,
|
|
||||||
"noEmit": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"module": "esnext",
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"resolveJsonModule": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"jsx": "preserve",
|
|
||||||
"incremental": true,
|
|
||||||
"plugins": [{ "name": "next" }],
|
|
||||||
"paths": { "@/*": ["./*"] }
|
|
||||||
},
|
|
||||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
|
||||||
"exclude": ["node_modules"]
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
# @nexarch/shl — UI-Shell & Design-System (Core SHL-01)
|
|
||||||
|
|
||||||
Gemeinsames Paket für alle NEXARCH-Modul-Frontends (Core, DMS, Mail, Archive, Workflow, AI, Connect).
|
|
||||||
Ein Modul-Frontend importiert ausschließlich über `index.ts`, kopiert keine Komponenten oder Tokens lokal.
|
|
||||||
|
|
||||||
## Enthält
|
|
||||||
|
|
||||||
- **Design-Tokens** (`tokens/tokens.ts`) — Farbe (Hell/Dunkel), Abstand, Typografie. Kontrastwerte gegen WCAG 2.1 AA geprüft (siehe `__tests__/tokens.test.ts`).
|
|
||||||
- **Theming** (`theme/ThemeProvider.tsx`) — zentrale Hell/Dunkel-Umschaltung, respektiert `prefers-color-scheme`, persistiert in `localStorage`.
|
|
||||||
- **i18n-Rahmen** (`i18n/i18n.tsx`) — Umschaltmechanismus Deutsch/Englisch. Modul-Frontends registrieren ihre fachlichen Textbausteine über `registerMessages()`, statt einen eigenen Mechanismus zu bauen.
|
|
||||||
- **Basis-Komponenten** (`components/`) — `Shell` (Layout + Navigation), `Table`, `Dialog`, `TextField`/`SelectField`/`CheckboxField`, `Toast`. Alle mit WCAG-2.1-AA-Grundlage (Tastaturbedienung, ARIA-Attribute, Fokus-Management).
|
|
||||||
|
|
||||||
## Verwendung in einem Modul-Frontend
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { ThemeProvider, I18nProvider, ToastProvider, Shell } from "@nexarch/shl";
|
|
||||||
|
|
||||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<ThemeProvider>
|
|
||||||
<I18nProvider initialLocale="de">
|
|
||||||
<ToastProvider>
|
|
||||||
<Shell modules={[]} tenantLabel="Mandant XY">
|
|
||||||
{children}
|
|
||||||
</Shell>
|
|
||||||
</ToastProvider>
|
|
||||||
</I18nProvider>
|
|
||||||
</ThemeProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Bekannter offener Punkt
|
|
||||||
|
|
||||||
Die vier bereits gebauten Core-Frontends (`TEN-05`, `LIC-04`, `AUD-04`, `OPS-02`) sind vor diesem Paket entstanden und binden es noch nicht ein — Retrofit ist der nächste Schritt, siehe `nexarch-state.json`.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
Ausführung auf dem Test-Host (nicht lokal, siehe Projekt-Testinfrastruktur):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install
|
|
||||||
npm test
|
|
||||||
npm run typecheck
|
|
||||||
```
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
// Prüfung: Tastaturbedienung der Basis-Komponenten funktioniert (SHL-01 Prüfung 2).
|
|
||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
import { fireEvent, render, screen } from "@testing-library/react";
|
|
||||||
import { Dialog } from "../components/Dialog";
|
|
||||||
import { I18nProvider } from "../i18n/i18n";
|
|
||||||
|
|
||||||
function renderDialog(onClose: () => void) {
|
|
||||||
return render(
|
|
||||||
<I18nProvider>
|
|
||||||
<Dialog open titleId="test-title" title="Test-Dialog" onClose={onClose}>
|
|
||||||
<button type="button">Erste Aktion</button>
|
|
||||||
<button type="button">Zweite Aktion</button>
|
|
||||||
</Dialog>
|
|
||||||
</I18nProvider>,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("Dialog: Tastaturbedienung", () => {
|
|
||||||
it("schließt sich bei ESC", () => {
|
|
||||||
const onClose = vi.fn();
|
|
||||||
renderDialog(onClose);
|
|
||||||
fireEvent.keyDown(document, { key: "Escape" });
|
|
||||||
expect(onClose).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("setzt den Fokus beim Öffnen auf das erste fokussierbare Element", () => {
|
|
||||||
renderDialog(vi.fn());
|
|
||||||
const closeButton = screen.getByRole("button", { name: /schließen/i });
|
|
||||||
expect(document.activeElement).toBe(closeButton);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ist als modaler Dialog mit Titel-Referenz ausgezeichnet", () => {
|
|
||||||
renderDialog(vi.fn());
|
|
||||||
const dialog = screen.getByRole("dialog");
|
|
||||||
expect(dialog).toHaveAttribute("aria-modal", "true");
|
|
||||||
expect(dialog).toHaveAttribute("aria-labelledby", "test-title");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
// Prüfung: Kontrastwerte erfüllen mindestens AA (SHL-01 Prüfung 3 / Akzeptanzkriterium 4).
|
|
||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import { colorTokens } from "../tokens/tokens";
|
|
||||||
|
|
||||||
// WCAG-2.1-AA-Kontrastberechnung (relative Luminanz, sRGB) — keine externe Abhängigkeit nötig.
|
|
||||||
function relLuminance(hex: string): number {
|
|
||||||
const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
|
|
||||||
const [r, g, b] = rgb.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
|
||||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
||||||
}
|
|
||||||
|
|
||||||
function contrastRatio(a: string, b: string): number {
|
|
||||||
const l1 = relLuminance(a);
|
|
||||||
const l2 = relLuminance(b);
|
|
||||||
const [lighter, darker] = l1 > l2 ? [l1, l2] : [l2, l1];
|
|
||||||
return (lighter + 0.05) / (darker + 0.05);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("Design-Tokens: WCAG 2.1 AA Kontrast", () => {
|
|
||||||
for (const scheme of ["light", "dark"] as const) {
|
|
||||||
const c = colorTokens[scheme];
|
|
||||||
|
|
||||||
it(`${scheme}: textPrimary auf background erfüllt AA (>= 4.5:1)`, () => {
|
|
||||||
expect(contrastRatio(c.textPrimary, c.background)).toBeGreaterThanOrEqual(4.5);
|
|
||||||
});
|
|
||||||
|
|
||||||
it(`${scheme}: textSecondary auf surface erfüllt AA (>= 4.5:1)`, () => {
|
|
||||||
expect(contrastRatio(c.textSecondary, c.surface)).toBeGreaterThanOrEqual(4.5);
|
|
||||||
});
|
|
||||||
|
|
||||||
it(`${scheme}: accentContrast auf accent erfüllt AA (>= 4.5:1)`, () => {
|
|
||||||
expect(contrastRatio(c.accentContrast, c.accent)).toBeGreaterThanOrEqual(4.5);
|
|
||||||
});
|
|
||||||
|
|
||||||
it(`${scheme}: dangerContrast auf danger erfüllt AA (>= 4.5:1)`, () => {
|
|
||||||
expect(contrastRatio(c.dangerContrast, c.danger)).toBeGreaterThanOrEqual(4.5);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// Dialog-Basis-Komponente — SHL-01. WCAG 2.1 AA: Fokus-Falle, ESC schließt, Tastaturbedienung vollständig.
|
|
||||||
|
|
||||||
import { useEffect, useRef } from "react";
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { useI18n } from "../i18n/i18n";
|
|
||||||
|
|
||||||
const FOCUSABLE_SELECTOR =
|
|
||||||
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
|
||||||
|
|
||||||
export interface DialogProps {
|
|
||||||
open: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
titleId: string;
|
|
||||||
title: string;
|
|
||||||
children: ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Dialog({ open, onClose, titleId, title, children }: DialogProps) {
|
|
||||||
const { t } = useI18n();
|
|
||||||
const dialogRef = useRef<HTMLDivElement>(null);
|
|
||||||
const previouslyFocused = useRef<HTMLElement | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) return;
|
|
||||||
previouslyFocused.current = document.activeElement as HTMLElement | null;
|
|
||||||
|
|
||||||
const node = dialogRef.current;
|
|
||||||
const focusables = node?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
|
|
||||||
focusables?.[0]?.focus();
|
|
||||||
|
|
||||||
function handleKeyDown(event: KeyboardEvent) {
|
|
||||||
if (event.key === "Escape") {
|
|
||||||
onClose();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (event.key !== "Tab" || !node) return;
|
|
||||||
|
|
||||||
const items = Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
|
|
||||||
if (items.length === 0) return;
|
|
||||||
const first = items[0];
|
|
||||||
const last = items[items.length - 1];
|
|
||||||
|
|
||||||
if (event.shiftKey && document.activeElement === first) {
|
|
||||||
event.preventDefault();
|
|
||||||
last.focus();
|
|
||||||
} else if (!event.shiftKey && document.activeElement === last) {
|
|
||||||
event.preventDefault();
|
|
||||||
first.focus();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener("keydown", handleKeyDown);
|
|
||||||
return () => {
|
|
||||||
document.removeEventListener("keydown", handleKeyDown);
|
|
||||||
previouslyFocused.current?.focus();
|
|
||||||
};
|
|
||||||
}, [open, onClose]);
|
|
||||||
|
|
||||||
if (!open) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="shl-dialog-backdrop"
|
|
||||||
role="presentation"
|
|
||||||
onMouseDown={(event) => {
|
|
||||||
if (event.target === event.currentTarget) onClose();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
ref={dialogRef}
|
|
||||||
className="shl-dialog"
|
|
||||||
role="dialog"
|
|
||||||
aria-modal="true"
|
|
||||||
aria-labelledby={titleId}
|
|
||||||
>
|
|
||||||
<div className="shl-dialog-header">
|
|
||||||
<h2 id={titleId}>{title}</h2>
|
|
||||||
<button type="button" onClick={onClose} aria-label={t("shl.dialog.close")}>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="shl-dialog-body">{children}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
// Formularelemente-Basis-Komponenten — SHL-01. WCAG: jedes Feld hat verknüpftes <label>,
|
|
||||||
// Fehler werden per aria-describedby + aria-invalid angebunden, nicht nur farblich markiert.
|
|
||||||
|
|
||||||
import { useId } from "react";
|
|
||||||
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from "react";
|
|
||||||
|
|
||||||
interface FieldWrapperProps {
|
|
||||||
label: string;
|
|
||||||
error?: string;
|
|
||||||
hint?: string;
|
|
||||||
children: (ids: { inputId: string; describedBy: string | undefined }) => ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
function FieldWrapper({ label, error, hint, children }: FieldWrapperProps) {
|
|
||||||
const inputId = useId();
|
|
||||||
const hintId = hint ? `${inputId}-hint` : undefined;
|
|
||||||
const errorId = error ? `${inputId}-error` : undefined;
|
|
||||||
const describedBy = [hintId, errorId].filter(Boolean).join(" ") || undefined;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="shl-field">
|
|
||||||
<label htmlFor={inputId}>{label}</label>
|
|
||||||
{children({ inputId, describedBy })}
|
|
||||||
{hint && (
|
|
||||||
<p id={hintId} className="shl-field-hint">
|
|
||||||
{hint}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{error && (
|
|
||||||
<p id={errorId} className="shl-field-error" role="alert">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TextFieldProps
|
|
||||||
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "aria-describedby"> {
|
|
||||||
label: string;
|
|
||||||
error?: string;
|
|
||||||
hint?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function TextField({ label, error, hint, ...inputProps }: TextFieldProps) {
|
|
||||||
return (
|
|
||||||
<FieldWrapper label={label} error={error} hint={hint}>
|
|
||||||
{({ inputId, describedBy }) => (
|
|
||||||
<input
|
|
||||||
id={inputId}
|
|
||||||
aria-describedby={describedBy}
|
|
||||||
aria-invalid={error ? true : undefined}
|
|
||||||
{...inputProps}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</FieldWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SelectFieldProps
|
|
||||||
extends Omit<SelectHTMLAttributes<HTMLSelectElement>, "id" | "aria-describedby"> {
|
|
||||||
label: string;
|
|
||||||
error?: string;
|
|
||||||
hint?: string;
|
|
||||||
children: ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SelectField({ label, error, hint, children, ...selectProps }: SelectFieldProps) {
|
|
||||||
return (
|
|
||||||
<FieldWrapper label={label} error={error} hint={hint}>
|
|
||||||
{({ inputId, describedBy }) => (
|
|
||||||
<select
|
|
||||||
id={inputId}
|
|
||||||
aria-describedby={describedBy}
|
|
||||||
aria-invalid={error ? true : undefined}
|
|
||||||
{...selectProps}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</select>
|
|
||||||
)}
|
|
||||||
</FieldWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CheckboxFieldProps
|
|
||||||
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "type"> {
|
|
||||||
label: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CheckboxField({ label, ...inputProps }: CheckboxFieldProps) {
|
|
||||||
const inputId = useId();
|
|
||||||
return (
|
|
||||||
<div className="shl-field shl-field-checkbox">
|
|
||||||
<input id={inputId} type="checkbox" {...inputProps} />
|
|
||||||
<label htmlFor={inputId}>{label}</label>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// Layout-Shell mit Navigation — SHL-01 Akzeptanzkriterium 1.
|
|
||||||
// Globale Navigation zeigt nur Module, die Core für Tenant/Benutzer freigibt (Backend entscheidet, UI blendet nur aus).
|
|
||||||
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { useI18n } from "../i18n/i18n";
|
|
||||||
import { useTheme } from "../theme/ThemeProvider";
|
|
||||||
|
|
||||||
export interface ModuleLink {
|
|
||||||
key: string;
|
|
||||||
label: string;
|
|
||||||
href: string;
|
|
||||||
active?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ShellProps {
|
|
||||||
modules: ModuleLink[];
|
|
||||||
tenantLabel: string;
|
|
||||||
children: ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Shell({ modules, tenantLabel, children }: ShellProps) {
|
|
||||||
const { scheme, toggle } = useTheme();
|
|
||||||
const { t } = useI18n();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="shl-shell">
|
|
||||||
<a className="shl-skip-link" href="#shl-main-content">
|
|
||||||
{t("shl.shell.skipToContent", "Zum Inhalt springen")}
|
|
||||||
</a>
|
|
||||||
<header className="shl-shell-header">
|
|
||||||
<nav aria-label={t("shl.shell.moduleNav", "Modul-Navigation")}>
|
|
||||||
<ul>
|
|
||||||
{modules.map((mod) => (
|
|
||||||
<li key={mod.key}>
|
|
||||||
<a href={mod.href} aria-current={mod.active ? "page" : undefined}>
|
|
||||||
{mod.label}
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
<div className="shl-shell-context">
|
|
||||||
<span className="shl-tenant-context">{tenantLabel}</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={toggle}
|
|
||||||
aria-label={
|
|
||||||
scheme === "light" ? t("shl.theme.toggleToDark") : t("shl.theme.toggleToLight")
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{scheme === "light" ? "🌙" : "☀️"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<main id="shl-main-content" className="shl-shell-content" tabIndex={-1}>
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
// Table-Basis-Komponente — SHL-01. WCAG: semantische <table>, scope auf Kopfzellen, sortierbare Spalten per Tastatur.
|
|
||||||
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { useI18n } from "../i18n/i18n";
|
|
||||||
|
|
||||||
export interface TableColumn<Row> {
|
|
||||||
key: string;
|
|
||||||
header: string;
|
|
||||||
render: (row: Row) => ReactNode;
|
|
||||||
sortable?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TableProps<Row> {
|
|
||||||
columns: TableColumn<Row>[];
|
|
||||||
rows: Row[];
|
|
||||||
rowKey: (row: Row) => string;
|
|
||||||
sortKey?: string;
|
|
||||||
sortDirection?: "asc" | "desc";
|
|
||||||
onSort?: (key: string) => void;
|
|
||||||
caption?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Table<Row>({
|
|
||||||
columns,
|
|
||||||
rows,
|
|
||||||
rowKey,
|
|
||||||
sortKey,
|
|
||||||
sortDirection,
|
|
||||||
onSort,
|
|
||||||
caption,
|
|
||||||
}: TableProps<Row>) {
|
|
||||||
const { t } = useI18n();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<table className="shl-table">
|
|
||||||
{caption && <caption>{caption}</caption>}
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
{columns.map((column) => {
|
|
||||||
const isSorted = column.key === sortKey;
|
|
||||||
const ariaSort = column.sortable
|
|
||||||
? isSorted
|
|
||||||
? sortDirection === "asc"
|
|
||||||
? "ascending"
|
|
||||||
: "descending"
|
|
||||||
: "none"
|
|
||||||
: undefined;
|
|
||||||
return (
|
|
||||||
<th key={column.key} scope="col" aria-sort={ariaSort}>
|
|
||||||
{column.sortable ? (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => onSort?.(column.key)}
|
|
||||||
className="shl-table-sort-button"
|
|
||||||
>
|
|
||||||
{column.header}
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
column.header
|
|
||||||
)}
|
|
||||||
</th>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{rows.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={columns.length}>{t("shl.table.noRows")}</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
rows.map((row) => (
|
|
||||||
<tr key={rowKey(row)}>
|
|
||||||
{columns.map((column) => (
|
|
||||||
<td key={column.key}>{column.render(row)}</td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// Toast-Basis-Komponente — SHL-01. WCAG: aria-live sorgt dafür, dass Screenreader Meldungen ansagen.
|
|
||||||
|
|
||||||
import { createContext, useCallback, useContext, useMemo, useState } from "react";
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { useI18n } from "../i18n/i18n";
|
|
||||||
|
|
||||||
export type ToastVariant = "info" | "success" | "danger" | "warning";
|
|
||||||
|
|
||||||
export interface ToastMessage {
|
|
||||||
id: string;
|
|
||||||
text: string;
|
|
||||||
variant: ToastVariant;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ToastContextValue {
|
|
||||||
toasts: ToastMessage[];
|
|
||||||
push: (text: string, variant?: ToastVariant) => void;
|
|
||||||
dismiss: (id: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ToastContext = createContext<ToastContextValue | null>(null);
|
|
||||||
|
|
||||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
|
||||||
const [toasts, setToasts] = useState<ToastMessage[]>([]);
|
|
||||||
const { t } = useI18n();
|
|
||||||
|
|
||||||
const dismiss = useCallback((id: string) => {
|
|
||||||
setToasts((current) => current.filter((toast) => toast.id !== id));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const push = useCallback((text: string, variant: ToastVariant = "info") => {
|
|
||||||
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
||||||
setToasts((current) => [...current, { id, text, variant }]);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const value = useMemo(() => ({ toasts, push, dismiss }), [toasts, push, dismiss]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ToastContext.Provider value={value}>
|
|
||||||
{children}
|
|
||||||
<div className="shl-toast-region" role="status" aria-live="polite" aria-atomic="false">
|
|
||||||
{toasts.map((toast) => (
|
|
||||||
<div key={toast.id} className={`shl-toast shl-toast-${toast.variant}`}>
|
|
||||||
<span>{toast.text}</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => dismiss(toast.id)}
|
|
||||||
aria-label={t("shl.toast.dismiss")}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</ToastContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useToast(): ToastContextValue {
|
|
||||||
const ctx = useContext(ToastContext);
|
|
||||||
if (!ctx) {
|
|
||||||
throw new Error("useToast muss innerhalb von <ToastProvider> aufgerufen werden");
|
|
||||||
}
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// i18n-Rahmen (mind. Deutsch/Englisch) — SHL-01 Akzeptanzkriterium 5.
|
|
||||||
// Liefert nur den Umschaltmechanismus + Basis-Komponenten-Texte.
|
|
||||||
// Modul-Frontends liefern ihre eigenen fachlichen Textbausteine über registerMessages(),
|
|
||||||
// statt einen eigenen i18n-Mechanismus zu bauen (siehe UI-UX-KONZEPT.md Abschnitt 4).
|
|
||||||
|
|
||||||
import { createContext, useContext, useMemo, useState } from "react";
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
|
|
||||||
export type Locale = "de" | "en";
|
|
||||||
|
|
||||||
type MessageDict = Record<string, string>;
|
|
||||||
type MessageBundle = Record<Locale, MessageDict>;
|
|
||||||
|
|
||||||
const baseMessages: MessageBundle = {
|
|
||||||
de: {
|
|
||||||
"shl.dialog.close": "Schließen",
|
|
||||||
"shl.toast.dismiss": "Meldung schließen",
|
|
||||||
"shl.table.noRows": "Keine Einträge vorhanden",
|
|
||||||
"shl.theme.toggleToLight": "Helles Erscheinungsbild",
|
|
||||||
"shl.theme.toggleToDark": "Dunkles Erscheinungsbild",
|
|
||||||
},
|
|
||||||
en: {
|
|
||||||
"shl.dialog.close": "Close",
|
|
||||||
"shl.toast.dismiss": "Dismiss message",
|
|
||||||
"shl.table.noRows": "No entries",
|
|
||||||
"shl.theme.toggleToLight": "Switch to light theme",
|
|
||||||
"shl.theme.toggleToDark": "Switch to dark theme",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Registry, in die Modul-Frontends ihre eigenen Textbausteine einhängen.
|
|
||||||
const registry: MessageBundle = { de: { ...baseMessages.de }, en: { ...baseMessages.en } };
|
|
||||||
|
|
||||||
export function registerMessages(locale: Locale, messages: MessageDict): void {
|
|
||||||
registry[locale] = { ...registry[locale], ...messages };
|
|
||||||
}
|
|
||||||
|
|
||||||
interface I18nContextValue {
|
|
||||||
locale: Locale;
|
|
||||||
setLocale: (locale: Locale) => void;
|
|
||||||
t: (key: string, fallback?: string) => string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const I18nContext = createContext<I18nContextValue | null>(null);
|
|
||||||
|
|
||||||
export function I18nProvider({
|
|
||||||
initialLocale = "de",
|
|
||||||
children,
|
|
||||||
}: {
|
|
||||||
initialLocale?: Locale;
|
|
||||||
children: ReactNode;
|
|
||||||
}) {
|
|
||||||
const [locale, setLocale] = useState<Locale>(initialLocale);
|
|
||||||
|
|
||||||
const value = useMemo<I18nContextValue>(
|
|
||||||
() => ({
|
|
||||||
locale,
|
|
||||||
setLocale,
|
|
||||||
t: (key: string, fallback?: string) => registry[locale][key] ?? fallback ?? key,
|
|
||||||
}),
|
|
||||||
[locale],
|
|
||||||
);
|
|
||||||
|
|
||||||
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useI18n(): I18nContextValue {
|
|
||||||
const ctx = useContext(I18nContext);
|
|
||||||
if (!ctx) {
|
|
||||||
throw new Error("useI18n muss innerhalb von <I18nProvider> aufgerufen werden");
|
|
||||||
}
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
// Öffentliche Schnittstelle des Pakets @nexarch/shl — Modul-Frontends importieren ausschließlich hierüber,
|
|
||||||
// nicht aus internen Unterpfaden (SHL-01 Akzeptanzkriterium 2: dokumentiert, versioniert, importierbar statt kopiert).
|
|
||||||
|
|
||||||
export { colorTokens, spacing, breakpoints, typography, cssVariables } from "./tokens/tokens";
|
|
||||||
export type { ColorScheme, ColorTokens } from "./tokens/tokens";
|
|
||||||
|
|
||||||
export { ThemeProvider, useTheme, currentColors } from "./theme/ThemeProvider";
|
|
||||||
|
|
||||||
export { I18nProvider, useI18n, registerMessages } from "./i18n/i18n";
|
|
||||||
export type { Locale } from "./i18n/i18n";
|
|
||||||
|
|
||||||
export { Shell } from "./components/Shell";
|
|
||||||
export type { ShellProps, ModuleLink } from "./components/Shell";
|
|
||||||
|
|
||||||
export { Dialog } from "./components/Dialog";
|
|
||||||
export type { DialogProps } from "./components/Dialog";
|
|
||||||
|
|
||||||
export { Table } from "./components/Table";
|
|
||||||
export type { TableProps, TableColumn } from "./components/Table";
|
|
||||||
|
|
||||||
export { TextField, SelectField, CheckboxField } from "./components/FormElements";
|
|
||||||
export type { TextFieldProps, SelectFieldProps, CheckboxFieldProps } from "./components/FormElements";
|
|
||||||
|
|
||||||
export { ToastProvider, useToast } from "./components/Toast";
|
|
||||||
export type { ToastMessage, ToastVariant } from "./components/Toast";
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@nexarch/shl",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"private": true,
|
|
||||||
"description": "NEXARCH UI-Shell & Design-System (Core SHL-01) — gemeinsames Paket für alle Modul-Frontends.",
|
|
||||||
"main": "index.ts",
|
|
||||||
"types": "index.ts",
|
|
||||||
"scripts": {
|
|
||||||
"test": "vitest run",
|
|
||||||
"typecheck": "tsc --noEmit"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": "^18.3.1",
|
|
||||||
"react-dom": "^18.3.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@testing-library/jest-dom": "^6.4.8",
|
|
||||||
"@testing-library/react": "^16.0.0",
|
|
||||||
"@types/react": "18.3.3",
|
|
||||||
"@types/react-dom": "18.3.0",
|
|
||||||
"jsdom": "^24.1.1",
|
|
||||||
"typescript": "5.5.3",
|
|
||||||
"vitest": "^2.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// Zentrales Theming (Hell/Dunkel) — SHL-01 Akzeptanzkriterium 6.
|
|
||||||
// Einzige Quelle für Hell/Dunkel-Werte; Modul-Frontends schalten nur um, bauen kein eigenes Theming.
|
|
||||||
|
|
||||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { colorTokens, cssVariables, type ColorScheme } from "../tokens/tokens";
|
|
||||||
|
|
||||||
const STORAGE_KEY = "nexarch-shl-theme";
|
|
||||||
|
|
||||||
interface ThemeContextValue {
|
|
||||||
scheme: ColorScheme;
|
|
||||||
setScheme: (scheme: ColorScheme) => void;
|
|
||||||
toggle: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
|
||||||
|
|
||||||
function readStoredScheme(): ColorScheme | null {
|
|
||||||
if (typeof window === "undefined") return null;
|
|
||||||
try {
|
|
||||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
|
||||||
return stored === "light" || stored === "dark" ? stored : null;
|
|
||||||
} catch {
|
|
||||||
// localStorage kann in privaten Fenstern/eingeschränkten Kontexten fehlschlagen — kein Absturz, nur kein persistierter Zustand.
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function systemPrefersDark(): boolean {
|
|
||||||
if (typeof window === "undefined" || !window.matchMedia) return false;
|
|
||||||
return window.matchMedia("(prefers-color-scheme: dark)").matches;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
|
||||||
const [scheme, setSchemeState] = useState<ColorScheme>("light");
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const stored = readStoredScheme();
|
|
||||||
setSchemeState(stored ?? (systemPrefersDark() ? "dark" : "light"));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setScheme = useCallback((next: ColorScheme) => {
|
|
||||||
setSchemeState(next);
|
|
||||||
try {
|
|
||||||
window.localStorage.setItem(STORAGE_KEY, next);
|
|
||||||
} catch {
|
|
||||||
// Speichern optional — Umschaltung funktioniert auch ohne Persistenz.
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const toggle = useCallback(() => {
|
|
||||||
setScheme(scheme === "light" ? "dark" : "light");
|
|
||||||
}, [scheme, setScheme]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const vars = cssVariables(scheme);
|
|
||||||
const root = document.documentElement;
|
|
||||||
for (const [key, value] of Object.entries(vars)) {
|
|
||||||
root.style.setProperty(key, value);
|
|
||||||
}
|
|
||||||
root.dataset.shlTheme = scheme;
|
|
||||||
}, [scheme]);
|
|
||||||
|
|
||||||
const value = useMemo(() => ({ scheme, setScheme, toggle }), [scheme, setScheme, toggle]);
|
|
||||||
|
|
||||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useTheme(): ThemeContextValue {
|
|
||||||
const ctx = useContext(ThemeContext);
|
|
||||||
if (!ctx) {
|
|
||||||
throw new Error("useTheme muss innerhalb von <ThemeProvider> aufgerufen werden");
|
|
||||||
}
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function currentColors(scheme: ColorScheme) {
|
|
||||||
return colorTokens[scheme];
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
// Design-Tokens: einzige Quelle für Farbe, Abstand, Typografie im gesamten Frontend-Verbund.
|
|
||||||
// Modul-Frontends importieren diese Tokens, überschreiben sie nicht lokal (SHL-01 Akzeptanzkriterium 3).
|
|
||||||
// Kontrastwerte sind gegen WCAG 2.1 AA geprüft (Akzeptanzkriterium 1/4): mindestens 4.5:1 für Fließtext.
|
|
||||||
|
|
||||||
export type ColorScheme = "light" | "dark";
|
|
||||||
|
|
||||||
export interface ColorTokens {
|
|
||||||
background: string;
|
|
||||||
surface: string;
|
|
||||||
surfaceRaised: string;
|
|
||||||
border: string;
|
|
||||||
textPrimary: string;
|
|
||||||
textSecondary: string;
|
|
||||||
accent: string;
|
|
||||||
accentContrast: string;
|
|
||||||
danger: string;
|
|
||||||
dangerContrast: string;
|
|
||||||
success: string;
|
|
||||||
warning: string;
|
|
||||||
focusRing: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Kontrastwerte geprüft: textPrimary auf background/surface >= 7:1, textSecondary >= 4.5:1,
|
|
||||||
// accentContrast auf accent >= 4.5:1 (WCAG AA, siehe SHL-01 Prüfung 3).
|
|
||||||
export const colorTokens: Record<ColorScheme, ColorTokens> = {
|
|
||||||
light: {
|
|
||||||
background: "#FFFFFF",
|
|
||||||
surface: "#F5F6F8",
|
|
||||||
surfaceRaised: "#FFFFFF",
|
|
||||||
border: "#D7DBE0",
|
|
||||||
textPrimary: "#14181F",
|
|
||||||
textSecondary: "#4B5563",
|
|
||||||
accent: "#1D4ED8",
|
|
||||||
accentContrast: "#FFFFFF",
|
|
||||||
danger: "#B91C1C",
|
|
||||||
dangerContrast: "#FFFFFF",
|
|
||||||
success: "#15803D",
|
|
||||||
warning: "#B45309",
|
|
||||||
focusRing: "#1D4ED8",
|
|
||||||
},
|
|
||||||
dark: {
|
|
||||||
background: "#0F1115",
|
|
||||||
surface: "#181B21",
|
|
||||||
surfaceRaised: "#20242C",
|
|
||||||
border: "#333944",
|
|
||||||
textPrimary: "#F2F4F7",
|
|
||||||
textSecondary: "#B4BAC4",
|
|
||||||
accent: "#5B8DEF",
|
|
||||||
accentContrast: "#0F1115",
|
|
||||||
danger: "#F87171",
|
|
||||||
dangerContrast: "#0F1115",
|
|
||||||
success: "#4ADE80",
|
|
||||||
warning: "#FBBF24",
|
|
||||||
focusRing: "#5B8DEF",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export const spacing = {
|
|
||||||
xs: "4px",
|
|
||||||
sm: "8px",
|
|
||||||
md: "16px",
|
|
||||||
lg: "24px",
|
|
||||||
xl: "32px",
|
|
||||||
xxl: "48px",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export const breakpoints = {
|
|
||||||
mobile: "0px",
|
|
||||||
tablet: "768px",
|
|
||||||
desktop: "1200px",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export const typography = {
|
|
||||||
fontFamily: "'Inter', 'Segoe UI', system-ui, sans-serif",
|
|
||||||
fontFamilyMono: "'JetBrains Mono', ui-monospace, monospace",
|
|
||||||
sizeSm: "13px",
|
|
||||||
sizeMd: "15px",
|
|
||||||
sizeLg: "18px",
|
|
||||||
sizeXl: "24px",
|
|
||||||
lineHeight: 1.5,
|
|
||||||
weightRegular: 400,
|
|
||||||
weightMedium: 500,
|
|
||||||
weightBold: 600,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export function cssVariables(scheme: ColorScheme): Record<string, string> {
|
|
||||||
const c = colorTokens[scheme];
|
|
||||||
const vars: Record<string, string> = {};
|
|
||||||
for (const [key, value] of Object.entries(c)) {
|
|
||||||
vars[`--shl-color-${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`] = value;
|
|
||||||
}
|
|
||||||
for (const [key, value] of Object.entries(spacing)) {
|
|
||||||
vars[`--shl-spacing-${key}`] = value;
|
|
||||||
}
|
|
||||||
return vars;
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2020",
|
|
||||||
"lib": ["dom", "dom.iterable", "esnext"],
|
|
||||||
"jsx": "react-jsx",
|
|
||||||
"module": "ESNext",
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"strict": true,
|
|
||||||
"declaration": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"noUnusedLocals": true,
|
|
||||||
"noUnusedParameters": true
|
|
||||||
},
|
|
||||||
"include": ["**/*.ts", "**/*.tsx"],
|
|
||||||
"exclude": ["node_modules"]
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { defineConfig } from "vitest/config";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
test: {
|
|
||||||
environment: "jsdom",
|
|
||||||
setupFiles: ["./vitest.setup.ts"],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import "@testing-library/jest-dom/vitest";
|
|
||||||
import { afterEach } from "vitest";
|
|
||||||
import { cleanup } from "@testing-library/react";
|
|
||||||
|
|
||||||
// Ohne explizites Cleanup bleiben zwischen den it()-Blöcken gerenderte Dialoge im DOM stehen
|
|
||||||
// (mehrere <html>/<body>-Bäume stapeln sich), wodurch getByRole() mehrere Treffer statt einen findet.
|
|
||||||
afterEach(() => {
|
|
||||||
cleanup();
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user